Search is not available for this dataset
repo
stringlengths
2
152
file
stringlengths
15
239
code
stringlengths
0
58.4M
file_length
int64
0
58.4M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
364 values
lightly
lightly-master/docs/source/tutorials_source/platform/tutorial_pizza_filter.py
# -*- coding: utf-8 -*- """ This documentation accompanies the video tutorial: `youtube link <https://youtu.be/imQWZ0HhYjk>`_ ############################################################################## .. _lightly-tutorial-pizza-filter: Tutorial 1: Curate Pizza Images =============================== .. warning:: **Tutorial is outdated** This tutorial uses a deprecated workflow of the Lightly Solution and will be removed in the future. Please refer to the `new documentation and tutorials <https://docs.lightly.ai>`_ instead. In this tutorial, you will learn how to upload a dataset to the Lightly platform, curate the data, and finally use the curated data to train a model. What you will learn ------------------- * Create and upload a new dataset * Curate a dataset using simple image metrics such as Width, Height, Sharpness, Signal-to-Noise ratio, File Size * Download images based on a tag from a dataset * Train an image classifier with the filtered dataset Requirements ------------ You can use your dataset or use the one we provide with this tutorial: :download:`pizzas.zip <../../../_data/pizzas.zip>`. If you use your dataset, please make sure the images are smaller than 2048 pixels with width and height, and you use less than 1000 images. .. note:: For this tutorial, we provide you with a small dataset of pizza images. We chose a small dataset because it's easy to ship and train. Upload the data --------------- We start by uploading the dataset to the `Lightly Platform <https://app.lightly.ai>`_. Create a new account if you do not have one yet. Go to your user Preferences and copy your API token. Now install lightly if you haven't already, and upload your dataset. .. code-block:: console # install Lightly pip3 install lightly # upload your DATA directory lightly-upload token=MY_TOKEN new_dataset_name='NEW_DATASET_NAME' input_dir='DATA/' Filter the dataset using metadata --------------------------------- Once the dataset is created and the images uploaded, you can head to 'Metadata' under the 'Analyze & Filter' menu. Move the sliders below the histograms to define filter rules for the dataset. Once you are satisfied with the filtered dataset, create a new tag using the tag menu on the left side. Download the curated dataset ---------------------------- We have filtered the dataset and want to download it now to train a model. Therefore, click on the download menu on the left. We can now download the filtered images by clicking on the 'DOWNLOAD IMAGES' button. In our case, the images are stored in the 'pizzas' folder. We now have to annotate the images. We can do this by moving the individual images to subfolders corresponding to the class. E.g. we move salami pizza images to the 'salami' folder and Margherita pizza images to the 'margherita' folder. ############################################################################## Training a model using the curated data --------------------------------------- """ # %% # Now we can start training our model using PyTorch Lightning # We start by importing the necessary dependencies import os import pytorch_lightning as pl import torch import torchmetrics from torch.utils.data import DataLoader, random_split from torchvision import transforms from torchvision.datasets import ImageFolder from torchvision.models import resnet18 # %% # We use a small batch size to make sure we can run the training on all kinds # of machines. Feel free to adjust the value to one that works on your machine. batch_size = 8 seed = 42 # %% # Set the seed to make the experiment reproducible pl.seed_everything(seed) # %% # Let's set up the augmentations for the train and the test data. train_transform = transforms.Compose( [ transforms.RandomResizedCrop((224, 224), scale=(0.7, 1.0)), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), ] ) # we don't do any resizing or mirroring for the test data test_transform = transforms.Compose( [ transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), ] ) # %% # We load our data and split it into train/test with a 70/30 ratio. # Please make sure the data folder contains subfolders for each class # # pizzas # L salami # L margherita dset = ImageFolder("pizzas", transform=train_transform) # to use the random_split method we need to obtain the length # of the train and test set full_len = len(dset) train_len = int(full_len * 0.7) test_len = int(full_len - train_len) dataset_train, dataset_test = random_split(dset, [train_len, test_len]) dataset_test.transforms = test_transform print("Training set consists of {} images".format(len(dataset_train))) print("Test set consists of {} images".format(len(dataset_test))) # %% # We can create our data loaders to fetch the data from the training and test # set and pack them into batches. dataloader_train = DataLoader(dataset_train, batch_size=batch_size, shuffle=True) dataloader_test = DataLoader(dataset_test, batch_size=batch_size) # %% # PyTorch Lightning allows us to pack the loss as well as the # optimizer into a single module. class MyModel(pl.LightningModule): def __init__(self, num_classes=2): super().__init__() self.save_hyperparameters() # load a pretrained resnet from torchvision self.model = resnet18(pretrained=True) # add new linear output layer (transfer learning) num_ftrs = self.model.fc.in_features self.model.fc = torch.nn.Linear(num_ftrs, 2) self.accuracy = torchmetrics.Accuracy() def forward(self, x): return self.model(x) def training_step(self, batch, batch_idx): x, y = batch y_hat = self(x) loss = torch.nn.functional.cross_entropy(y_hat, y) self.log("train_loss", loss, prog_bar=True) return loss def validation_step(self, batch, batch_idx): x, y = batch y_hat = self(x) loss = torch.nn.functional.cross_entropy(y_hat, y) y_hat = torch.nn.functional.softmax(y_hat, dim=1) self.accuracy(y_hat, y) self.log("val_loss", loss, on_epoch=True, prog_bar=True) self.log("val_acc", self.accuracy.compute(), on_epoch=True, prog_bar=True) def configure_optimizers(self): return torch.optim.SGD(self.model.fc.parameters(), lr=0.001, momentum=0.9) # %% # Finally, we can create the model and use the Trainer # to train our model. model = MyModel() trainer = pl.Trainer(max_epochs=4, devices=1) trainer.fit(model, dataloader_train, dataloader_test)
6,748
31.291866
112
py
lightly
lightly-master/docs/source/tutorials_source/platform/tutorial_sunflowers.py
""" .. _lightly-tutorial-sunflowers: Tutorial 2: Diversify the Sunflowers Dataset ============================================= .. warning:: **Tutorial is outdated** This tutorial uses a deprecated workflow of the Lightly Solution and will be removed in the future. Please refer to the `new documentation and tutorials <https://docs.lightly.ai>`_ instead. This tutorial highlights the basic functionality of selecting a subset in the web-app. You can use the CORESET selection strategy to choose a diverse subset of your dataset. This can be useful many purposes, e.g. for having a good subset of data to label or for creating a validation or test dataset that covers the complete sample space. Removing duplicate images can also help you in reducing bias and imbalances in your dataset. What you will learn -------------------- * Upload images and embeddings to the web-app via the Python package * Sample a diverse subset of your original dataset in the web-app * Download the filenames of the subset and use it to create a new local dataset folder. Requirements ------------- You can use your own dataset or the one we provide for this tutorial. The dataset we provide consists of 734 images of sunflowers. You can download it here :download:`Sunflowers.zip <../../../_data/Sunflowers.zip>`. To use the Lightly platform, we need to upload the dataset with embeddings to it. The first step for this is to train a self-supervised embedding model. Then, embed your dataset and lastly, upload the dataset and embeddings to the Lightly platform. These three steps can be done using a single terminal command from the lightly pip package: lightly-magic But first, we need to install lightly from the Python package index. .. code-block:: bash # Install lightly as a pip package pip install lightly .. code-block:: bash # The lightly-magic command first needs the input directory of your dataset. # Then it needs the information for how many epochs to train an embedding model on it. # If you want to use our pretrained model instead, set trainer.max_epochs=0. # Next, the embedding model is used to embed all images in the input directory # and saves the embeddings in a csv file. Last, a new dataset with the specified name # is created on the Lightly platform. lightly-magic input_dir="./Sunflowers" trainer.max_epochs=0 token=YOUR_TOKEN new_dataset_name="sunflowers_dataset" .. note:: The lightly-magic command with prefilled parameters is displayed in the web-app when you create a new dataset. `Head over there and try it! <https://app.lightly.ai>`_ For more information on the CLI commands refer to :ref:`lightly-command-line-tool` and :ref:`lightly-at-a-glance`. Create a Selection ------------------ Now, you have everything you need to create a selection of your dataset. For this, head to the *Embedding* page of your dataset. You should see a two-dimensional scatter plot of your embeddings. If you hover over the images, their thumbnails will appear. Can you find clusters of similar images? .. figure:: ../../tutorials_source/platform/images/sunflowers_scatter_before_selection.jpg :align: center :alt: Alt text :figclass: align-center You should see a two-dimensional scatter plot of your dataset as shown above. Hover over an image to view a thumbnail of it. There are also features like selecting and browsing some images and creating a tag from it. .. note:: We reduce the dimensionality of the embeddings to 2 dimensions before plotting them. You can switch between the PCA, tSNE and UMAP dimensionality reduction methods. Right above the scatter plot you should see a button "Create Sampling". Click on it to create a selection. You will need to configure the following settings: * **Embedding:** Choose the embedding to use for the selection. * **Sampling Strategy:** Choose the selection strategy to use. This will be one of: * CORESET: Selects samples which are diverse. * CORAL: Combines CORESET with uncertainty scores to do active learning. * RANDOM: Selects samples uniformly at random. * **Stopping Condition:** Indicate how many samples you want to keep. * **Name:** Give your selection a name. A new tag will be created under this name. .. figure:: ../../tutorials_source/platform/images/selection_create_request.png :align: center :alt: Alt text :figclass: align-center :figwidth: 400px Example of a filled out selection request in the web-app. After confirming your settings, a worker will start processing your request. Once it's done, the page switches to the new tag. You can see how the scatter plot now shows selected images and discarded images in a different color. Play around with the different selection strategies to see differences between the results. .. figure:: ../../tutorials_source/platform/images/sunflowers_scatter_after_selection.jpg :align: center :alt: Alt text :figclass: align-center After the selection you can see which samples were selected and which ones were discarded. Here, the green dots are part of the new tag while the gray ones are left away. Notice how the CORESET selection strategy selects an evenly spaced subset of images. .. note:: The CORESET selection strategy chooses the samples evenly spaced out in the 32-dimensional space. This does not necessarily translate into being evenly spaced out after the dimensionality reduction to 2 dimensions. Download selected samples ------------------------- Now you can use this diverse subset for your machine learning project. Just head over to the *Download* tag to see the different download options. Apart from downloading the filenames or the images directly, you can also use the lightly-download command to copy the files in the subset from your existing to a new directory. The CLI command with prefilled arguments is already provided. """
5,955
42.474453
117
py
lightly
lightly-master/examples/README.md
# Examples We provide example implementations for self-supervised learning models for PyTorch and PyTorch Lightning to give you a headstart when implementing your own model! All examples can be run from the terminal with: ``` python <path to example.py> ``` The examples should also run on [Google Colab](https://colab.research.google.com/). Remember to activate the GPU otherwise training will be very slow! You can simply copy paste the code and add the following line at the beginning of the notebook to install lightly: ``` !pip install lightly # add code from example below ``` You can find additional information for each model in our [Documentation](https://docs.lightly.ai//examples/models.html#)
715
31.545455
265
md
lightly
lightly-master/examples/pytorch/barlowtwins.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import torch import torchvision from torch import nn from lightly.loss import BarlowTwinsLoss from lightly.models.modules import BarlowTwinsProjectionHead from lightly.transforms.simclr_transform import SimCLRTransform class BarlowTwins(nn.Module): def __init__(self, backbone): super().__init__() self.backbone = backbone self.projection_head = BarlowTwinsProjectionHead(512, 2048, 2048) def forward(self, x): x = self.backbone(x).flatten(start_dim=1) z = self.projection_head(x) return z resnet = torchvision.models.resnet18() backbone = nn.Sequential(*list(resnet.children())[:-1]) model = BarlowTwins(backbone) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) transform = SimCLRTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) criterion = BarlowTwinsLoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.06) print("Starting Training") for epoch in range(10): total_loss = 0 for batch in dataloader: x0, x1 = batch[0] x0 = x0.to(device) x1 = x1.to(device) z0 = model(x0) z1 = model(x1) loss = criterion(z0, z1) total_loss += loss.detach() loss.backward() optimizer.step() optimizer.zero_grad() avg_loss = total_loss / len(dataloader) print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")
1,923
27.716418
77
py
lightly
lightly-master/examples/pytorch/byol.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import copy import torch import torchvision from torch import nn from lightly.loss import NegativeCosineSimilarity from lightly.models.modules import BYOLPredictionHead, BYOLProjectionHead from lightly.models.utils import deactivate_requires_grad, update_momentum from lightly.transforms.simclr_transform import SimCLRTransform from lightly.utils.scheduler import cosine_schedule class BYOL(nn.Module): def __init__(self, backbone): super().__init__() self.backbone = backbone self.projection_head = BYOLProjectionHead(512, 1024, 256) self.prediction_head = BYOLPredictionHead(256, 1024, 256) self.backbone_momentum = copy.deepcopy(self.backbone) self.projection_head_momentum = copy.deepcopy(self.projection_head) deactivate_requires_grad(self.backbone_momentum) deactivate_requires_grad(self.projection_head_momentum) def forward(self, x): y = self.backbone(x).flatten(start_dim=1) z = self.projection_head(y) p = self.prediction_head(z) return p def forward_momentum(self, x): y = self.backbone_momentum(x).flatten(start_dim=1) z = self.projection_head_momentum(y) z = z.detach() return z resnet = torchvision.models.resnet18() backbone = nn.Sequential(*list(resnet.children())[:-1]) model = BYOL(backbone) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) transform = SimCLRTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) criterion = NegativeCosineSimilarity() optimizer = torch.optim.SGD(model.parameters(), lr=0.06) epochs = 10 print("Starting Training") for epoch in range(epochs): total_loss = 0 momentum_val = cosine_schedule(epoch, epochs, 0.996, 1) for batch in dataloader: x0, x1 = batch[0] update_momentum(model.backbone, model.backbone_momentum, m=momentum_val) update_momentum( model.projection_head, model.projection_head_momentum, m=momentum_val ) x0 = x0.to(device) x1 = x1.to(device) p0 = model(x0) z0 = model.forward_momentum(x0) p1 = model(x1) z1 = model.forward_momentum(x1) loss = 0.5 * (criterion(p0, z1) + criterion(p1, z0)) total_loss += loss.detach() loss.backward() optimizer.step() optimizer.zero_grad() avg_loss = total_loss / len(dataloader) print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")
2,999
30.578947
81
py
lightly
lightly-master/examples/pytorch/dcl.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import torch import torchvision from torch import nn from lightly.loss import DCLLoss from lightly.models.modules import SimCLRProjectionHead from lightly.transforms.simclr_transform import SimCLRTransform class DCL(nn.Module): def __init__(self, backbone): super().__init__() self.backbone = backbone self.projection_head = SimCLRProjectionHead(512, 512, 128) def forward(self, x): x = self.backbone(x).flatten(start_dim=1) z = self.projection_head(x) return z resnet = torchvision.models.resnet18() backbone = nn.Sequential(*list(resnet.children())[:-1]) model = DCL(backbone) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) transform = SimCLRTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) criterion = DCLLoss() # or use the weighted DCLW loss: # criterion = DCLWLoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.06) print("Starting Training") for epoch in range(10): total_loss = 0 for batch in dataloader: x0, x1 = batch[0] x0 = x0.to(device) x1 = x1.to(device) z0 = model(x0) z1 = model(x1) loss = criterion(z0, z1) total_loss += loss.detach() loss.backward() optimizer.step() optimizer.zero_grad() avg_loss = total_loss / len(dataloader) print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")
1,938
26.7
77
py
lightly
lightly-master/examples/pytorch/dino.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import copy import torch import torchvision from torch import nn from lightly.loss import DINOLoss from lightly.models.modules import DINOProjectionHead from lightly.models.utils import deactivate_requires_grad, update_momentum from lightly.transforms.dino_transform import DINOTransform from lightly.utils.scheduler import cosine_schedule class DINO(torch.nn.Module): def __init__(self, backbone, input_dim): super().__init__() self.student_backbone = backbone self.student_head = DINOProjectionHead( input_dim, 512, 64, 2048, freeze_last_layer=1 ) self.teacher_backbone = copy.deepcopy(backbone) self.teacher_head = DINOProjectionHead(input_dim, 512, 64, 2048) deactivate_requires_grad(self.teacher_backbone) deactivate_requires_grad(self.teacher_head) def forward(self, x): y = self.student_backbone(x).flatten(start_dim=1) z = self.student_head(y) return z def forward_teacher(self, x): y = self.teacher_backbone(x).flatten(start_dim=1) z = self.teacher_head(y) return z resnet = torchvision.models.resnet18() backbone = nn.Sequential(*list(resnet.children())[:-1]) input_dim = 512 # instead of a resnet you can also use a vision transformer backbone as in the # original paper (you might have to reduce the batch size in this case): # backbone = torch.hub.load('facebookresearch/dino:main', 'dino_vits16', pretrained=False) # input_dim = backbone.embed_dim model = DINO(backbone, input_dim) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) transform = DINOTransform() # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=64, shuffle=True, drop_last=True, num_workers=8, ) criterion = DINOLoss( output_dim=2048, warmup_teacher_temp_epochs=5, ) # move loss to correct device because it also contains parameters criterion = criterion.to(device) optimizer = torch.optim.Adam(model.parameters(), lr=0.001) epochs = 10 print("Starting Training") for epoch in range(epochs): total_loss = 0 momentum_val = cosine_schedule(epoch, epochs, 0.996, 1) for batch in dataloader: views = batch[0] update_momentum(model.student_backbone, model.teacher_backbone, m=momentum_val) update_momentum(model.student_head, model.teacher_head, m=momentum_val) views = [view.to(device) for view in views] global_views = views[:2] teacher_out = [model.forward_teacher(view) for view in global_views] student_out = [model.forward(view) for view in views] loss = criterion(teacher_out, student_out, epoch=epoch) total_loss += loss.detach() loss.backward() # We only cancel gradients of student head. model.student_head.cancel_last_layer_gradients(current_epoch=epoch) optimizer.step() optimizer.zero_grad() avg_loss = total_loss / len(dataloader) print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")
3,561
32.603774
90
py
lightly
lightly-master/examples/pytorch/fastsiam.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import torch import torchvision from torch import nn from lightly.loss import NegativeCosineSimilarity from lightly.models.modules import SimSiamPredictionHead, SimSiamProjectionHead from lightly.transforms import FastSiamTransform class FastSiam(nn.Module): def __init__(self, backbone): super().__init__() self.backbone = backbone self.projection_head = SimSiamProjectionHead(512, 512, 128) self.prediction_head = SimSiamPredictionHead(128, 64, 128) def forward(self, x): f = self.backbone(x).flatten(start_dim=1) z = self.projection_head(f) p = self.prediction_head(z) z = z.detach() return z, p resnet = torchvision.models.resnet18() backbone = nn.Sequential(*list(resnet.children())[:-1]) model = FastSiam(backbone) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) transform = FastSiamTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) criterion = NegativeCosineSimilarity() optimizer = torch.optim.SGD(model.parameters(), lr=0.06) print("Starting Training") for epoch in range(10): total_loss = 0 for batch in dataloader: views = batch[0] features = [model(view.to(device)) for view in views] zs = torch.stack([z for z, _ in features]) ps = torch.stack([p for _, p in features]) loss = 0.0 for i in range(len(views)): mask = torch.arange(len(views), device=device) != i loss += criterion(ps[i], torch.mean(zs[mask], dim=0)) / len(views) total_loss += loss.detach() loss.backward() optimizer.step() optimizer.zero_grad() avg_loss = total_loss / len(dataloader) print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")
2,294
30.013514
79
py
lightly
lightly-master/examples/pytorch/ijepa.py
import copy import torch import torchvision from torch import nn from torch.nn import functional as F from tqdm import tqdm from lightly.data.collate import IJEPAMaskCollator from lightly.models import utils from lightly.models.modules.ijepa import IJEPABackbone, IJEPAPredictor from lightly.transforms.ijepa_transform import IJEPATransform class IJEPA(nn.Module): def __init__(self, vit_encoder, vit_predictor, momentum_scheduler): super().__init__() self.encoder = IJEPABackbone.from_vit(vit_encoder) self.predictor = IJEPAPredictor.from_vit_encoder( vit_predictor.encoder, (vit_predictor.image_size // vit_predictor.patch_size) ** 2, ) self.target_encoder = copy.deepcopy(self.encoder) self.momentum_scheduler = momentum_scheduler def forward_target(self, imgs, masks_enc, masks_pred): with torch.no_grad(): h = self.target_encoder(imgs) h = F.layer_norm(h, (h.size(-1),)) # normalize over feature-dim B = len(h) # -- create targets (masked regions of h) h = utils.apply_masks(h, masks_pred) h = utils.repeat_interleave_batch(h, B, repeat=len(masks_enc)) return h def forward_context(self, imgs, masks_enc, masks_pred): z = self.encoder(imgs, masks_enc) z = self.predictor(z, masks_enc, masks_pred) return z def forward(self, imgs, masks_enc, masks_pred): z = self.forward_context(imgs, masks_enc, masks_pred) h = self.forward_target(imgs, masks_enc, masks_pred) return z, h def update_target_encoder( self, ): with torch.no_grad(): m = next(self.momentum_scheduler) for param_q, param_k in zip( self.encoder.parameters(), self.target_encoder.parameters() ): param_k.data.mul_(m).add_((1.0 - m) * param_q.detach().data) collator = IJEPAMaskCollator( input_size=(224, 224), patch_size=32, ) transform = IJEPATransform() # we ignore object detection annotations by setting target_transform to return 0 # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) data_loader = torch.utils.data.DataLoader( dataset, collate_fn=collator, batch_size=10, persistent_workers=False ) ema = (0.996, 1.0) ipe_scale = 1.0 ipe = len(data_loader) num_epochs = 10 momentum_scheduler = ( ema[0] + i * (ema[1] - ema[0]) / (ipe * num_epochs * ipe_scale) for i in range(int(ipe * num_epochs * ipe_scale) + 1) ) vit_for_predictor = torchvision.models.vit_b_32(pretrained=False) vit_for_embedder = torchvision.models.vit_b_32(pretrained=False) model = IJEPA(vit_for_embedder, vit_for_predictor, momentum_scheduler) criterion = nn.SmoothL1Loss() optimizer = torch.optim.AdamW(model.parameters(), lr=1.5e-4) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) print("Starting Training") for epoch in range(num_epochs): total_loss = 0 for udata, masks_enc, masks_pred in tqdm(data_loader): def load_imgs(): # -- unsupervised imgs imgs = udata[0].to(device, non_blocking=True) masks_1 = [u.to(device, non_blocking=True) for u in masks_enc] masks_2 = [u.to(device, non_blocking=True) for u in masks_pred] return (imgs, masks_1, masks_2) imgs, masks_enc, masks_pred = load_imgs() z, h = model(imgs, masks_enc, masks_pred) loss = criterion(z, h) total_loss += loss.detach() loss.backward() optimizer.step() optimizer.zero_grad() model.update_target_encoder() avg_loss = total_loss / len(data_loader) print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")
3,957
32.542373
80
py
lightly
lightly-master/examples/pytorch/mae.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import torch import torchvision from torch import nn from lightly.models import utils from lightly.models.modules import masked_autoencoder from lightly.transforms.mae_transform import MAETransform class MAE(nn.Module): def __init__(self, vit): super().__init__() decoder_dim = 512 self.mask_ratio = 0.75 self.patch_size = vit.patch_size self.sequence_length = vit.seq_length self.mask_token = nn.Parameter(torch.zeros(1, 1, decoder_dim)) self.backbone = masked_autoencoder.MAEBackbone.from_vit(vit) self.decoder = masked_autoencoder.MAEDecoder( seq_length=vit.seq_length, num_layers=1, num_heads=16, embed_input_dim=vit.hidden_dim, hidden_dim=decoder_dim, mlp_dim=decoder_dim * 4, out_dim=vit.patch_size**2 * 3, dropout=0, attention_dropout=0, ) def forward_encoder(self, images, idx_keep=None): return self.backbone.encode(images, idx_keep) def forward_decoder(self, x_encoded, idx_keep, idx_mask): # build decoder input batch_size = x_encoded.shape[0] x_decode = self.decoder.embed(x_encoded) x_masked = utils.repeat_token( self.mask_token, (batch_size, self.sequence_length) ) x_masked = utils.set_at_index(x_masked, idx_keep, x_decode.type_as(x_masked)) # decoder forward pass x_decoded = self.decoder.decode(x_masked) # predict pixel values for masked tokens x_pred = utils.get_at_index(x_decoded, idx_mask) x_pred = self.decoder.predict(x_pred) return x_pred def forward(self, images): batch_size = images.shape[0] idx_keep, idx_mask = utils.random_token_mask( size=(batch_size, self.sequence_length), mask_ratio=self.mask_ratio, device=images.device, ) x_encoded = self.forward_encoder(images, idx_keep) x_pred = self.forward_decoder(x_encoded, idx_keep, idx_mask) # get image patches for masked tokens patches = utils.patchify(images, self.patch_size) # must adjust idx_mask for missing class token target = utils.get_at_index(patches, idx_mask - 1) return x_pred, target vit = torchvision.models.vit_b_32(pretrained=False) model = MAE(vit) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) transform = MAETransform() # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) criterion = nn.MSELoss() optimizer = torch.optim.AdamW(model.parameters(), lr=1.5e-4) print("Starting Training") for epoch in range(10): total_loss = 0 for batch in dataloader: views = batch[0] images = views[0].to(device) # views contains only a single view predictions, targets = model(images) loss = criterion(predictions, targets) total_loss += loss.detach() loss.backward() optimizer.step() optimizer.zero_grad() avg_loss = total_loss / len(dataloader) print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")
3,762
31.721739
85
py
lightly
lightly-master/examples/pytorch/moco.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import copy import torch import torchvision from torch import nn from lightly.loss import NTXentLoss from lightly.models.modules import MoCoProjectionHead from lightly.models.utils import deactivate_requires_grad, update_momentum from lightly.transforms.moco_transform import MoCoV2Transform from lightly.utils.scheduler import cosine_schedule class MoCo(nn.Module): def __init__(self, backbone): super().__init__() self.backbone = backbone self.projection_head = MoCoProjectionHead(512, 512, 128) self.backbone_momentum = copy.deepcopy(self.backbone) self.projection_head_momentum = copy.deepcopy(self.projection_head) deactivate_requires_grad(self.backbone_momentum) deactivate_requires_grad(self.projection_head_momentum) def forward(self, x): query = self.backbone(x).flatten(start_dim=1) query = self.projection_head(query) return query def forward_momentum(self, x): key = self.backbone_momentum(x).flatten(start_dim=1) key = self.projection_head_momentum(key).detach() return key resnet = torchvision.models.resnet18() backbone = nn.Sequential(*list(resnet.children())[:-1]) model = MoCo(backbone) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) transform = MoCoV2Transform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) criterion = NTXentLoss(memory_bank_size=4096) optimizer = torch.optim.SGD(model.parameters(), lr=0.06) epochs = 10 print("Starting Training") for epoch in range(epochs): total_loss = 0 momentum_val = cosine_schedule(epoch, epochs, 0.996, 1) for batch in dataloader: x_query, x_key = batch[0] update_momentum(model.backbone, model.backbone_momentum, m=momentum_val) update_momentum( model.projection_head, model.projection_head_momentum, m=momentum_val ) x_query = x_query.to(device) x_key = x_key.to(device) query = model(x_query) key = model.forward_momentum(x_key) loss = criterion(query, key) total_loss += loss.detach() loss.backward() optimizer.step() optimizer.zero_grad() avg_loss = total_loss / len(dataloader) print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")
2,827
30.076923
81
py
lightly
lightly-master/examples/pytorch/msn.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import copy import torch import torchvision from torch import nn from lightly.loss import MSNLoss from lightly.models import utils from lightly.models.modules.heads import MSNProjectionHead from lightly.models.modules.masked_autoencoder import MAEBackbone from lightly.transforms.msn_transform import MSNTransform class MSN(nn.Module): def __init__(self, vit): super().__init__() self.mask_ratio = 0.15 self.backbone = MAEBackbone.from_vit(vit) self.projection_head = MSNProjectionHead(input_dim=384) self.anchor_backbone = copy.deepcopy(self.backbone) self.anchor_projection_head = copy.deepcopy(self.projection_head) utils.deactivate_requires_grad(self.backbone) utils.deactivate_requires_grad(self.projection_head) self.prototypes = nn.Linear(256, 1024, bias=False).weight def forward(self, images): out = self.backbone(images) return self.projection_head(out) def forward_masked(self, images): batch_size, _, _, width = images.shape seq_length = (width // self.anchor_backbone.patch_size) ** 2 idx_keep, _ = utils.random_token_mask( size=(batch_size, seq_length), mask_ratio=self.mask_ratio, device=images.device, ) out = self.anchor_backbone(images, idx_keep) return self.anchor_projection_head(out) # ViT small configuration (ViT-S/16) vit = torchvision.models.VisionTransformer( image_size=224, patch_size=16, num_layers=12, num_heads=6, hidden_dim=384, mlp_dim=384 * 4, ) model = MSN(vit) # or use a torchvision ViT backbone: # vit = torchvision.models.vit_b_32(pretrained=False) # model = MSN(vit) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) transform = MSNTransform() # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=64, shuffle=True, drop_last=True, num_workers=8, ) criterion = MSNLoss() params = [ *list(model.anchor_backbone.parameters()), *list(model.anchor_projection_head.parameters()), model.prototypes, ] optimizer = torch.optim.AdamW(params, lr=1.5e-4) print("Starting Training") for epoch in range(10): total_loss = 0 for batch in dataloader: views = batch[0] utils.update_momentum(model.anchor_backbone, model.backbone, 0.996) utils.update_momentum( model.anchor_projection_head, model.projection_head, 0.996 ) views = [view.to(device, non_blocking=True) for view in views] targets = views[0] anchors = views[1] anchors_focal = torch.concat(views[2:], dim=0) targets_out = model.backbone(targets) targets_out = model.projection_head(targets_out) anchors_out = model.forward_masked(anchors) anchors_focal_out = model.forward_masked(anchors_focal) anchors_out = torch.cat([anchors_out, anchors_focal_out], dim=0) loss = criterion(anchors_out, targets_out, model.prototypes.data) total_loss += loss.detach() loss.backward() optimizer.step() optimizer.zero_grad() avg_loss = total_loss / len(dataloader) print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")
3,790
30.07377
80
py
lightly
lightly-master/examples/pytorch/nnclr.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import torch import torchvision from torch import nn from lightly.loss import NTXentLoss from lightly.models.modules import ( NNCLRPredictionHead, NNCLRProjectionHead, NNMemoryBankModule, ) from lightly.transforms.simclr_transform import SimCLRTransform class NNCLR(nn.Module): def __init__(self, backbone): super().__init__() self.backbone = backbone self.projection_head = NNCLRProjectionHead(512, 512, 128) self.prediction_head = NNCLRPredictionHead(128, 512, 128) def forward(self, x): y = self.backbone(x).flatten(start_dim=1) z = self.projection_head(y) p = self.prediction_head(z) z = z.detach() return z, p resnet = torchvision.models.resnet18() backbone = nn.Sequential(*list(resnet.children())[:-1]) model = NNCLR(backbone) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) memory_bank = NNMemoryBankModule(size=4096) memory_bank.to(device) transform = SimCLRTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) criterion = NTXentLoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.06) print("Starting Training") for epoch in range(10): total_loss = 0 for batch in dataloader: x0, x1 = batch[0] x0 = x0.to(device) x1 = x1.to(device) z0, p0 = model(x0) z1, p1 = model(x1) z0 = memory_bank(z0, update=False) z1 = memory_bank(z1, update=True) loss = 0.5 * (criterion(z0, p1) + criterion(z1, p0)) total_loss += loss.detach() loss.backward() optimizer.step() optimizer.zero_grad() avg_loss = total_loss / len(dataloader) print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")
2,263
27.3
77
py
lightly
lightly-master/examples/pytorch/pmsn.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import copy import torch import torchvision from torch import nn from lightly.loss import PMSNLoss from lightly.models import utils from lightly.models.modules.heads import MSNProjectionHead from lightly.models.modules.masked_autoencoder import MAEBackbone from lightly.transforms import MSNTransform class PMSN(nn.Module): def __init__(self, vit): super().__init__() self.mask_ratio = 0.15 self.backbone = MAEBackbone.from_vit(vit) self.projection_head = MSNProjectionHead(384) self.anchor_backbone = copy.deepcopy(self.backbone) self.anchor_projection_head = copy.deepcopy(self.projection_head) utils.deactivate_requires_grad(self.backbone) utils.deactivate_requires_grad(self.projection_head) self.prototypes = nn.Linear(256, 1024, bias=False).weight def forward(self, images): out = self.backbone(images) return self.projection_head(out) def forward_masked(self, images): batch_size, _, _, width = images.shape seq_length = (width // self.anchor_backbone.patch_size) ** 2 idx_keep, _ = utils.random_token_mask( size=(batch_size, seq_length), mask_ratio=self.mask_ratio, device=images.device, ) out = self.anchor_backbone(images, idx_keep) return self.anchor_projection_head(out) # ViT small configuration (ViT-S/16) vit = torchvision.models.VisionTransformer( image_size=224, patch_size=16, num_layers=12, num_heads=6, hidden_dim=384, mlp_dim=384 * 4, ) model = PMSN(vit) # # or use a torchvision ViT backbone: # vit = torchvision.models.vit_b_32(pretrained=False) # model = PMSN(vit) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) transform = MSNTransform() # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=64, shuffle=True, drop_last=True, num_workers=8, ) criterion = PMSNLoss() params = [ *list(model.anchor_backbone.parameters()), *list(model.anchor_projection_head.parameters()), model.prototypes, ] optimizer = torch.optim.AdamW(params, lr=1.5e-4) print("Starting Training") for epoch in range(10): total_loss = 0 for batch in dataloader: views = batch[0] utils.update_momentum(model.anchor_backbone, model.backbone, 0.996) utils.update_momentum( model.anchor_projection_head, model.projection_head, 0.996 ) views = [view.to(device, non_blocking=True) for view in views] targets = views[0] anchors = views[1] anchors_focal = torch.concat(views[2:], dim=0) targets_out = model.backbone(targets) targets_out = model.projection_head(targets_out) anchors_out = model.forward_masked(anchors) anchors_focal_out = model.forward_masked(anchors_focal) anchors_out = torch.cat([anchors_out, anchors_focal_out], dim=0) loss = criterion(anchors_out, targets_out, model.prototypes.data) total_loss += loss.detach() loss.backward() optimizer.step() optimizer.zero_grad() avg_loss = total_loss / len(dataloader) print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")
3,773
29.934426
80
py
lightly
lightly-master/examples/pytorch/simclr.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import torch import torchvision from torch import nn from lightly.loss import NTXentLoss from lightly.models.modules import SimCLRProjectionHead from lightly.transforms.simclr_transform import SimCLRTransform class SimCLR(nn.Module): def __init__(self, backbone): super().__init__() self.backbone = backbone self.projection_head = SimCLRProjectionHead(512, 512, 128) def forward(self, x): x = self.backbone(x).flatten(start_dim=1) z = self.projection_head(x) return z resnet = torchvision.models.resnet18() backbone = nn.Sequential(*list(resnet.children())[:-1]) model = SimCLR(backbone) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) transform = SimCLRTransform(input_size=32, gaussian_blur=0.0) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) criterion = NTXentLoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.06) print("Starting Training") for epoch in range(10): total_loss = 0 for batch in dataloader: x0, x1 = batch[0] x0 = x0.to(device) x1 = x1.to(device) z0 = model(x0) z1 = model(x1) loss = criterion(z0, z1) total_loss += loss.detach() loss.backward() optimizer.step() optimizer.zero_grad() avg_loss = total_loss / len(dataloader) print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")
1,910
27.522388
77
py
lightly
lightly-master/examples/pytorch/simmim.py
import torch import torchvision from torch import nn from lightly.models import utils from lightly.models.modules import masked_autoencoder from lightly.transforms.mae_transform import MAETransform # Same transform as MAE class SimMIM(nn.Module): def __init__(self, vit): super().__init__() decoder_dim = vit.hidden_dim self.mask_ratio = 0.75 self.patch_size = vit.patch_size self.sequence_length = vit.seq_length self.mask_token = nn.Parameter(torch.zeros(1, 1, decoder_dim)) # same backbone as MAE self.backbone = masked_autoencoder.MAEBackbone.from_vit(vit) # the decoder is a simple linear layer self.decoder = nn.Linear(vit.hidden_dim, vit.patch_size**2 * 3) def forward_encoder(self, images, batch_size, idx_mask): # pass all the tokens to the encoder, both masked and non masked ones tokens = self.backbone.images_to_tokens(images, prepend_class_token=True) tokens_masked = utils.mask_at_index(tokens, idx_mask, self.mask_token) return self.backbone.encoder(tokens_masked) def forward_decoder(self, x_encoded): return self.decoder(x_encoded) def forward(self, images): batch_size = images.shape[0] idx_keep, idx_mask = utils.random_token_mask( size=(batch_size, self.sequence_length), mask_ratio=self.mask_ratio, device=images.device, ) # Encoding... x_encoded = self.forward_encoder(images, batch_size, idx_mask) x_encoded_masked = utils.get_at_index(x_encoded, idx_mask) # Decoding... x_out = self.forward_decoder(x_encoded_masked) # get image patches for masked tokens patches = utils.patchify(images, self.patch_size) # must adjust idx_mask for missing class token target = utils.get_at_index(patches, idx_mask - 1) return x_out, target vit = torchvision.models.vit_b_32(pretrained=False) model = SimMIM(vit) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) transform = MAETransform() # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=8, shuffle=True, drop_last=True, num_workers=8, ) # L1 loss as paper suggestion criterion = nn.L1Loss() optimizer = torch.optim.AdamW(model.parameters(), lr=1.5e-4) print("Starting Training") for epoch in range(10): total_loss = 0 for batch in dataloader: views = batch[0] images = views[0].to(device) # views contains only a single view predictions, targets = model(images) loss = criterion(predictions, targets) total_loss += loss.detach() loss.backward() optimizer.step() optimizer.zero_grad() avg_loss = total_loss / len(dataloader) print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")
3,213
30.203883
82
py
lightly
lightly-master/examples/pytorch/simsiam.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import torch import torchvision from torch import nn from lightly.loss import NegativeCosineSimilarity from lightly.models.modules import SimSiamPredictionHead, SimSiamProjectionHead from lightly.transforms import SimSiamTransform class SimSiam(nn.Module): def __init__(self, backbone): super().__init__() self.backbone = backbone self.projection_head = SimSiamProjectionHead(512, 512, 128) self.prediction_head = SimSiamPredictionHead(128, 64, 128) def forward(self, x): f = self.backbone(x).flatten(start_dim=1) z = self.projection_head(f) p = self.prediction_head(z) z = z.detach() return z, p resnet = torchvision.models.resnet18() backbone = nn.Sequential(*list(resnet.children())[:-1]) model = SimSiam(backbone) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) transform = SimSiamTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) criterion = NegativeCosineSimilarity() optimizer = torch.optim.SGD(model.parameters(), lr=0.06) print("Starting Training") for epoch in range(10): total_loss = 0 for batch in dataloader: x0, x1 = batch[0] x0 = x0.to(device) x1 = x1.to(device) z0, p0 = model(x0) z1, p1 = model(x1) loss = 0.5 * (criterion(z0, p1) + criterion(z1, p0)) total_loss += loss.detach() loss.backward() optimizer.step() optimizer.zero_grad() avg_loss = total_loss / len(dataloader) print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")
2,096
28.957143
79
py
lightly
lightly-master/examples/pytorch/smog.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import copy import torch import torchvision from sklearn.cluster import KMeans from torch import nn from lightly.loss.memory_bank import MemoryBankModule from lightly.models import utils from lightly.models.modules.heads import ( SMoGPredictionHead, SMoGProjectionHead, SMoGPrototypes, ) from lightly.transforms.smog_transform import SMoGTransform class SMoGModel(nn.Module): def __init__(self, backbone): super().__init__() self.backbone = backbone self.projection_head = SMoGProjectionHead(512, 2048, 128) self.prediction_head = SMoGPredictionHead(128, 2048, 128) self.backbone_momentum = copy.deepcopy(self.backbone) self.projection_head_momentum = copy.deepcopy(self.projection_head) utils.deactivate_requires_grad(self.backbone_momentum) utils.deactivate_requires_grad(self.projection_head_momentum) self.n_groups = 300 self.smog = SMoGPrototypes( group_features=torch.rand(self.n_groups, 128), beta=0.99 ) def _cluster_features(self, features: torch.Tensor) -> torch.Tensor: # clusters the features using sklearn # (note: faiss is probably more efficient) features = features.cpu().numpy() kmeans = KMeans(self.n_groups).fit(features) clustered = torch.from_numpy(kmeans.cluster_centers_).float() clustered = torch.nn.functional.normalize(clustered, dim=1) return clustered def reset_group_features(self, memory_bank): # see https://arxiv.org/pdf/2207.06167.pdf Table 7b) features = memory_bank.bank group_features = self._cluster_features(features.t()) self.smog.set_group_features(group_features) def reset_momentum_weights(self): # see https://arxiv.org/pdf/2207.06167.pdf Table 7b) self.backbone_momentum = copy.deepcopy(self.backbone) self.projection_head_momentum = copy.deepcopy(self.projection_head) utils.deactivate_requires_grad(self.backbone_momentum) utils.deactivate_requires_grad(self.projection_head_momentum) def forward(self, x): features = self.backbone(x).flatten(start_dim=1) encoded = self.projection_head(features) predicted = self.prediction_head(encoded) return encoded, predicted def forward_momentum(self, x): features = self.backbone_momentum(x).flatten(start_dim=1) encoded = self.projection_head_momentum(features) return encoded batch_size = 256 resnet = torchvision.models.resnet18() backbone = nn.Sequential(*list(resnet.children())[:-1]) model = SMoGModel(backbone) # memory bank because we reset the group features every 300 iterations memory_bank_size = 300 * batch_size memory_bank = MemoryBankModule(size=memory_bank_size) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) transform = SMoGTransform( crop_sizes=(32, 32), crop_counts=(1, 1), gaussian_blur_probs=(0.0, 0.0), crop_min_scales=(0.2, 0.2), crop_max_scales=(1.0, 1.0), ) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) criterion = nn.CrossEntropyLoss() optimizer = torch.optim.SGD( model.parameters(), lr=0.01, momentum=0.9, weight_decay=1e-6 ) global_step = 0 print("Starting Training") for epoch in range(10): total_loss = 0 for batch_idx, batch in enumerate(dataloader): (x0, x1) = batch[0] if batch_idx % 2: # swap batches every second iteration x1, x0 = x0, x1 x0 = x0.to(device) x1 = x1.to(device) if global_step > 0 and global_step % 300 == 0: # reset group features and weights every 300 iterations model.reset_group_features(memory_bank=memory_bank) model.reset_momentum_weights() else: # update momentum utils.update_momentum(model.backbone, model.backbone_momentum, 0.99) utils.update_momentum( model.projection_head, model.projection_head_momentum, 0.99 ) x0_encoded, x0_predicted = model(x0) x1_encoded = model.forward_momentum(x1) # update group features and get group assignments assignments = model.smog.assign_groups(x1_encoded) group_features = model.smog.get_updated_group_features(x0_encoded) logits = model.smog(x0_predicted, group_features, temperature=0.1) model.smog.set_group_features(group_features) loss = criterion(logits, assignments) # use memory bank to periodically reset the group features with k-means memory_bank(x0_encoded, update=True) loss.backward() optimizer.step() optimizer.zero_grad() global_step += 1 total_loss += loss.detach() avg_loss = total_loss / len(dataloader) print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")
5,393
32.092025
80
py
lightly
lightly-master/examples/pytorch/swav.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import torch import torchvision from torch import nn from lightly.loss import SwaVLoss from lightly.models.modules import SwaVProjectionHead, SwaVPrototypes from lightly.transforms.swav_transform import SwaVTransform class SwaV(nn.Module): def __init__(self, backbone): super().__init__() self.backbone = backbone self.projection_head = SwaVProjectionHead(512, 512, 128) self.prototypes = SwaVPrototypes(128, n_prototypes=512) def forward(self, x): x = self.backbone(x).flatten(start_dim=1) x = self.projection_head(x) x = nn.functional.normalize(x, dim=1, p=2) p = self.prototypes(x) return p resnet = torchvision.models.resnet18() backbone = nn.Sequential(*list(resnet.children())[:-1]) model = SwaV(backbone) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) transform = SwaVTransform() # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=128, shuffle=True, drop_last=True, num_workers=8, ) criterion = SwaVLoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.001) print("Starting Training") for epoch in range(10): total_loss = 0 for batch in dataloader: views = batch[0] model.prototypes.normalize() multi_crop_features = [model(view.to(device)) for view in views] high_resolution = multi_crop_features[:2] low_resolution = multi_crop_features[2:] loss = criterion(high_resolution, low_resolution) total_loss += loss.detach() loss.backward() optimizer.step() optimizer.zero_grad() avg_loss = total_loss / len(dataloader) print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")
2,268
29.662162
80
py
lightly
lightly-master/examples/pytorch/swav_queue.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import torch import torchvision from torch import nn from lightly.loss import SwaVLoss from lightly.loss.memory_bank import MemoryBankModule from lightly.models.modules import SwaVProjectionHead, SwaVPrototypes from lightly.transforms.swav_transform import SwaVTransform class SwaV(nn.Module): def __init__(self, backbone): super().__init__() self.backbone = backbone self.projection_head = SwaVProjectionHead(512, 512, 128) self.prototypes = SwaVPrototypes(128, 512, 1) self.start_queue_at_epoch = 2 self.queues = nn.ModuleList([MemoryBankModule(size=3840) for _ in range(2)]) def forward(self, high_resolution, low_resolution, epoch): self.prototypes.normalize() high_resolution_features = [self._subforward(x) for x in high_resolution] low_resolution_features = [self._subforward(x) for x in low_resolution] high_resolution_prototypes = [ self.prototypes(x, epoch) for x in high_resolution_features ] low_resolution_prototypes = [ self.prototypes(x, epoch) for x in low_resolution_features ] queue_prototypes = self._get_queue_prototypes(high_resolution_features, epoch) return high_resolution_prototypes, low_resolution_prototypes, queue_prototypes def _subforward(self, input): features = self.backbone(input).flatten(start_dim=1) features = self.projection_head(features) features = nn.functional.normalize(features, dim=1, p=2) return features @torch.no_grad() def _get_queue_prototypes(self, high_resolution_features, epoch): if len(high_resolution_features) != len(self.queues): raise ValueError( f"The number of queues ({len(self.queues)}) should be equal to the number of high " f"resolution inputs ({len(high_resolution_features)}). Set `n_queues` accordingly." ) # Get the queue features queue_features = [] for i in range(len(self.queues)): _, features = self.queues[i](high_resolution_features[i], update=True) # Queue features are in (num_ftrs X queue_length) shape, while the high res # features are in (batch_size X num_ftrs). Swap the axes for interoperability. features = torch.permute(features, (1, 0)) queue_features.append(features) # If loss calculation with queue prototypes starts at a later epoch, # just queue the features and return None instead of queue prototypes. if self.start_queue_at_epoch > 0 and epoch < self.start_queue_at_epoch: return None # Assign prototypes queue_prototypes = [self.prototypes(x, epoch) for x in queue_features] return queue_prototypes resnet = torchvision.models.resnet18() backbone = nn.Sequential(*list(resnet.children())[:-1]) model = SwaV(backbone) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) transform = SwaVTransform() # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=128, shuffle=True, drop_last=True, num_workers=8, ) criterion = SwaVLoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.001) print("Starting Training") for epoch in range(10): total_loss = 0 for batch in dataloader: views = batch[0] views = [view.to(device) for view in views] high_resolution, low_resolution = views[:2], views[2:] high_resolution, low_resolution, queue = model( high_resolution, low_resolution, epoch ) loss = criterion(high_resolution, low_resolution, queue) total_loss += loss.detach() loss.backward() optimizer.step() optimizer.zero_grad() avg_loss = total_loss / len(dataloader) print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")
4,433
35.644628
99
py
lightly
lightly-master/examples/pytorch/tico.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import copy import torch import torchvision from torch import nn from lightly.loss.tico_loss import TiCoLoss from lightly.models.modules.heads import TiCoProjectionHead from lightly.models.utils import deactivate_requires_grad, update_momentum from lightly.transforms.simclr_transform import SimCLRTransform from lightly.utils.scheduler import cosine_schedule class TiCo(nn.Module): def __init__(self, backbone): super().__init__() self.backbone = backbone self.projection_head = TiCoProjectionHead(512, 1024, 256) self.backbone_momentum = copy.deepcopy(self.backbone) self.projection_head_momentum = copy.deepcopy(self.projection_head) deactivate_requires_grad(self.backbone_momentum) deactivate_requires_grad(self.projection_head_momentum) def forward(self, x): y = self.backbone(x).flatten(start_dim=1) z = self.projection_head(y) return z def forward_momentum(self, x): y = self.backbone_momentum(x).flatten(start_dim=1) z = self.projection_head_momentum(y) z = z.detach() return z resnet = torchvision.models.resnet18() backbone = nn.Sequential(*list(resnet.children())[:-1]) model = TiCo(backbone) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) transform = SimCLRTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) criterion = TiCoLoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.06) epochs = 10 print("Starting Training") for epoch in range(epochs): total_loss = 0 momentum_val = cosine_schedule(epoch, epochs, 0.996, 1) for batch in dataloader: x0, x1 = batch[0] update_momentum(model.backbone, model.backbone_momentum, m=momentum_val) update_momentum( model.projection_head, model.projection_head_momentum, m=momentum_val ) x0 = x0.to(device) x1 = x1.to(device) z0 = model(x0) z1 = model.forward_momentum(x1) loss = criterion(z0, z1) total_loss += loss.detach() loss.backward() optimizer.step() optimizer.zero_grad() avg_loss = total_loss / len(dataloader) print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")
2,771
29.130435
81
py
lightly
lightly-master/examples/pytorch/vicreg.py
import torch import torchvision from torch import nn ## The projection head is the same as the Barlow Twins one from lightly.loss import VICRegLoss ## The projection head is the same as the Barlow Twins one from lightly.loss.vicreg_loss import VICRegLoss from lightly.models.modules import BarlowTwinsProjectionHead from lightly.transforms.vicreg_transform import VICRegTransform class VICReg(nn.Module): def __init__(self, backbone): super().__init__() self.backbone = backbone self.projection_head = BarlowTwinsProjectionHead(512, 2048, 2048) def forward(self, x): x = self.backbone(x).flatten(start_dim=1) z = self.projection_head(x) return z resnet = torchvision.models.resnet18() backbone = nn.Sequential(*list(resnet.children())[:-1]) model = VICReg(backbone) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) transform = VICRegTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) criterion = VICRegLoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.06) print("Starting Training") for epoch in range(10): total_loss = 0 for batch in dataloader: x0, x1 = batch[0] x0 = x0.to(device) x1 = x1.to(device) z0 = model(x0) z1 = model(x1) loss = criterion(z0, z1) total_loss += loss.detach() loss.backward() optimizer.step() optimizer.zero_grad() avg_loss = total_loss / len(dataloader) print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")
1,869
27.333333
73
py
lightly
lightly-master/examples/pytorch/vicregl.py
import torch import torchvision from torch import nn from lightly.loss import VICRegLLoss ## The global projection head is the same as the Barlow Twins one from lightly.models.modules import BarlowTwinsProjectionHead from lightly.models.modules.heads import VicRegLLocalProjectionHead from lightly.transforms.vicregl_transform import VICRegLTransform class VICRegL(nn.Module): def __init__(self, backbone): super().__init__() self.backbone = backbone self.projection_head = BarlowTwinsProjectionHead(512, 2048, 2048) self.local_projection_head = VicRegLLocalProjectionHead(512, 128, 128) self.average_pool = nn.AdaptiveAvgPool2d(output_size=(1, 1)) def forward(self, x): x = self.backbone(x) y = self.average_pool(x).flatten(start_dim=1) z = self.projection_head(y) y_local = x.permute(0, 2, 3, 1) # (B, D, W, H) to (B, W, H, D) z_local = self.local_projection_head(y_local) return z, z_local resnet = torchvision.models.resnet18() backbone = nn.Sequential(*list(resnet.children())[:-2]) model = VICRegL(backbone) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) transform = VICRegLTransform(n_local_views=0) # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) criterion = VICRegLLoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9) print("Starting Training") for epoch in range(10): total_loss = 0 for views_and_grids, _ in dataloader: views_and_grids = [x.to(device) for x in views_and_grids] views = views_and_grids[: len(views_and_grids) // 2] grids = views_and_grids[len(views_and_grids) // 2 :] features = [model(view) for view in views] loss = criterion( global_view_features=features[:2], global_view_grids=grids[:2], local_view_features=features[2:], local_view_grids=grids[2:], ) total_loss += loss.detach() loss.backward() optimizer.step() optimizer.zero_grad() avg_loss = total_loss / len(dataloader) print(f"epoch: {epoch:>02}, loss: {avg_loss:.5f}")
2,591
31.810127
80
py
lightly
lightly-master/examples/pytorch_lightning/barlowtwins.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import BarlowTwinsLoss from lightly.models.modules import BarlowTwinsProjectionHead from lightly.transforms.simclr_transform import SimCLRTransform class BarlowTwins(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = BarlowTwinsProjectionHead(512, 2048, 2048) self.criterion = BarlowTwinsLoss() def forward(self, x): x = self.backbone(x).flatten(start_dim=1) z = self.projection_head(x) return z def training_step(self, batch, batch_index): (x0, x1) = batch[0] z0 = self.forward(x0) z1 = self.forward(x1) loss = self.criterion(z0, z1) return loss def configure_optimizers(self): optim = torch.optim.SGD(self.parameters(), lr=0.06) return optim model = BarlowTwins() transform = SimCLRTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) accelerator = "gpu" if torch.cuda.is_available() else "cpu" trainer = pl.Trainer(max_epochs=10, devices=1, accelerator=accelerator) trainer.fit(model=model, train_dataloaders=dataloader)
1,844
29.245902
77
py
lightly
lightly-master/examples/pytorch_lightning/byol.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import copy import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import NegativeCosineSimilarity from lightly.models.modules import BYOLPredictionHead, BYOLProjectionHead from lightly.models.utils import deactivate_requires_grad, update_momentum from lightly.transforms.simclr_transform import SimCLRTransform from lightly.utils.scheduler import cosine_schedule class BYOL(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = BYOLProjectionHead(512, 1024, 256) self.prediction_head = BYOLPredictionHead(256, 1024, 256) self.backbone_momentum = copy.deepcopy(self.backbone) self.projection_head_momentum = copy.deepcopy(self.projection_head) deactivate_requires_grad(self.backbone_momentum) deactivate_requires_grad(self.projection_head_momentum) self.criterion = NegativeCosineSimilarity() def forward(self, x): y = self.backbone(x).flatten(start_dim=1) z = self.projection_head(y) p = self.prediction_head(z) return p def forward_momentum(self, x): y = self.backbone_momentum(x).flatten(start_dim=1) z = self.projection_head_momentum(y) z = z.detach() return z def training_step(self, batch, batch_idx): momentum = cosine_schedule(self.current_epoch, 10, 0.996, 1) update_momentum(self.backbone, self.backbone_momentum, m=momentum) update_momentum(self.projection_head, self.projection_head_momentum, m=momentum) (x0, x1) = batch[0] p0 = self.forward(x0) z0 = self.forward_momentum(x0) p1 = self.forward(x1) z1 = self.forward_momentum(x1) loss = 0.5 * (self.criterion(p0, z1) + self.criterion(p1, z0)) return loss def configure_optimizers(self): return torch.optim.SGD(self.parameters(), lr=0.06) model = BYOL() transform = SimCLRTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) accelerator = "gpu" if torch.cuda.is_available() else "cpu" trainer = pl.Trainer(max_epochs=10, devices=1, accelerator=accelerator) trainer.fit(model=model, train_dataloaders=dataloader)
2,857
33.02381
88
py
lightly
lightly-master/examples/pytorch_lightning/dcl.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import DCLLoss from lightly.models.modules import SimCLRProjectionHead from lightly.transforms.simclr_transform import SimCLRTransform class DCL(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = SimCLRProjectionHead(512, 2048, 2048) self.criterion = DCLLoss() # or use the weighted DCLW loss: # self.criterion = DCLWLoss() def forward(self, x): x = self.backbone(x).flatten(start_dim=1) z = self.projection_head(x) return z def training_step(self, batch, batch_index): (x0, x1) = batch[0] z0 = self.forward(x0) z1 = self.forward(x1) loss = self.criterion(z0, z1) return loss def configure_optimizers(self): optim = torch.optim.SGD(self.parameters(), lr=0.06) return optim model = DCL() transform = SimCLRTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) accelerator = "gpu" if torch.cuda.is_available() else "cpu" trainer = pl.Trainer(max_epochs=10, devices=1, accelerator=accelerator) trainer.fit(model=model, train_dataloaders=dataloader)
1,880
29.33871
77
py
lightly
lightly-master/examples/pytorch_lightning/dino.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import copy import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import DINOLoss from lightly.models.modules import DINOProjectionHead from lightly.models.utils import deactivate_requires_grad, update_momentum from lightly.transforms.dino_transform import DINOTransform from lightly.utils.scheduler import cosine_schedule class DINO(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() backbone = nn.Sequential(*list(resnet.children())[:-1]) input_dim = 512 # instead of a resnet you can also use a vision transformer backbone as in the # original paper (you might have to reduce the batch size in this case): # backbone = torch.hub.load('facebookresearch/dino:main', 'dino_vits16', pretrained=False) # input_dim = backbone.embed_dim self.student_backbone = backbone self.student_head = DINOProjectionHead( input_dim, 512, 64, 2048, freeze_last_layer=1 ) self.teacher_backbone = copy.deepcopy(backbone) self.teacher_head = DINOProjectionHead(input_dim, 512, 64, 2048) deactivate_requires_grad(self.teacher_backbone) deactivate_requires_grad(self.teacher_head) self.criterion = DINOLoss(output_dim=2048, warmup_teacher_temp_epochs=5) def forward(self, x): y = self.student_backbone(x).flatten(start_dim=1) z = self.student_head(y) return z def forward_teacher(self, x): y = self.teacher_backbone(x).flatten(start_dim=1) z = self.teacher_head(y) return z def training_step(self, batch, batch_idx): momentum = cosine_schedule(self.current_epoch, 10, 0.996, 1) update_momentum(self.student_backbone, self.teacher_backbone, m=momentum) update_momentum(self.student_head, self.teacher_head, m=momentum) views = batch[0] views = [view.to(self.device) for view in views] global_views = views[:2] teacher_out = [self.forward_teacher(view) for view in global_views] student_out = [self.forward(view) for view in views] loss = self.criterion(teacher_out, student_out, epoch=self.current_epoch) return loss def on_after_backward(self): self.student_head.cancel_last_layer_gradients(current_epoch=self.current_epoch) def configure_optimizers(self): optim = torch.optim.Adam(self.parameters(), lr=0.001) return optim model = DINO() transform = DINOTransform() # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=64, shuffle=True, drop_last=True, num_workers=8, ) accelerator = "gpu" if torch.cuda.is_available() else "cpu" trainer = pl.Trainer(max_epochs=10, devices=1, accelerator=accelerator) trainer.fit(model=model, train_dataloaders=dataloader)
3,437
34.8125
98
py
lightly
lightly-master/examples/pytorch_lightning/fastsiam.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import NegativeCosineSimilarity from lightly.models.modules import SimSiamPredictionHead, SimSiamProjectionHead from lightly.transforms import FastSiamTransform class FastSiam(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = SimSiamProjectionHead(512, 512, 128) self.prediction_head = SimSiamPredictionHead(128, 64, 128) self.criterion = NegativeCosineSimilarity() def forward(self, x): f = self.backbone(x).flatten(start_dim=1) z = self.projection_head(f) p = self.prediction_head(z) z = z.detach() return z, p def training_step(self, batch, batch_idx): views = batch[0] features = [self.forward(view) for view in views] zs = torch.stack([z for z, _ in features]) ps = torch.stack([p for _, p in features]) loss = 0.0 for i in range(len(views)): mask = torch.arange(len(views), device=self.device) != i loss += self.criterion(ps[i], torch.mean(zs[mask], dim=0)) / len(views) self.log("train_loss_ssl", loss) return loss def configure_optimizers(self): optim = torch.optim.SGD(self.parameters(), lr=0.06) return optim model = FastSiam() transform = FastSiamTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) accelerator = "gpu" if torch.cuda.is_available() else "cpu" trainer = pl.Trainer(max_epochs=10, devices=1, accelerator=accelerator) trainer.fit(model=model, train_dataloaders=dataloader)
2,293
31.309859
83
py
lightly
lightly-master/examples/pytorch_lightning/ijepa.py
# TODO
7
3
6
py
lightly
lightly-master/examples/pytorch_lightning/mae.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.models import utils from lightly.models.modules import masked_autoencoder from lightly.transforms.mae_transform import MAETransform class MAE(pl.LightningModule): def __init__(self): super().__init__() decoder_dim = 512 vit = torchvision.models.vit_b_32(pretrained=False) self.mask_ratio = 0.75 self.patch_size = vit.patch_size self.sequence_length = vit.seq_length self.mask_token = nn.Parameter(torch.zeros(1, 1, decoder_dim)) self.backbone = masked_autoencoder.MAEBackbone.from_vit(vit) self.decoder = masked_autoencoder.MAEDecoder( seq_length=vit.seq_length, num_layers=1, num_heads=16, embed_input_dim=vit.hidden_dim, hidden_dim=decoder_dim, mlp_dim=decoder_dim * 4, out_dim=vit.patch_size**2 * 3, dropout=0, attention_dropout=0, ) self.criterion = nn.MSELoss() def forward_encoder(self, images, idx_keep=None): return self.backbone.encode(images, idx_keep) def forward_decoder(self, x_encoded, idx_keep, idx_mask): # build decoder input batch_size = x_encoded.shape[0] x_decode = self.decoder.embed(x_encoded) x_masked = utils.repeat_token( self.mask_token, (batch_size, self.sequence_length) ) x_masked = utils.set_at_index(x_masked, idx_keep, x_decode.type_as(x_masked)) # decoder forward pass x_decoded = self.decoder.decode(x_masked) # predict pixel values for masked tokens x_pred = utils.get_at_index(x_decoded, idx_mask) x_pred = self.decoder.predict(x_pred) return x_pred def training_step(self, batch, batch_idx): views = batch[0] images = views[0] # views contains only a single view batch_size = images.shape[0] idx_keep, idx_mask = utils.random_token_mask( size=(batch_size, self.sequence_length), mask_ratio=self.mask_ratio, device=images.device, ) x_encoded = self.forward_encoder(images, idx_keep) x_pred = self.forward_decoder(x_encoded, idx_keep, idx_mask) # get image patches for masked tokens patches = utils.patchify(images, self.patch_size) # must adjust idx_mask for missing class token target = utils.get_at_index(patches, idx_mask - 1) loss = self.criterion(x_pred, target) return loss def configure_optimizers(self): optim = torch.optim.AdamW(self.parameters(), lr=1.5e-4) return optim model = MAE() transform = MAETransform() # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) accelerator = "gpu" if torch.cuda.is_available() else "cpu" trainer = pl.Trainer(max_epochs=10, devices=1, accelerator=accelerator) trainer.fit(model=model, train_dataloaders=dataloader)
3,626
32.275229
85
py
lightly
lightly-master/examples/pytorch_lightning/moco.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import copy import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import NTXentLoss from lightly.models.modules import MoCoProjectionHead from lightly.models.utils import deactivate_requires_grad, update_momentum from lightly.transforms.moco_transform import MoCoV2Transform from lightly.utils.scheduler import cosine_schedule class MoCo(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = MoCoProjectionHead(512, 512, 128) self.backbone_momentum = copy.deepcopy(self.backbone) self.projection_head_momentum = copy.deepcopy(self.projection_head) deactivate_requires_grad(self.backbone_momentum) deactivate_requires_grad(self.projection_head_momentum) self.criterion = NTXentLoss(memory_bank_size=4096) def forward(self, x): query = self.backbone(x).flatten(start_dim=1) query = self.projection_head(query) return query def forward_momentum(self, x): key = self.backbone_momentum(x).flatten(start_dim=1) key = self.projection_head_momentum(key).detach() return key def training_step(self, batch, batch_idx): momentum = cosine_schedule(self.current_epoch, 10, 0.996, 1) update_momentum(self.backbone, self.backbone_momentum, m=momentum) update_momentum(self.projection_head, self.projection_head_momentum, m=momentum) x_query, x_key = batch[0] query = self.forward(x_query) key = self.forward_momentum(x_key) loss = self.criterion(query, key) return loss def configure_optimizers(self): optim = torch.optim.SGD(self.parameters(), lr=0.06) return optim model = MoCo() transform = MoCoV2Transform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) accelerator = "gpu" if torch.cuda.is_available() else "cpu" trainer = pl.Trainer(max_epochs=10, devices=1, accelerator=accelerator) trainer.fit(model=model, train_dataloaders=dataloader)
2,677
32.475
88
py
lightly
lightly-master/examples/pytorch_lightning/msn.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import copy import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import MSNLoss from lightly.models import utils from lightly.models.modules.heads import MSNProjectionHead from lightly.models.modules.masked_autoencoder import MAEBackbone from lightly.transforms.msn_transform import MSNTransform class MSN(pl.LightningModule): def __init__(self): super().__init__() # ViT small configuration (ViT-S/16) self.mask_ratio = 0.15 self.backbone = MAEBackbone( image_size=224, patch_size=16, num_layers=12, num_heads=6, hidden_dim=384, mlp_dim=384 * 4, ) # or use a torchvision ViT backbone: # vit = torchvision.models.vit_b_32(pretrained=False) # self.backbone = MAEBackbone.from_vit(vit) self.projection_head = MSNProjectionHead(384) self.anchor_backbone = copy.deepcopy(self.backbone) self.anchor_projection_head = copy.deepcopy(self.projection_head) utils.deactivate_requires_grad(self.backbone) utils.deactivate_requires_grad(self.projection_head) self.prototypes = nn.Linear(256, 1024, bias=False).weight self.criterion = MSNLoss() def training_step(self, batch, batch_idx): utils.update_momentum(self.anchor_backbone, self.backbone, 0.996) utils.update_momentum(self.anchor_projection_head, self.projection_head, 0.996) views = batch[0] views = [view.to(self.device, non_blocking=True) for view in views] targets = views[0] anchors = views[1] anchors_focal = torch.concat(views[2:], dim=0) targets_out = self.backbone(targets) targets_out = self.projection_head(targets_out) anchors_out = self.encode_masked(anchors) anchors_focal_out = self.encode_masked(anchors_focal) anchors_out = torch.cat([anchors_out, anchors_focal_out], dim=0) loss = self.criterion(anchors_out, targets_out, self.prototypes.data) return loss def encode_masked(self, anchors): batch_size, _, _, width = anchors.shape seq_length = (width // self.anchor_backbone.patch_size) ** 2 idx_keep, _ = utils.random_token_mask( size=(batch_size, seq_length), mask_ratio=self.mask_ratio, device=self.device, ) out = self.anchor_backbone(anchors, idx_keep) return self.anchor_projection_head(out) def configure_optimizers(self): params = [ *list(self.anchor_backbone.parameters()), *list(self.anchor_projection_head.parameters()), self.prototypes, ] optim = torch.optim.AdamW(params, lr=1.5e-4) return optim model = MSN() transform = MSNTransform() # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=64, shuffle=True, drop_last=True, num_workers=8, ) accelerator = "gpu" if torch.cuda.is_available() else "cpu" trainer = pl.Trainer(max_epochs=10, devices=1, accelerator=accelerator) trainer.fit(model=model, train_dataloaders=dataloader)
3,715
32.477477
87
py
lightly
lightly-master/examples/pytorch_lightning/nnclr.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import NTXentLoss from lightly.models.modules import ( NNCLRPredictionHead, NNCLRProjectionHead, NNMemoryBankModule, ) from lightly.transforms.simclr_transform import SimCLRTransform class NNCLR(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = NNCLRProjectionHead(512, 512, 128) self.prediction_head = NNCLRPredictionHead(128, 512, 128) self.memory_bank = NNMemoryBankModule(size=4096) self.criterion = NTXentLoss() def forward(self, x): y = self.backbone(x).flatten(start_dim=1) z = self.projection_head(y) p = self.prediction_head(z) z = z.detach() return z, p def training_step(self, batch, batch_idx): (x0, x1) = batch[0] z0, p0 = self.forward(x0) z1, p1 = self.forward(x1) z0 = self.memory_bank(z0, update=False) z1 = self.memory_bank(z1, update=True) loss = 0.5 * (self.criterion(z0, p1) + self.criterion(z1, p0)) return loss def configure_optimizers(self): optim = torch.optim.SGD(self.parameters(), lr=0.06) return optim model = NNCLR() transform = SimCLRTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) accelerator = "gpu" if torch.cuda.is_available() else "cpu" trainer = pl.Trainer(max_epochs=10, devices=1, accelerator=accelerator) trainer.fit(model=model, train_dataloaders=dataloader)
2,186
29.375
77
py
lightly
lightly-master/examples/pytorch_lightning/pmsn.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import copy import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import PMSNLoss from lightly.models import utils from lightly.models.modules.heads import MSNProjectionHead from lightly.models.modules.masked_autoencoder import MAEBackbone from lightly.transforms import MSNTransform class PMSN(pl.LightningModule): def __init__(self): super().__init__() # ViT small configuration (ViT-S/16) self.mask_ratio = 0.15 self.backbone = MAEBackbone( image_size=224, patch_size=16, num_layers=12, num_heads=6, hidden_dim=384, mlp_dim=384 * 4, ) # or use a torchvision ViT backbone: # vit = torchvision.models.vit_b_32(pretrained=False) # self.backbone = MAEBackbone.from_vit(vit) self.projection_head = MSNProjectionHead(384) self.anchor_backbone = copy.deepcopy(self.backbone) self.anchor_projection_head = copy.deepcopy(self.projection_head) utils.deactivate_requires_grad(self.backbone) utils.deactivate_requires_grad(self.projection_head) self.prototypes = nn.Linear(256, 1024, bias=False).weight self.criterion = PMSNLoss() def training_step(self, batch, batch_idx): utils.update_momentum(self.anchor_backbone, self.backbone, 0.996) utils.update_momentum(self.anchor_projection_head, self.projection_head, 0.996) views = batch[0] views = [view.to(self.device, non_blocking=True) for view in views] targets = views[0] anchors = views[1] anchors_focal = torch.concat(views[2:], dim=0) targets_out = self.backbone(targets) targets_out = self.projection_head(targets_out) anchors_out = self.encode_masked(anchors) anchors_focal_out = self.encode_masked(anchors_focal) anchors_out = torch.cat([anchors_out, anchors_focal_out], dim=0) loss = self.criterion(anchors_out, targets_out, self.prototypes.data) return loss def encode_masked(self, anchors): batch_size, _, _, width = anchors.shape seq_length = (width // self.anchor_backbone.patch_size) ** 2 idx_keep, _ = utils.random_token_mask( size=(batch_size, seq_length), mask_ratio=self.mask_ratio, device=self.device, ) out = self.anchor_backbone(anchors, idx_keep) return self.anchor_projection_head(out) def configure_optimizers(self): params = [ *list(self.anchor_backbone.parameters()), *list(self.anchor_projection_head.parameters()), self.prototypes, ] optim = torch.optim.AdamW(params, lr=1.5e-4) return optim model = PMSN() transform = MSNTransform() # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=64, shuffle=True, drop_last=True, num_workers=8, ) accelerator = "gpu" if torch.cuda.is_available() else "cpu" trainer = pl.Trainer(max_epochs=10, devices=1, accelerator=accelerator) trainer.fit(model=model, train_dataloaders=dataloader)
3,705
32.387387
87
py
lightly
lightly-master/examples/pytorch_lightning/simclr.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import NTXentLoss from lightly.models.modules import SimCLRProjectionHead from lightly.transforms.simclr_transform import SimCLRTransform class SimCLR(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = SimCLRProjectionHead(512, 2048, 2048) self.criterion = NTXentLoss() def forward(self, x): x = self.backbone(x).flatten(start_dim=1) z = self.projection_head(x) return z def training_step(self, batch, batch_index): (x0, x1) = batch[0] z0 = self.forward(x0) z1 = self.forward(x1) loss = self.criterion(z0, z1) return loss def configure_optimizers(self): optim = torch.optim.SGD(self.parameters(), lr=0.06) return optim model = SimCLR() transform = SimCLRTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) accelerator = "gpu" if torch.cuda.is_available() else "cpu" trainer = pl.Trainer(max_epochs=10, devices=1, accelerator=accelerator) trainer.fit(model=model, train_dataloaders=dataloader)
1,814
28.754098
77
py
lightly
lightly-master/examples/pytorch_lightning/simmim.py
import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.models import utils from lightly.models.modules import masked_autoencoder from lightly.transforms.mae_transform import MAETransform # Same transform as MAE class SimMIM(pl.LightningModule): def __init__(self): super().__init__() vit = torchvision.models.vit_b_32(pretrained=False) decoder_dim = vit.hidden_dim self.mask_ratio = 0.75 self.patch_size = vit.patch_size self.sequence_length = vit.seq_length self.mask_token = nn.Parameter(torch.zeros(1, 1, decoder_dim)) # same backbone as MAE self.backbone = masked_autoencoder.MAEBackbone.from_vit(vit) # the decoder is a simple linear layer self.decoder = nn.Linear(vit.hidden_dim, vit.patch_size**2 * 3) # L1 loss as paper suggestion self.criterion = nn.L1Loss() def forward_encoder(self, images, batch_size, idx_mask): # pass all the tokens to the encoder, both masked and non masked ones tokens = self.backbone.images_to_tokens(images, prepend_class_token=True) tokens_masked = utils.mask_at_index(tokens, idx_mask, self.mask_token) return self.backbone.encoder(tokens_masked) def forward_decoder(self, x_encoded): return self.decoder(x_encoded) def training_step(self, batch, batch_idx): views = batch[0] images = views[0] # views contains only a single view batch_size = images.shape[0] idx_keep, idx_mask = utils.random_token_mask( size=(batch_size, self.sequence_length), mask_ratio=self.mask_ratio, device=images.device, ) # Encoding... x_encoded = self.forward_encoder(images, batch_size, idx_mask) x_encoded_masked = utils.get_at_index(x_encoded, idx_mask) # Decoding... x_out = self.forward_decoder(x_encoded_masked) # get image patches for masked tokens patches = utils.patchify(images, self.patch_size) # must adjust idx_mask for missing class token target = utils.get_at_index(patches, idx_mask - 1) loss = self.criterion(x_out, target) return loss def configure_optimizers(self): optim = torch.optim.AdamW(self.parameters(), lr=1.5e-4) return optim model = SimMIM() device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) transform = MAETransform() # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=8, shuffle=True, drop_last=True, num_workers=8, ) accelerator = "gpu" if torch.cuda.is_available() else "cpu" trainer = pl.Trainer(max_epochs=10, devices=1, accelerator=accelerator) trainer.fit(model=model, train_dataloaders=dataloader)
3,158
30.909091
82
py
lightly
lightly-master/examples/pytorch_lightning/simsiam.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import NegativeCosineSimilarity from lightly.models.modules import SimSiamPredictionHead, SimSiamProjectionHead from lightly.transforms import SimSiamTransform class SimSiam(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = SimSiamProjectionHead(512, 512, 128) self.prediction_head = SimSiamPredictionHead(128, 64, 128) self.criterion = NegativeCosineSimilarity() def forward(self, x): f = self.backbone(x).flatten(start_dim=1) z = self.projection_head(f) p = self.prediction_head(z) z = z.detach() return z, p def training_step(self, batch, batch_idx): (x0, x1) = batch[0] z0, p0 = self.forward(x0) z1, p1 = self.forward(x1) loss = 0.5 * (self.criterion(z0, p1) + self.criterion(z1, p0)) return loss def configure_optimizers(self): optim = torch.optim.SGD(self.parameters(), lr=0.06) return optim model = SimSiam() transform = SimSiamTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) accelerator = "gpu" if torch.cuda.is_available() else "cpu" trainer = pl.Trainer(max_epochs=10, devices=1, accelerator=accelerator) trainer.fit(model=model, train_dataloaders=dataloader)
2,020
30.578125
79
py
lightly
lightly-master/examples/pytorch_lightning/smog.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import copy import pytorch_lightning as pl import torch import torchvision from sklearn.cluster import KMeans from torch import nn from lightly import loss, models from lightly.models import utils from lightly.models.modules import heads from lightly.transforms.smog_transform import SMoGTransform class SMoGModel(pl.LightningModule): def __init__(self): super().__init__() # create a ResNet backbone and remove the classification head resnet = models.ResNetGenerator("resnet-18") self.backbone = nn.Sequential( *list(resnet.children())[:-1], nn.AdaptiveAvgPool2d(1) ) # create a model based on ResNet self.projection_head = heads.SMoGProjectionHead(512, 2048, 128) self.prediction_head = heads.SMoGPredictionHead(128, 2048, 128) self.backbone_momentum = copy.deepcopy(self.backbone) self.projection_head_momentum = copy.deepcopy(self.projection_head) utils.deactivate_requires_grad(self.backbone_momentum) utils.deactivate_requires_grad(self.projection_head_momentum) # smog self.n_groups = 300 memory_bank_size = 10000 self.memory_bank = loss.memory_bank.MemoryBankModule(size=memory_bank_size) # create our loss group_features = torch.nn.functional.normalize( torch.rand(self.n_groups, 128), dim=1 ).to(self.device) self.smog = heads.SMoGPrototypes(group_features=group_features, beta=0.99) self.criterion = nn.CrossEntropyLoss() def _cluster_features(self, features: torch.Tensor) -> torch.Tensor: features = features.cpu().numpy() kmeans = KMeans(self.n_groups).fit(features) clustered = torch.from_numpy(kmeans.cluster_centers_).float() clustered = torch.nn.functional.normalize(clustered, dim=1) return clustered def _reset_group_features(self): # see https://arxiv.org/pdf/2207.06167.pdf Table 7b) features = self.memory_bank.bank group_features = self._cluster_features(features.t()) self.smog.set_group_features(group_features) def _reset_momentum_weights(self): # see https://arxiv.org/pdf/2207.06167.pdf Table 7b) self.backbone_momentum = copy.deepcopy(self.backbone) self.projection_head_momentum = copy.deepcopy(self.projection_head) utils.deactivate_requires_grad(self.backbone_momentum) utils.deactivate_requires_grad(self.projection_head_momentum) def training_step(self, batch, batch_idx): if self.global_step > 0 and self.global_step % 300 == 0: # reset group features and weights every 300 iterations self._reset_group_features() self._reset_momentum_weights() else: # update momentum utils.update_momentum(self.backbone, self.backbone_momentum, 0.99) utils.update_momentum( self.projection_head, self.projection_head_momentum, 0.99 ) (x0, x1) = batch[0] if batch_idx % 2: # swap batches every second iteration x0, x1 = x1, x0 x0_features = self.backbone(x0).flatten(start_dim=1) x0_encoded = self.projection_head(x0_features) x0_predicted = self.prediction_head(x0_encoded) x1_features = self.backbone_momentum(x1).flatten(start_dim=1) x1_encoded = self.projection_head_momentum(x1_features) # update group features and get group assignments assignments = self.smog.assign_groups(x1_encoded) group_features = self.smog.get_updated_group_features(x0_encoded) logits = self.smog(x0_predicted, group_features, temperature=0.1) self.smog.set_group_features(group_features) loss = self.criterion(logits, assignments) # use memory bank to periodically reset the group features with k-means self.memory_bank(x0_encoded, update=True) return loss def configure_optimizers(self): params = ( list(self.backbone.parameters()) + list(self.projection_head.parameters()) + list(self.prediction_head.parameters()) ) optim = torch.optim.SGD( params, lr=0.01, momentum=0.9, weight_decay=1e-6, ) return optim model = SMoGModel() transform = SMoGTransform( crop_sizes=(32, 32), crop_counts=(1, 1), gaussian_blur_probs=(0.0, 0.0), crop_min_scales=(0.2, 0.2), crop_max_scales=(1.0, 1.0), ) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) accelerator = "gpu" if torch.cuda.is_available() else "cpu" trainer = pl.Trainer(max_epochs=10, devices=1, accelerator=accelerator) trainer.fit(model=model, train_dataloaders=dataloader)
5,306
35.349315
83
py
lightly
lightly-master/examples/pytorch_lightning/swav.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import SwaVLoss from lightly.models.modules import SwaVProjectionHead, SwaVPrototypes from lightly.transforms.swav_transform import SwaVTransform class SwaV(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = SwaVProjectionHead(512, 512, 128) self.prototypes = SwaVPrototypes(128, n_prototypes=512) self.criterion = SwaVLoss() def forward(self, x): x = self.backbone(x).flatten(start_dim=1) x = self.projection_head(x) x = nn.functional.normalize(x, dim=1, p=2) p = self.prototypes(x) return p def training_step(self, batch, batch_idx): self.prototypes.normalize() views = batch[0] multi_crop_features = [self.forward(view.to(self.device)) for view in views] high_resolution = multi_crop_features[:2] low_resolution = multi_crop_features[2:] loss = self.criterion(high_resolution, low_resolution) return loss def configure_optimizers(self): optim = torch.optim.Adam(self.parameters(), lr=0.001) return optim model = SwaV() transform = SwaVTransform() # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=128, shuffle=True, drop_last=True, num_workers=8, ) accelerator = "gpu" if torch.cuda.is_available() else "cpu" trainer = pl.Trainer(max_epochs=10, devices=1, accelerator=accelerator) trainer.fit(model=model, train_dataloaders=dataloader)
2,236
30.957143
84
py
lightly
lightly-master/examples/pytorch_lightning/swav_queue.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import SwaVLoss from lightly.loss.memory_bank import MemoryBankModule from lightly.models.modules import SwaVProjectionHead, SwaVPrototypes from lightly.transforms.swav_transform import SwaVTransform class SwaV(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = SwaVProjectionHead(512, 512, 128) self.prototypes = SwaVPrototypes(128, 512, 1) self.start_queue_at_epoch = 2 self.queues = nn.ModuleList([MemoryBankModule(size=3840) for _ in range(2)]) self.criterion = SwaVLoss() def training_step(self, batch, batch_idx): views = batch[0] high_resolution, low_resolution = views[:2], views[2:] self.prototypes.normalize() high_resolution_features = [self._subforward(x) for x in high_resolution] low_resolution_features = [self._subforward(x) for x in low_resolution] high_resolution_prototypes = [ self.prototypes(x, self.current_epoch) for x in high_resolution_features ] low_resolution_prototypes = [ self.prototypes(x, self.current_epoch) for x in low_resolution_features ] queue_prototypes = self._get_queue_prototypes(high_resolution_features) loss = self.criterion( high_resolution_prototypes, low_resolution_prototypes, queue_prototypes ) return loss def configure_optimizers(self): optim = torch.optim.Adam(self.parameters(), lr=0.001) return optim def _subforward(self, input): features = self.backbone(input).flatten(start_dim=1) features = self.projection_head(features) features = nn.functional.normalize(features, dim=1, p=2) return features @torch.no_grad() def _get_queue_prototypes(self, high_resolution_features): if len(high_resolution_features) != len(self.queues): raise ValueError( f"The number of queues ({len(self.queues)}) should be equal to the number of high " f"resolution inputs ({len(high_resolution_features)}). Set `n_queues` accordingly." ) # Get the queue features queue_features = [] for i in range(len(self.queues)): _, features = self.queues[i](high_resolution_features[i], update=True) # Queue features are in (num_ftrs X queue_length) shape, while the high res # features are in (batch_size X num_ftrs). Swap the axes for interoperability. features = torch.permute(features, (1, 0)) queue_features.append(features) # If loss calculation with queue prototypes starts at a later epoch, # just queue the features and return None instead of queue prototypes. if ( self.start_queue_at_epoch > 0 and self.current_epoch < self.start_queue_at_epoch ): return None # Assign prototypes queue_prototypes = [ self.prototypes(x, self.current_epoch) for x in queue_features ] return queue_prototypes model = SwaV() transform = SwaVTransform() # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=128, shuffle=True, drop_last=True, num_workers=8, ) accelerator = "gpu" if torch.cuda.is_available() else "cpu" trainer = pl.Trainer(max_epochs=10, devices=1, accelerator=accelerator) trainer.fit(model=model, train_dataloaders=dataloader)
4,217
36.327434
99
py
lightly
lightly-master/examples/pytorch_lightning/tico.py
import copy import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss.tico_loss import TiCoLoss from lightly.models.modules.heads import TiCoProjectionHead from lightly.models.utils import deactivate_requires_grad, update_momentum from lightly.transforms.simclr_transform import SimCLRTransform from lightly.utils.scheduler import cosine_schedule class TiCo(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = TiCoProjectionHead(512, 1024, 256) self.backbone_momentum = copy.deepcopy(self.backbone) self.projection_head_momentum = copy.deepcopy(self.projection_head) deactivate_requires_grad(self.backbone_momentum) deactivate_requires_grad(self.projection_head_momentum) self.criterion = TiCoLoss() def forward(self, x): y = self.backbone(x).flatten(start_dim=1) z = self.projection_head(y) return z def forward_momentum(self, x): y = self.backbone_momentum(x).flatten(start_dim=1) z = self.projection_head_momentum(y) z = z.detach() return z def training_step(self, batch, batch_idx): (x0, x1) = batch[0] momentum = cosine_schedule(self.current_epoch, 10, 0.996, 1) update_momentum(self.backbone, self.backbone_momentum, m=momentum) update_momentum(self.projection_head, self.projection_head_momentum, m=momentum) x0 = x0.to(self.device) x1 = x1.to(self.device) z0 = self.forward(x0) z1 = self.forward_momentum(x1) loss = self.criterion(z0, z1) return loss def configure_optimizers(self): return torch.optim.SGD(self.parameters(), lr=0.06) model = TiCo() transform = SimCLRTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) accelerator = "gpu" if torch.cuda.is_available() else "cpu" trainer = pl.Trainer(max_epochs=10, devices=1, accelerator=accelerator) trainer.fit(model=model, train_dataloaders=dataloader)
2,481
30.820513
88
py
lightly
lightly-master/examples/pytorch_lightning/vicreg.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss.vicreg_loss import VICRegLoss ## The projection head is the same as the Barlow Twins one from lightly.models.modules import BarlowTwinsProjectionHead from lightly.transforms.vicreg_transform import VICRegTransform class VICReg(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = BarlowTwinsProjectionHead(512, 2048, 2048) self.criterion = VICRegLoss() def forward(self, x): x = self.backbone(x).flatten(start_dim=1) z = self.projection_head(x) return z def training_step(self, batch, batch_index): (x0, x1) = batch[0] z0 = self.forward(x0) z1 = self.forward(x1) loss = self.criterion(z0, z1) return loss def configure_optimizers(self): optim = torch.optim.SGD(self.parameters(), lr=0.06) return optim model = VICReg() transform = VICRegTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) accelerator = "gpu" if torch.cuda.is_available() else "cpu" trainer = pl.Trainer(max_epochs=10, devices=1, accelerator=accelerator) trainer.fit(model=model, train_dataloaders=dataloader)
1,896
29.111111
77
py
lightly
lightly-master/examples/pytorch_lightning/vicregl.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import VICRegLLoss ## The global projection head is the same as the Barlow Twins one from lightly.models.modules import BarlowTwinsProjectionHead from lightly.models.modules.heads import VicRegLLocalProjectionHead from lightly.transforms.vicregl_transform import VICRegLTransform class VICRegL(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-2]) self.projection_head = BarlowTwinsProjectionHead(512, 2048, 2048) self.local_projection_head = VicRegLLocalProjectionHead(512, 128, 128) self.average_pool = nn.AdaptiveAvgPool2d(output_size=(1, 1)) self.criterion = VICRegLLoss() def forward(self, x): x = self.backbone(x) y = self.average_pool(x).flatten(start_dim=1) z = self.projection_head(y) y_local = x.permute(0, 2, 3, 1) # (B, D, W, H) to (B, W, H, D) z_local = self.local_projection_head(y_local) return z, z_local def training_step(self, batch, batch_index): views_and_grids = batch[0] views = views_and_grids[: len(views_and_grids) // 2] grids = views_and_grids[len(views_and_grids) // 2 :] features = [self.forward(view) for view in views] loss = self.criterion( global_view_features=features[:2], global_view_grids=grids[:2], local_view_features=features[2:], local_view_grids=grids[2:], ) return loss def configure_optimizers(self): optim = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9) return optim model = VICRegL() transform = VICRegLTransform(n_local_views=0) # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) accelerator = "gpu" if torch.cuda.is_available() else "cpu" trainer = pl.Trainer(max_epochs=10, devices=1, accelerator=accelerator) trainer.fit(model=model, train_dataloaders=dataloader)
2,714
33.367089
80
py
lightly
lightly-master/examples/pytorch_lightning_distributed/barlowtwins.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import BarlowTwinsLoss from lightly.models.modules import BarlowTwinsProjectionHead from lightly.transforms.simclr_transform import SimCLRTransform class BarlowTwins(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = BarlowTwinsProjectionHead(512, 2048, 2048) # enable gather_distributed to gather features from all gpus # before calculating the loss self.criterion = BarlowTwinsLoss(gather_distributed=True) def forward(self, x): x = self.backbone(x).flatten(start_dim=1) z = self.projection_head(x) return z def training_step(self, batch, batch_index): (x0, x1) = batch[0] z0 = self.forward(x0) z1 = self.forward(x1) loss = self.criterion(z0, z1) return loss def configure_optimizers(self): optim = torch.optim.SGD(self.parameters(), lr=0.06) return optim model = BarlowTwins() transform = SimCLRTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) # Train with DDP and use Synchronized Batch Norm for a more accurate batch norm # calculation. Distributed sampling is also enabled with replace_sampler_ddp=True. trainer = pl.Trainer( max_epochs=10, devices="auto", accelerator="gpu", strategy="ddp", sync_batchnorm=True, use_distributed_sampler=True, # or replace_sampler_ddp=True for PyTorch Lightning <2.0 ) trainer.fit(model=model, train_dataloaders=dataloader)
2,228
30.394366
91
py
lightly
lightly-master/examples/pytorch_lightning_distributed/byol.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import copy import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import NegativeCosineSimilarity from lightly.models.modules import BYOLProjectionHead from lightly.models.modules.heads import BYOLPredictionHead from lightly.models.utils import deactivate_requires_grad, update_momentum from lightly.transforms.simclr_transform import SimCLRTransform from lightly.utils.scheduler import cosine_schedule class BYOL(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = BYOLProjectionHead(512, 1024, 256) self.prediction_head = BYOLPredictionHead(256, 1024, 256) self.backbone_momentum = copy.deepcopy(self.backbone) self.projection_head_momentum = copy.deepcopy(self.projection_head) deactivate_requires_grad(self.backbone_momentum) deactivate_requires_grad(self.projection_head_momentum) self.criterion = NegativeCosineSimilarity() def forward(self, x): y = self.backbone(x).flatten(start_dim=1) z = self.projection_head(y) p = self.prediction_head(z) return p def forward_momentum(self, x): y = self.backbone_momentum(x).flatten(start_dim=1) z = self.projection_head_momentum(y) z = z.detach() return z def training_step(self, batch, batch_idx): momentum = cosine_schedule(self.current_epoch, 10, 0.996, 1) update_momentum(self.backbone, self.backbone_momentum, m=momentum) update_momentum(self.projection_head, self.projection_head_momentum, m=momentum) (x0, x1) = batch[0] p0 = self.forward(x0) z0 = self.forward_momentum(x0) p1 = self.forward(x1) z1 = self.forward_momentum(x1) loss = 0.5 * (self.criterion(p0, z1) + self.criterion(p1, z0)) return loss def configure_optimizers(self): return torch.optim.SGD(self.parameters(), lr=0.06) model = BYOL() transform = SimCLRTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) # Train with DDP and use Synchronized Batch Norm for a more accurate batch norm # calculation. Distributed sampling is also enabled with replace_sampler_ddp=True. trainer = pl.Trainer( max_epochs=10, devices="auto", accelerator="gpu", strategy="ddp", sync_batchnorm=True, use_distributed_sampler=True, # or replace_sampler_ddp=True for PyTorch Lightning <2.0 ) trainer.fit(model=model, train_dataloaders=dataloader)
3,150
33.25
91
py
lightly
lightly-master/examples/pytorch_lightning_distributed/dcl.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import DCLLoss from lightly.models.modules import SimCLRProjectionHead from lightly.transforms.simclr_transform import SimCLRTransform class DCL(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = SimCLRProjectionHead(512, 2048, 2048) # enable gather_distributed to gather features from all gpus # before calculating the loss self.criterion = DCLLoss(gather_distributed=True) # or use the weighted DCLW loss: # self.criterion = DCLWLoss(gather_distributed=True) def forward(self, x): x = self.backbone(x).flatten(start_dim=1) z = self.projection_head(x) return z def training_step(self, batch, batch_index): (x0, x1) = batch[0] z0 = self.forward(x0) z1 = self.forward(x1) loss = self.criterion(z0, z1) return loss def configure_optimizers(self): optim = torch.optim.SGD(self.parameters(), lr=0.06) return optim model = DCL() transform = SimCLRTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) # Train with DDP and use Synchronized Batch Norm for a more accurate batch norm # calculation. Distributed sampling is also enabled with replace_sampler_ddp=True. trainer = pl.Trainer( max_epochs=10, devices="auto", accelerator="gpu", strategy="ddp", sync_batchnorm=True, use_distributed_sampler=True, # or replace_sampler_ddp=True for PyTorch Lightning <2.0 ) trainer.fit(model=model, train_dataloaders=dataloader)
2,288
30.356164
91
py
lightly
lightly-master/examples/pytorch_lightning_distributed/dino.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import copy import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import DINOLoss from lightly.models.modules import DINOProjectionHead from lightly.models.utils import deactivate_requires_grad, update_momentum from lightly.transforms.dino_transform import DINOTransform from lightly.utils.scheduler import cosine_schedule class DINO(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() backbone = nn.Sequential(*list(resnet.children())[:-1]) input_dim = 512 # instead of a resnet you can also use a vision transformer backbone as in the # original paper (you might have to reduce the batch size in this case): # backbone = torch.hub.load('facebookresearch/dino:main', 'dino_vits16', pretrained=False) # input_dim = backbone.embed_dim self.student_backbone = backbone self.student_head = DINOProjectionHead( input_dim, 512, 64, 2048, freeze_last_layer=1 ) self.teacher_backbone = copy.deepcopy(backbone) self.teacher_head = DINOProjectionHead(input_dim, 512, 64, 2048) deactivate_requires_grad(self.teacher_backbone) deactivate_requires_grad(self.teacher_head) self.criterion = DINOLoss(output_dim=2048, warmup_teacher_temp_epochs=5) def forward(self, x): y = self.student_backbone(x).flatten(start_dim=1) z = self.student_head(y) return z def forward_teacher(self, x): y = self.teacher_backbone(x).flatten(start_dim=1) z = self.teacher_head(y) return z def training_step(self, batch, batch_idx): momentum = cosine_schedule(self.current_epoch, 10, 0.996, 1) update_momentum(self.student_backbone, self.teacher_backbone, m=momentum) update_momentum(self.student_head, self.teacher_head, m=momentum) views = batch[0] views = [view.to(self.device) for view in views] global_views = views[:2] teacher_out = [self.forward_teacher(view) for view in global_views] student_out = [self.forward(view) for view in views] loss = self.criterion(teacher_out, student_out, epoch=self.current_epoch) return loss def on_after_backward(self): self.student_head.cancel_last_layer_gradients(current_epoch=self.current_epoch) def configure_optimizers(self): optim = torch.optim.Adam(self.parameters(), lr=0.001) return optim model = DINO() transform = DINOTransform() # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=64, shuffle=True, drop_last=True, num_workers=8, ) # Train with DDP and use Synchronized Batch Norm for a more accurate batch norm # calculation. Distributed sampling is also enabled with replace_sampler_ddp=True. trainer = pl.Trainer( max_epochs=10, devices="auto", accelerator="gpu", strategy="ddp", sync_batchnorm=True, use_distributed_sampler=True, # or replace_sampler_ddp=True for PyTorch Lightning <2.0 ) trainer.fit(model=model, train_dataloaders=dataloader)
3,690
34.834951
98
py
lightly
lightly-master/examples/pytorch_lightning_distributed/fastsiam.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import NegativeCosineSimilarity from lightly.models.modules import SimSiamPredictionHead, SimSiamProjectionHead from lightly.transforms import FastSiamTransform class FastSiam(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = SimSiamProjectionHead(512, 512, 128) self.prediction_head = SimSiamPredictionHead(128, 64, 128) self.criterion = NegativeCosineSimilarity() def forward(self, x): f = self.backbone(x).flatten(start_dim=1) z = self.projection_head(f) p = self.prediction_head(z) z = z.detach() return z, p def training_step(self, batch, batch_idx): views = batch[0] features = [self.forward(view) for view in views] zs = torch.stack([z for z, _ in features]) ps = torch.stack([p for _, p in features]) loss = 0.0 for i in range(len(views)): mask = torch.arange(len(views), device=self.device) != i loss += self.criterion(ps[i], torch.mean(zs[mask], dim=0)) / len(views) self.log("train_loss_ssl", loss) return loss def configure_optimizers(self): optim = torch.optim.SGD(self.parameters(), lr=0.06) return optim model = FastSiam() transform = FastSiamTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) # Train with DDP and use Synchronized Batch Norm for a more accurate batch norm # calculation. Distributed sampling is also enabled with replace_sampler_ddp=True. trainer = pl.Trainer( max_epochs=10, devices="auto", accelerator="gpu", strategy="ddp", sync_batchnorm=True, use_distributed_sampler=True, # or replace_sampler_ddp=True for PyTorch Lightning <2.0 ) trainer.fit(model=model, train_dataloaders=dataloader)
2,546
31.653846
91
py
lightly
lightly-master/examples/pytorch_lightning_distributed/ijepa.py
# TODO
7
3
6
py
lightly
lightly-master/examples/pytorch_lightning_distributed/mae.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.models import utils from lightly.models.modules import masked_autoencoder from lightly.transforms.mae_transform import MAETransform class MAE(pl.LightningModule): def __init__(self): super().__init__() decoder_dim = 512 vit = torchvision.models.vit_b_32(pretrained=False) self.mask_ratio = 0.75 self.patch_size = vit.patch_size self.sequence_length = vit.seq_length self.mask_token = nn.Parameter(torch.zeros(1, 1, decoder_dim)) self.backbone = masked_autoencoder.MAEBackbone.from_vit(vit) self.decoder = masked_autoencoder.MAEDecoder( seq_length=vit.seq_length, num_layers=1, num_heads=16, embed_input_dim=vit.hidden_dim, hidden_dim=decoder_dim, mlp_dim=decoder_dim * 4, out_dim=vit.patch_size**2 * 3, dropout=0, attention_dropout=0, ) self.criterion = nn.MSELoss() def forward_encoder(self, images, idx_keep=None): return self.backbone.encode(images, idx_keep) def forward_decoder(self, x_encoded, idx_keep, idx_mask): # build decoder input batch_size = x_encoded.shape[0] x_decode = self.decoder.embed(x_encoded) x_masked = utils.repeat_token( self.mask_token, (batch_size, self.sequence_length) ) x_masked = utils.set_at_index(x_masked, idx_keep, x_decode.type_as(x_masked)) # decoder forward pass x_decoded = self.decoder.decode(x_masked) # predict pixel values for masked tokens x_pred = utils.get_at_index(x_decoded, idx_mask) x_pred = self.decoder.predict(x_pred) return x_pred def training_step(self, batch, batch_idx): views = batch[0] images = views[0] # views contains only a single view batch_size = images.shape[0] idx_keep, idx_mask = utils.random_token_mask( size=(batch_size, self.sequence_length), mask_ratio=self.mask_ratio, device=images.device, ) x_encoded = self.forward_encoder(images, idx_keep) x_pred = self.forward_decoder(x_encoded, idx_keep, idx_mask) # get image patches for masked tokens patches = utils.patchify(images, self.patch_size) # must adjust idx_mask for missing class token target = utils.get_at_index(patches, idx_mask - 1) loss = self.criterion(x_pred, target) return loss def configure_optimizers(self): optim = torch.optim.AdamW(self.parameters(), lr=1.5e-4) return optim model = MAE() transform = MAETransform() # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) # Train with DDP on multiple gpus. Distributed sampling is also enabled with # replace_sampler_ddp=True. trainer = pl.Trainer( max_epochs=10, devices="auto", accelerator="gpu", strategy="ddp", use_distributed_sampler=True, # or replace_sampler_ddp=True for PyTorch Lightning <2.0 ) trainer.fit(model=model, train_dataloaders=dataloader)
3,796
32.017391
91
py
lightly
lightly-master/examples/pytorch_lightning_distributed/moco.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import copy import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import NTXentLoss from lightly.models.modules import MoCoProjectionHead from lightly.models.utils import deactivate_requires_grad, update_momentum from lightly.transforms.moco_transform import MoCoV2Transform from lightly.utils.scheduler import cosine_schedule class MoCo(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = MoCoProjectionHead(512, 512, 128) self.backbone_momentum = copy.deepcopy(self.backbone) self.projection_head_momentum = copy.deepcopy(self.projection_head) deactivate_requires_grad(self.backbone_momentum) deactivate_requires_grad(self.projection_head_momentum) self.criterion = NTXentLoss(memory_bank_size=4096) def forward(self, x): query = self.backbone(x).flatten(start_dim=1) query = self.projection_head(query) return query def forward_momentum(self, x): key = self.backbone_momentum(x).flatten(start_dim=1) key = self.projection_head_momentum(key).detach() return key def training_step(self, batch, batch_idx): momentum = cosine_schedule(self.current_epoch, 10, 0.996, 1) update_momentum(self.backbone, self.backbone_momentum, m=momentum) update_momentum(self.projection_head, self.projection_head_momentum, m=momentum) x_query, x_key = batch[0] query = self.forward(x_query) key = self.forward_momentum(x_key) loss = self.criterion(query, key) return loss def configure_optimizers(self): optim = torch.optim.SGD(self.parameters(), lr=0.06) return optim model = MoCo() transform = MoCoV2Transform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) # Train with DDP and use Synchronized Batch Norm for a more accurate batch norm # calculation. Distributed sampling is also enabled with replace_sampler_ddp=True. trainer = pl.Trainer( max_epochs=10, devices="auto", accelerator="gpu", strategy="ddp", sync_batchnorm=True, use_distributed_sampler=True, # or replace_sampler_ddp=True for PyTorch Lightning <2.0 ) trainer.fit(model=model, train_dataloaders=dataloader)
2,930
32.689655
91
py
lightly
lightly-master/examples/pytorch_lightning_distributed/msn.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import copy import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import MSNLoss from lightly.models import utils from lightly.models.modules.heads import MSNProjectionHead from lightly.models.modules.masked_autoencoder import MAEBackbone from lightly.transforms.msn_transform import MSNTransform class MSN(pl.LightningModule): def __init__(self): super().__init__() # ViT small configuration (ViT-S/16) self.mask_ratio = 0.15 self.backbone = MAEBackbone( image_size=224, patch_size=16, num_layers=12, num_heads=6, hidden_dim=384, mlp_dim=384 * 4, ) # or use a torchvision ViT backbone: # vit = torchvision.models.vit_b_32(pretrained=False) # self.backbone = MAEBackbone.from_vit(vit) self.projection_head = MSNProjectionHead(384) self.anchor_backbone = copy.deepcopy(self.backbone) self.anchor_projection_head = copy.deepcopy(self.projection_head) utils.deactivate_requires_grad(self.backbone) utils.deactivate_requires_grad(self.projection_head) self.prototypes = nn.Linear(256, 1024, bias=False).weight # set gather_distributed to True for distributed training self.criterion = MSNLoss(gather_distributed=True) def training_step(self, batch, batch_idx): utils.update_momentum(self.anchor_backbone, self.backbone, 0.996) utils.update_momentum(self.anchor_projection_head, self.projection_head, 0.996) views = batch[0] views = [view.to(self.device, non_blocking=True) for view in views] targets = views[0] anchors = views[1] anchors_focal = torch.concat(views[2:], dim=0) targets_out = self.backbone(targets) targets_out = self.projection_head(targets_out) anchors_out = self.encode_masked(anchors) anchors_focal_out = self.encode_masked(anchors_focal) anchors_out = torch.cat([anchors_out, anchors_focal_out], dim=0) loss = self.criterion(anchors_out, targets_out, self.prototypes.data) return loss def encode_masked(self, anchors): batch_size, _, _, width = anchors.shape seq_length = (width // self.anchor_backbone.patch_size) ** 2 idx_keep, _ = utils.random_token_mask( size=(batch_size, seq_length), mask_ratio=self.mask_ratio, device=self.device, ) out = self.anchor_backbone(anchors, idx_keep) return self.anchor_projection_head(out) def configure_optimizers(self): params = [ *list(self.anchor_backbone.parameters()), *list(self.anchor_projection_head.parameters()), self.prototypes, ] optim = torch.optim.AdamW(params, lr=1.5e-4) return optim model = MSN() transform = MSNTransform() # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=64, shuffle=True, drop_last=True, num_workers=8, ) # Train with DDP on multiple gpus. Distributed sampling is also enabled with # replace_sampler_ddp=True. trainer = pl.Trainer( max_epochs=10, devices="auto", accelerator="gpu", strategy="ddp", use_distributed_sampler=True, # or replace_sampler_ddp=True for PyTorch Lightning <2.0 ) trainer.fit(model=model, train_dataloaders=dataloader)
3,975
32.411765
91
py
lightly
lightly-master/examples/pytorch_lightning_distributed/nnclr.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import NTXentLoss from lightly.models.modules import ( NNCLRPredictionHead, NNCLRProjectionHead, NNMemoryBankModule, ) from lightly.transforms.simclr_transform import SimCLRTransform class NNCLR(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = NNCLRProjectionHead(512, 512, 128) self.prediction_head = NNCLRPredictionHead(128, 512, 128) self.memory_bank = NNMemoryBankModule(size=4096) self.criterion = NTXentLoss() def forward(self, x): y = self.backbone(x).flatten(start_dim=1) z = self.projection_head(y) p = self.prediction_head(z) z = z.detach() return z, p def training_step(self, batch, batch_idx): (x0, x1) = batch[0] z0, p0 = self.forward(x0) z1, p1 = self.forward(x1) z0 = self.memory_bank(z0, update=False) z1 = self.memory_bank(z1, update=True) loss = 0.5 * (self.criterion(z0, p1) + self.criterion(z1, p0)) return loss def configure_optimizers(self): optim = torch.optim.SGD(self.parameters(), lr=0.06) return optim model = NNCLR() transform = SimCLRTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) # Train with DDP and use Synchronized Batch Norm for a more accurate batch norm # calculation. Distributed sampling is also enabled with replace_sampler_ddp=True. trainer = pl.Trainer( max_epochs=10, devices="auto", accelerator="gpu", strategy="ddp", sync_batchnorm=True, use_distributed_sampler=True, # or replace_sampler_ddp=True for PyTorch Lightning <2.0 ) trainer.fit(model=model, train_dataloaders=dataloader)
2,439
29.886076
91
py
lightly
lightly-master/examples/pytorch_lightning_distributed/pmsn.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import copy import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import PMSNLoss from lightly.models import utils from lightly.models.modules.heads import MSNProjectionHead from lightly.models.modules.masked_autoencoder import MAEBackbone from lightly.transforms import MSNTransform class PMSN(pl.LightningModule): def __init__(self): super().__init__() # ViT small configuration (ViT-S/16) self.mask_ratio = 0.15 self.backbone = MAEBackbone( image_size=224, patch_size=16, num_layers=12, num_heads=6, hidden_dim=384, mlp_dim=384 * 4, ) # or use a torchvision ViT backbone: # vit = torchvision.models.vit_b_32(pretrained=False) # self.backbone = MAEBackbone.from_vit(vit) self.projection_head = MSNProjectionHead(384) self.anchor_backbone = copy.deepcopy(self.backbone) self.anchor_projection_head = copy.deepcopy(self.projection_head) utils.deactivate_requires_grad(self.backbone) utils.deactivate_requires_grad(self.projection_head) self.prototypes = nn.Linear(256, 1024, bias=False).weight # set gather_distributed to True for distributed training self.criterion = PMSNLoss(gather_distributed=True) def training_step(self, batch, batch_idx): utils.update_momentum(self.anchor_backbone, self.backbone, 0.996) utils.update_momentum(self.anchor_projection_head, self.projection_head, 0.996) views = batch[0] views = [view.to(self.device, non_blocking=True) for view in views] targets = views[0] anchors = views[1] anchors_focal = torch.concat(views[2:], dim=0) targets_out = self.backbone(targets) targets_out = self.projection_head(targets_out) anchors_out = self.encode_masked(anchors) anchors_focal_out = self.encode_masked(anchors_focal) anchors_out = torch.cat([anchors_out, anchors_focal_out], dim=0) loss = self.criterion(anchors_out, targets_out, self.prototypes.data) return loss def encode_masked(self, anchors): batch_size, _, _, width = anchors.shape seq_length = (width // self.anchor_backbone.patch_size) ** 2 idx_keep, _ = utils.random_token_mask( size=(batch_size, seq_length), mask_ratio=self.mask_ratio, device=self.device, ) out = self.anchor_backbone(anchors, idx_keep) return self.anchor_projection_head(out) def configure_optimizers(self): params = [ *list(self.anchor_backbone.parameters()), *list(self.anchor_projection_head.parameters()), self.prototypes, ] optim = torch.optim.AdamW(params, lr=1.5e-4) return optim model = PMSN() transform = MSNTransform() # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=64, shuffle=True, drop_last=True, num_workers=8, ) gpus = torch.cuda.device_count() # Train with DDP on multiple gpus. Distributed sampling is also enabled with # replace_sampler_ddp=True. trainer = pl.Trainer( max_epochs=10, devices="auto", accelerator="gpu", strategy="ddp", use_distributed_sampler=True, # or replace_sampler_ddp=True for PyTorch Lightning <2.0 ) trainer.fit(model=model, train_dataloaders=dataloader)
3,999
32.057851
91
py
lightly
lightly-master/examples/pytorch_lightning_distributed/simclr.py
import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import NTXentLoss from lightly.models.modules import SimCLRProjectionHead from lightly.transforms.simclr_transform import SimCLRTransform class SimCLR(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = SimCLRProjectionHead(512, 2048, 2048) # enable gather_distributed to gather features from all gpus # before calculating the loss self.criterion = NTXentLoss(gather_distributed=True) def forward(self, x): x = self.backbone(x).flatten(start_dim=1) z = self.projection_head(x) return z def training_step(self, batch, batch_index): (x0, x1) = batch[0] z0 = self.forward(x0) z1 = self.forward(x1) loss = self.criterion(z0, z1) return loss def configure_optimizers(self): optim = torch.optim.SGD(self.parameters(), lr=0.06) return optim model = SimCLR() transform = SimCLRTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) # Train with DDP and use Synchronized Batch Norm for a more accurate batch norm # calculation. Distributed sampling is also enabled with replace_sampler_ddp=True. trainer = pl.Trainer( max_epochs=10, devices="auto", accelerator="gpu", strategy="ddp", sync_batchnorm=True, use_distributed_sampler=True, # or replace_sampler_ddp=True for PyTorch Lightning <2.0 ) trainer.fit(model=model, train_dataloaders=dataloader)
1,998
28.835821
91
py
lightly
lightly-master/examples/pytorch_lightning_distributed/simmim.py
import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.models import utils from lightly.models.modules import masked_autoencoder from lightly.transforms.mae_transform import MAETransform # Same transform as MAE class SimMIM(pl.LightningModule): def __init__(self): super().__init__() decoder_dim = vit.hidden_dim vit = torchvision.models.vit_b_32(pretrained=False) self.mask_ratio = 0.75 self.patch_size = vit.patch_size self.sequence_length = vit.seq_length self.mask_token = nn.Parameter(torch.zeros(1, 1, decoder_dim)) # same backbone as MAE self.backbone = masked_autoencoder.MAEBackbone.from_vit(vit) # the decoder is a simple linear layer self.decoder = nn.Linear(vit.hidden_dim, vit.patch_size**2 * 3) # L1 loss as paper suggestion self.criterion = nn.L1Loss() def forward_encoder(self, images, batch_size, idx_mask): # pass all the tokens to the encoder, both masked and non masked ones tokens = self.backbone.images_to_tokens(images, prepend_class_token=True) tokens_masked = utils.mask_at_index(tokens, idx_mask, self.mask_token) return self.backbone.encoder(tokens_masked) def forward_decoder(self, x_encoded): return self.decoder(x_encoded) def training_step(self, batch, batch_idx): views = batch[0] images = views[0] # views contains only a single view batch_size = images.shape[0] idx_keep, idx_mask = utils.random_token_mask( size=(batch_size, self.sequence_length), mask_ratio=self.mask_ratio, device=images.device, ) # Encoding... x_encoded = self.forward_encoder(images, batch_size, idx_mask) x_encoded_masked = utils.get_at_index(x_encoded, idx_mask) # Decoding... x_out = self.forward_decoder(x_encoded_masked) # get image patches for masked tokens patches = utils.patchify(images, self.patch_size) # must adjust idx_mask for missing class token target = utils.get_at_index(patches, idx_mask - 1) loss = self.criterion(x_out, target) return loss def configure_optimizers(self): optim = torch.optim.AdamW(self.parameters(), lr=1.5e-4) return optim model = SimMIM() device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device) transform = MAETransform() # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=8, shuffle=True, drop_last=True, num_workers=8, ) # Train with DDP on multiple gpus. Distributed sampling is also enabled with # replace_sampler_ddp=True. trainer = pl.Trainer( max_epochs=10, devices="auto", accelerator="gpu", strategy="ddp", use_distributed_sampler=True, # or replace_sampler_ddp=True for PyTorch Lightning <2.0 ) trainer.fit(model=model, train_dataloaders=dataloader)
3,328
30.704762
91
py
lightly
lightly-master/examples/pytorch_lightning_distributed/simsiam.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import NegativeCosineSimilarity from lightly.models.modules import SimSiamPredictionHead, SimSiamProjectionHead from lightly.transforms import SimSiamTransform class SimSiam(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = SimSiamProjectionHead(512, 512, 128) self.prediction_head = SimSiamPredictionHead(128, 64, 128) self.criterion = NegativeCosineSimilarity() def forward(self, x): f = self.backbone(x).flatten(start_dim=1) z = self.projection_head(f) p = self.prediction_head(z) z = z.detach() return z, p def training_step(self, batch, batch_idx): (x0, x1) = batch[0] z0, p0 = self.forward(x0) z1, p1 = self.forward(x1) loss = 0.5 * (self.criterion(z0, p1) + self.criterion(z1, p0)) return loss def configure_optimizers(self): optim = torch.optim.SGD(self.parameters(), lr=0.06) return optim resnet = torchvision.models.resnet18() backbone = nn.Sequential(*list(resnet.children())[:-1]) model = SimSiam() transform = SimSiamTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) # Train with DDP and use Synchronized Batch Norm for a more accurate batch norm # calculation. Distributed sampling is also enabled with replace_sampler_ddp=True. trainer = pl.Trainer( max_epochs=10, devices="auto", accelerator="gpu", strategy="ddp", sync_batchnorm=True, use_distributed_sampler=True, # or replace_sampler_ddp=True for PyTorch Lightning <2.0 ) trainer.fit(model=model, train_dataloaders=dataloader)
2,368
31.452055
91
py
lightly
lightly-master/examples/pytorch_lightning_distributed/swav.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import SwaVLoss from lightly.models.modules import SwaVProjectionHead, SwaVPrototypes from lightly.transforms.swav_transform import SwaVTransform class SwaV(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = SwaVProjectionHead(512, 512, 128) self.prototypes = SwaVPrototypes(128, n_prototypes=512) # enable sinkhorn_gather_distributed to gather features from all gpus # while running the sinkhorn algorithm in the loss calculation self.criterion = SwaVLoss(sinkhorn_gather_distributed=True) def forward(self, x): x = self.backbone(x).flatten(start_dim=1) x = self.projection_head(x) x = nn.functional.normalize(x, dim=1, p=2) p = self.prototypes(x) return p def training_step(self, batch, batch_idx): self.prototypes.normalize() views = batch[0] multi_crop_features = [self.forward(view.to(self.device)) for view in views] high_resolution = multi_crop_features[:2] low_resolution = multi_crop_features[2:] loss = self.criterion(high_resolution, low_resolution) return loss def configure_optimizers(self): optim = torch.optim.Adam(self.parameters(), lr=0.001) return optim model = SwaV() transform = SwaVTransform() # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=128, shuffle=True, drop_last=True, num_workers=8, ) # Train with DDP and use Synchronized Batch Norm for a more accurate batch norm # calculation. Distributed sampling is also enabled with replace_sampler_ddp=True. trainer = pl.Trainer( max_epochs=10, devices="auto", accelerator="gpu", strategy="ddp", sync_batchnorm=True, use_distributed_sampler=True, # or replace_sampler_ddp=True for PyTorch Lightning <2.0 ) trainer.fit(model=model, train_dataloaders=dataloader)
2,671
32.4
91
py
lightly
lightly-master/examples/pytorch_lightning_distributed/tico.py
import copy import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss.tico_loss import TiCoLoss from lightly.models.modules.heads import TiCoProjectionHead from lightly.models.utils import deactivate_requires_grad, update_momentum from lightly.transforms.simclr_transform import SimCLRTransform from lightly.utils.scheduler import cosine_schedule class TiCo(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = TiCoProjectionHead(512, 1024, 256) self.backbone_momentum = copy.deepcopy(self.backbone) self.projection_head_momentum = copy.deepcopy(self.projection_head) deactivate_requires_grad(self.backbone_momentum) deactivate_requires_grad(self.projection_head_momentum) self.criterion = TiCoLoss() def forward(self, x): y = self.backbone(x).flatten(start_dim=1) z = self.projection_head(y) return z def forward_momentum(self, x): y = self.backbone_momentum(x).flatten(start_dim=1) z = self.projection_head_momentum(y) z = z.detach() return z def training_step(self, batch, batch_idx): (x0, x1) = batch[0] momentum = cosine_schedule(self.current_epoch, 10, 0.996, 1) update_momentum(self.backbone, self.backbone_momentum, m=momentum) update_momentum(self.projection_head, self.projection_head_momentum, m=momentum) x0 = x0.to(self.device) x1 = x1.to(self.device) z0 = self.forward(x0) z1 = self.forward_momentum(x1) loss = self.criterion(z0, z1) return loss def configure_optimizers(self): return torch.optim.SGD(self.parameters(), lr=0.06) model = TiCo() transform = SimCLRTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) # Train with DDP and use Synchronized Batch Norm for a more accurate batch norm # calculation. Distributed sampling is also enabled with replace_sampler_ddp=True. trainer = pl.Trainer( max_epochs=10, devices="auto", accelerator="gpu", strategy="ddp", sync_batchnorm=True, use_distributed_sampler=True, # or replace_sampler_ddp=True for PyTorch Lightning <2.0 ) trainer.fit(model=model, train_dataloaders=dataloader)
2,734
31.176471
91
py
lightly
lightly-master/examples/pytorch_lightning_distributed/vicreg.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import VICRegLoss ## The projection head is the same as the Barlow Twins one from lightly.models.modules import BarlowTwinsProjectionHead from lightly.transforms.vicreg_transform import VICRegTransform class VICReg(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-1]) self.projection_head = BarlowTwinsProjectionHead(512, 2048, 2048) # enable gather_distributed to gather features from all gpus # before calculating the loss self.criterion = VICRegLoss(gather_distributed=True) def forward(self, x): x = self.backbone(x).flatten(start_dim=1) z = self.projection_head(x) return z def training_step(self, batch, batch_index): (x0, x1) = batch[0] z0 = self.forward(x0) z1 = self.forward(x1) loss = self.criterion(z0, z1) return loss def configure_optimizers(self): optim = torch.optim.SGD(self.parameters(), lr=0.06) return optim model = VICReg() transform = VICRegTransform(input_size=32) dataset = torchvision.datasets.CIFAR10( "datasets/cifar10", download=True, transform=transform ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder", transform=transform) dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) # Train with DDP and use Synchronized Batch Norm for a more accurate batch norm # calculation. Distributed sampling is also enabled with replace_sampler_ddp=True. trainer = pl.Trainer( max_epochs=10, devices="auto", accelerator="gpu", strategy="ddp", sync_batchnorm=True, use_distributed_sampler=True, # or replace_sampler_ddp=True for PyTorch Lightning <2.0 ) trainer.fit(model=model, train_dataloaders=dataloader)
2,268
30.082192
91
py
lightly
lightly-master/examples/pytorch_lightning_distributed/vicregl.py
# Note: The model and training settings do not follow the reference settings # from the paper. The settings are chosen such that the example can easily be # run on a small dataset with a single GPU. import pytorch_lightning as pl import torch import torchvision from torch import nn from lightly.loss import VICRegLLoss ## The global projection head is the same as the Barlow Twins one from lightly.models.modules import BarlowTwinsProjectionHead from lightly.models.modules.heads import VicRegLLocalProjectionHead from lightly.transforms.vicregl_transform import VICRegLTransform class VICRegL(pl.LightningModule): def __init__(self): super().__init__() resnet = torchvision.models.resnet18() self.backbone = nn.Sequential(*list(resnet.children())[:-2]) self.projection_head = BarlowTwinsProjectionHead(512, 2048, 2048) self.local_projection_head = VicRegLLocalProjectionHead(512, 128, 128) self.average_pool = nn.AdaptiveAvgPool2d(output_size=(1, 1)) self.criterion = VICRegLLoss() def forward(self, x): x = self.backbone(x) y = self.average_pool(x).flatten(start_dim=1) z = self.projection_head(y) y_local = x.permute(0, 2, 3, 1) # (B, D, W, H) to (B, W, H, D) z_local = self.local_projection_head(y_local) return z, z_local def training_step(self, batch, batch_index): views_and_grids = batch[0] views = views_and_grids[: len(views_and_grids) // 2] grids = views_and_grids[len(views_and_grids) // 2 :] features = [self.forward(view) for view in views] loss = self.criterion( global_view_features=features[:2], global_view_grids=grids[:2], local_view_features=features[2:], local_view_grids=grids[2:], ) return loss def configure_optimizers(self): optim = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9) return optim model = VICRegL() transform = VICRegLTransform(n_local_views=0) # we ignore object detection annotations by setting target_transform to return 0 dataset = torchvision.datasets.VOCDetection( "datasets/pascal_voc", download=True, transform=transform, target_transform=lambda t: 0, ) # or create a dataset from a folder containing images or videos: # dataset = LightlyDataset("path/to/folder") dataloader = torch.utils.data.DataLoader( dataset, batch_size=256, shuffle=True, drop_last=True, num_workers=8, ) # Train with DDP and use Synchronized Batch Norm for a more accurate batch norm # calculation. Distributed sampling is also enabled with replace_sampler_ddp=True. trainer = pl.Trainer( max_epochs=10, devices="auto", accelerator="gpu", strategy="ddp", sync_batchnorm=True, use_distributed_sampler=True, # or replace_sampler_ddp=True for PyTorch Lightning <2.0 ) trainer.fit(model=model, train_dataloaders=dataloader)
2,967
33.511628
91
py
lightly
lightly-master/lightly/__init__.py
"""Lightly is a computer vision framework for self-supervised learning. With Lightly you can train deep learning models using self-supervision. This means, that you don't require any labels to train a model. Lightly has been built to help you understand and work with large unlabeled datasets. It is built on top of PyTorch and therefore fully compatible with other frameworks such as Fast.ai. The framework is structured into the following modules: - **api**: The lightly.api module handles communication with the Lightly web-app. - **cli**: The lightly.cli module provides a command-line interface for training self-supervised models and embedding images. Furthermore, the command-line tool can be used to upload and download images from/to the Lightly web-app. - **core**: The lightly.core module offers one-liners for simple self-supervised learning. - **data**: The lightly.data module provides a dataset wrapper and collate functions. The collate functions are in charge of the data augmentations which are crucial for self-supervised learning. - **loss**: The lightly.loss module contains implementations of popular self-supervised training loss functions. - **models**: The lightly.models module holds the implementation of the ResNet as well as heads for self-supervised methods. It currently implements the heads of: - Barlow Twins - BYOL - MoCo - NNCLR - SimCLR - SimSiam - SwaV - **transforms**: The lightly.transforms module implements custom data transforms. Currently implements: - Gaussian Blur - Random Rotation - Random Solarization - **utils**: The lightly.utils package provides global utility methods. The io module contains utility to save and load embeddings in a format which is understood by the Lightly library. """ # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved __name__ = "lightly" __version__ = "1.4.12" import os try: # See (https://github.com/PyTorchLightning/pytorch-lightning) # This variable is injected in the __builtins__ by the build # process. It used to enable importing subpackages of skimage when # the binaries are not built __LIGHTLY_SETUP__ except NameError: __LIGHTLY_SETUP__ = False if __LIGHTLY_SETUP__: # setting up lightly msg = f"Partial import of {__name__}=={__version__} during build process." print(msg) else: # see if torchvision vision transformer is available try: import torchvision.models.vision_transformer _torchvision_vit_available = True except ( RuntimeError, # Different CUDA versions for torch and torchvision OSError, # Different CUDA versions for torch and torchvision (old) ImportError, # No installation or old version of torchvision ): _torchvision_vit_available = False if os.getenv("LIGHTLY_DID_VERSION_CHECK", "False") == "False": os.environ["LIGHTLY_DID_VERSION_CHECK"] = "True" from multiprocessing import current_process if current_process().name == "MainProcess": from lightly.api.version_checking import is_latest_version try: is_latest_version(current_version=__version__) except Exception: # Version check should never break the package. pass
3,371
26.867769
88
py
lightly
lightly-master/lightly/core.py
""" Contains the core functionality of the lightly Python package. """ # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved import os from typing import List, Tuple import numpy as np import yaml import lightly.cli as cli from lightly.cli.embed_cli import _embed_cli from lightly.cli.lightly_cli import _lightly_cli from lightly.cli.train_cli import _train_cli def _get_config_path(config_path): """Find path to yaml config file Args: config_path: (str) Path to config.yaml file Returns: Path to config.yaml if specified else default config.yaml Raises: ValueError: If the config_path is not None but doesn't exist """ if config_path is None: dirname = os.path.dirname(cli.__file__) config_path = os.path.join(dirname, "config/config.yaml") if not os.path.exists(config_path): raise ValueError("Config path {} does not exist!".format(config_path)) return config_path def _load_config_file(config_path): """Load a yaml config file Args: config_path: (str) Path to config.yaml file Returns: Dictionary with configs from config.yaml """ Loader = yaml.FullLoader with open(config_path, "r") as config_file: cfg = yaml.load(config_file, Loader=Loader) return cfg def _add_kwargs(cfg, kwargs): """Add keyword arguments to config Args: cfg: (dict) Dictionary of configs from config.yaml kwargs: (dict) Dictionary of keyword arguments Returns: Union of cfg and kwargs """ for key, item in kwargs.items(): if isinstance(item, dict): if key in cfg: cfg[key] = _add_kwargs(cfg[key], item) else: cfg[key] = item else: cfg[key] = item return cfg def train_model_and_embed_images( config_path: str = None, **kwargs ) -> Tuple[np.ndarray, List[int], List[str]]: """Train a self-supervised model and use it to embed images. First trains a modle using the _train_cli(), then embeds with the _embed_cli(). All arguments passed to the CLI functions can also be passed to this function (see below for an example). Args: config_path: Path to config.yaml. If None, the default configs will be used. **kwargs: Overwrite default configs py passing keyword arguments. Returns: Embeddings, labels, and filenames of the images. Embeddings are of shape (n_samples, embedding_size) len(labels) = len(filenames) = n_samples Examples: >>> import lightly >>> >>> # train a model and embed images with default configs >>> embeddings, _, _ = lightly.train_model_and_embed_images( >>> input_dir='path/to/data') >>> >>> # train a model and embed images with separate config file >>> my_config_path = 'my/config/file.yaml' >>> embeddings, _, _ = lightly.train_model_and_embed_images( >>> input_dir='path/to/data', config_path=my_config_path) >>> >>> # train a model and embed images with default settings + overwrites >>> my_trainer = {max_epochs: 10} >>> embeddings, _, _ = lightly.train_model_and_embed_images( >>> input_dir='path/to/data', trainer=my_trainer) """ config_path = _get_config_path(config_path) config_args = _load_config_file(config_path) config_args = _add_kwargs(config_args, kwargs) checkpoint = _train_cli(config_args, is_cli_call=False) config_args["checkpoint"] = checkpoint embeddings, labels, filenames = _embed_cli(config_args, is_cli_call=False) return embeddings, labels, filenames def train_embedding_model(config_path: str = None, **kwargs): """Train a self-supervised model. Calls the same function as lightly-train. All arguments passed to lightly-train can also be passed to this function (see below for an example). Args: config_path: Path to config.yaml. If None, the default configs will be used. **kwargs: Overwrite default configs py passing keyword arguments. Returns: Path to checkpoint of the trained embedding model. Examples: >>> import lightly >>> >>> # train a model with default configs >>> checkpoint_path = lightly.train_embedding_model( >>> input_dir='path/to/data') >>> >>> # train a model with separate config file >>> my_config_path = 'my/config/file.yaml' >>> checkpoint_path = lightly.train_embedding_model( >>> input_dir='path/to/data', config_path=my_config_path) >>> >>> # train a model with default settings and overwrites: large batch >>> # sizes are benefitial for self-supervised training and more >>> # workers speed up the dataloading process. >>> my_loader = { >>> batch_size: 100, >>> num_workers: 8, >>> } >>> checkpoint_path = lightly.train_embedding_model( >>> input_dir='path/to/data', loader=my_loader) >>> # the command above is equivalent to: >>> # lightly-train input_dir='path/to/data' loader.batch_size=100 loader.num_workers=8 """ config_path = _get_config_path(config_path) config_args = _load_config_file(config_path) config_args = _add_kwargs(config_args, kwargs) return _train_cli(config_args, is_cli_call=False) def embed_images(checkpoint: str, config_path: str = None, **kwargs): """Embed images with a self-supervised model. Calls the same function as lightly-embed. All arguments passed to lightly-embed can also be passed to this function (see below for an example). Args: checkpoint: Path to the checkpoint file for the embedding model. config_path: Path to config.yaml. If None, the default configs will be used. **kwargs: Overwrite default configs py passing keyword arguments. Returns: Embeddings, labels, and filenames of the images. Examples: >>> import lightly >>> my_checkpoint_path = 'path/to/checkpoint.ckpt' >>> >>> # embed images with default configs >>> embeddings, _, _ = lightly.embed_images( >>> my_checkpoint_path, input_dir='path/to/data') >>> >>> # embed images with separate config file >>> my_config_path = 'my/config/file.yaml' >>> embeddings, _, _ = lightly.embed_images( >>> my_checkpoint_path, input_dir='path/to/data', config_path=my_config_path) >>> >>> # embed images with default settings and overwrites: at inference, >>> # we can use larger input_sizes because it requires less memory. >>> my_collate = {input_size: 256} >>> embeddings, _, _ = lightly.embed_images( >>> my_checkpoint_path, input_dir='path/to/data', collate=my_collate) >>> # the command above is equivalent to: >>> # lightly-embed input_dir='path/to/data' collate.input_size=256 """ config_path = _get_config_path(config_path) config_args = _load_config_file(config_path) config_args = _add_kwargs(config_args, kwargs) config_args["checkpoint"] = checkpoint return _embed_cli(config_args, is_cli_call=False)
7,426
32.606335
95
py
lightly
lightly-master/lightly/active_learning/__init__.py
import warnings def raise_active_learning_deprecation_warning(): warnings.warn( "Using active learning via the lightly package is deprecated and will be removed soon. " "Please use the Lightly Solution instead. " "See https://docs.lightly.ai for more information and tutorials on doing active learning.", DeprecationWarning, stacklevel=2, )
391
31.666667
99
py
lightly
lightly-master/lightly/active_learning/config/__init__.py
""" Collection of Selection Configurations """ # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved from lightly.active_learning.config.selection_config import SelectionConfig
200
27.714286
75
py
lightly
lightly-master/lightly/active_learning/config/selection_config.py
import warnings from datetime import datetime from lightly.active_learning import raise_active_learning_deprecation_warning from lightly.openapi_generated.swagger_client.models.sampling_method import ( SamplingMethod, ) class SelectionConfig: """Configuration class for a selection. Attributes: method: The method to use for selection, one of CORESET, RANDOM, CORAL, ACTIVE_LEARNING n_samples: The maximum number of samples to be chosen by the selection including the samples in the preselected tag. One of the stopping conditions. min_distance: The minimum distance of samples in the chosen set, one of the stopping conditions. name: The name of this selection, defaults to a name consisting of all other attributes and the datetime. A new tag will be created in the web-app under this name. Examples: >>> # select 100 images with CORESET selection >>> config = SelectionConfig(method=SamplingMethod.CORESET, n_samples=100) >>> >>> # give your selection a name >>> config = SelectionConfig(method=SamplingMethod.CORESET, n_samples=100, name='my-selection') >>> >>> # use minimum distance between samples as stopping criterion >>> config = SelectionConfig(method=SamplingMethod.CORESET, n_samples=-1, min_distance=0.1) """ def __init__( self, method: SamplingMethod = SamplingMethod.CORESET, n_samples: int = 32, min_distance: float = -1, name: str = None, ): raise_active_learning_deprecation_warning() self.method = method self.n_samples = n_samples self.min_distance = min_distance if name is None: date_time = datetime.now().strftime("%m_%d_%Y__%H_%M_%S") name = f"{self.method}_{self.n_samples}_{self.min_distance}_{date_time}" self.name = name
2,001
35.4
103
py
lightly
lightly-master/lightly/api/__init__.py
""" The lightly.api module provides access to the Lightly API.""" # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved from lightly.api import patch as _patch from lightly.api.api_workflow_artifacts import ArtifactNotExist from lightly.api.api_workflow_client import ApiWorkflowClient from lightly.openapi_generated.swagger_client.api_client import ( Configuration as _Configuration, ) # Make ApiWorkflowClient and swagger classes picklable. _patch.make_swagger_configuration_picklable( configuration_cls=_Configuration, )
555
33.75
65
py
lightly
lightly-master/lightly/api/api_workflow_artifacts.py
import os from lightly.api import download from lightly.openapi_generated.swagger_client.models import ( DockerRunArtifactData, DockerRunArtifactType, DockerRunData, ) class ArtifactNotExist(Exception): pass class _ArtifactsMixin: def download_compute_worker_run_artifacts( self, run: DockerRunData, output_dir: str, timeout: int = 60, ) -> None: """Downloads all artifacts from a run. Args: run: Run from which to download artifacts. output_dir: Output directory where artifacts will be saved. timeout: Timeout in seconds after which an artifact download is interrupted. Examples: >>> # schedule run >>> scheduled_run_id = client.schedule_compute_worker_run(...) >>> >>> # wait until run completed >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id=scheduled_run_id): >>> pass >>> >>> # download artifacts >>> run = client.get_compute_worker_run_from_scheduled_run(scheduled_run_id=scheduled_run_id) >>> client.download_compute_worker_run_artifacts(run=run, output_dir="my_run/artifacts") """ if run.artifacts is None: return for artifact in run.artifacts: self._download_compute_worker_run_artifact( run_id=run.id, artifact_id=artifact.id, output_path=os.path.join(output_dir, artifact.file_name), timeout=timeout, ) def download_compute_worker_run_checkpoint( self, run: DockerRunData, output_path: str, timeout: int = 60, ) -> None: """Downloads the last training checkpoint from a run. See our docs for more information regarding checkpoints: https://docs.lightly.ai/docs/train-a-self-supervised-model#checkpoints Args: run: Run from which to download the checkpoint. output_path: Path where checkpoint will be saved. timeout: Timeout in seconds after which download is interrupted. Raises: ArtifactNotExist: If the run has no checkpoint artifact or the checkpoint has not yet been uploaded. Examples: >>> # schedule run >>> scheduled_run_id = client.schedule_compute_worker_run(...) >>> >>> # wait until run completed >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id=scheduled_run_id): >>> pass >>> >>> # download checkpoint >>> run = client.get_compute_worker_run_from_scheduled_run(scheduled_run_id=scheduled_run_id) >>> client.download_compute_worker_run_checkpoint(run=run, output_path="my_checkpoint.ckpt") """ self._download_compute_worker_run_artifact_by_type( run=run, artifact_type=DockerRunArtifactType.CHECKPOINT, output_path=output_path, timeout=timeout, ) def download_compute_worker_run_report_pdf( self, run: DockerRunData, output_path: str, timeout: int = 60, ) -> None: """Download the report in pdf format from a run. Args: run: Run from which to download the report. output_path: Path where report will be saved. timeout: Timeout in seconds after which download is interrupted. Raises: ArtifactNotExist: If the run has no report artifact or the report has not yet been uploaded. Examples: >>> # schedule run >>> scheduled_run_id = client.schedule_compute_worker_run(...) >>> >>> # wait until run completed >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id=scheduled_run_id): >>> pass >>> >>> # download report >>> run = client.get_compute_worker_run_from_scheduled_run(scheduled_run_id=scheduled_run_id) >>> client.download_compute_worker_run_report_pdf(run=run, output_path="report.pdf") """ self._download_compute_worker_run_artifact_by_type( run=run, artifact_type=DockerRunArtifactType.REPORT_PDF, output_path=output_path, timeout=timeout, ) def download_compute_worker_run_report_json( self, run: DockerRunData, output_path: str, timeout: int = 60, ) -> None: """Download the report in json format from a run. Args: run: Run from which to download the report. output_path: Path where report will be saved. timeout: Timeout in seconds after which download is interrupted. Raises: ArtifactNotExist: If the run has no report artifact or the report has not yet been uploaded. Examples: >>> # schedule run >>> scheduled_run_id = client.schedule_compute_worker_run(...) >>> >>> # wait until run completed >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id=scheduled_run_id): >>> pass >>> >>> # download checkpoint >>> run = client.get_compute_worker_run_from_scheduled_run(scheduled_run_id=scheduled_run_id) >>> client.download_compute_worker_run_report_json(run=run, output_path="report.json") """ self._download_compute_worker_run_artifact_by_type( run=run, artifact_type=DockerRunArtifactType.REPORT_JSON, output_path=output_path, timeout=timeout, ) def download_compute_worker_run_log( self, run: DockerRunData, output_path: str, timeout: int = 60, ) -> None: """Download the log file from a run. Args: run: Run from which to download the log file. output_path: Path where log file will be saved. timeout: Timeout in seconds after which download is interrupted. Raises: ArtifactNotExist: If the run has no log artifact or the log file has not yet been uploaded. Examples: >>> # schedule run >>> scheduled_run_id = client.schedule_compute_worker_run(...) >>> >>> # wait until run completed >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id=scheduled_run_id): >>> pass >>> >>> # download log file >>> run = client.get_compute_worker_run_from_scheduled_run(scheduled_run_id=scheduled_run_id) >>> client.download_compute_worker_run_log(run=run, output_path="log.txt") """ self._download_compute_worker_run_artifact_by_type( run=run, artifact_type=DockerRunArtifactType.LOG, output_path=output_path, timeout=timeout, ) def download_compute_worker_run_memory_log( self, run: DockerRunData, output_path: str, timeout: int = 60, ) -> None: """Download the memory consumption log file from a run. Args: run: Run from which to download the memory log file. output_path: Path where memory log file will be saved. timeout: Timeout in seconds after which download is interrupted. Raises: ArtifactNotExist: If the run has no memory log artifact or the memory log file has not yet been uploaded. Examples: >>> # schedule run >>> scheduled_run_id = client.schedule_compute_worker_run(...) >>> >>> # wait until run completed >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id=scheduled_run_id): >>> pass >>> >>> # download memory log file >>> run = client.get_compute_worker_run_from_scheduled_run(scheduled_run_id=scheduled_run_id) >>> client.download_compute_worker_run_memory_log(run=run, output_path="memlog.txt") """ self._download_compute_worker_run_artifact_by_type( run=run, artifact_type=DockerRunArtifactType.MEMLOG, output_path=output_path, timeout=timeout, ) def download_compute_worker_run_corruptness_check_information( self, run: DockerRunData, output_path: str, timeout: int = 60, ) -> None: """Download the corruptness check information file from a run. Args: run: Run from which to download the file. output_path: Path where the file will be saved. timeout: Timeout in seconds after which download is interrupted. Raises: ArtifactNotExist: If the run has no corruptness check information artifact or the file has not yet been uploaded. Examples: >>> # schedule run >>> scheduled_run_id = client.schedule_compute_worker_run(...) >>> >>> # wait until run completed >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id=scheduled_run_id): >>> pass >>> >>> # download corruptness check information file >>> run = client.get_compute_worker_run_from_scheduled_run(scheduled_run_id=scheduled_run_id) >>> client.download_compute_worker_run_corruptness_check_information(run=run, output_path="corruptness_check_information.json") >>> >>> # print all corrupt samples and corruptions >>> with open("corruptness_check_information.json", 'r') as f: >>> corruptness_check_information = json.load(f) >>> for sample_name, error in corruptness_check_information["corrupt_samples"].items(): >>> print(f"Sample '{sample_name}' is corrupt because of the error '{error}'.") """ self._download_compute_worker_run_artifact_by_type( run=run, artifact_type=DockerRunArtifactType.CORRUPTNESS_CHECK_INFORMATION, output_path=output_path, timeout=timeout, ) def download_compute_worker_run_sequence_information( self, run: DockerRunData, output_path: str, timeout: int = 60, ) -> None: """Download the sequence information from a run. Args: run: Run from which to download the the file. output_path: Path where the file will be saved. timeout: Timeout in seconds after which download is interrupted. Raises: ArtifactNotExist: If the run has no sequence information artifact or the file has not yet been uploaded. Examples: >>> # schedule run >>> scheduled_run_id = client.schedule_compute_worker_run(...) >>> >>> # wait until run completed >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id=scheduled_run_id): >>> pass >>> >>> # download sequence information file >>> run = client.get_compute_worker_run_from_scheduled_run(scheduled_run_id=scheduled_run_id) >>> client.download_compute_worker_run_sequence_information(run=run, output_path="sequence_information.json") """ self._download_compute_worker_run_artifact_by_type( run=run, artifact_type=DockerRunArtifactType.SEQUENCE_INFORMATION, output_path=output_path, timeout=timeout, ) def _download_compute_worker_run_artifact_by_type( self, run: DockerRunData, artifact_type: str, output_path: str, timeout: int, ) -> None: artifact = self._get_artifact_by_type(artifact_type, run) self._download_compute_worker_run_artifact( run_id=run.id, artifact_id=artifact.id, output_path=output_path, timeout=timeout, ) def _get_artifact_by_type( self, artifact_type: str, run: DockerRunData ) -> DockerRunArtifactData: if run.artifacts is None: raise ArtifactNotExist(f"Run has no artifacts.") try: artifact = next(art for art in run.artifacts if art.type == artifact_type) except StopIteration: raise ArtifactNotExist( f"No artifact with type '{artifact_type}' in artifacts." ) return artifact def _download_compute_worker_run_artifact( self, run_id: str, artifact_id: str, output_path: str, timeout: int, ) -> None: read_url = self._compute_worker_api.get_docker_run_artifact_read_url_by_id( run_id=run_id, artifact_id=artifact_id, ) download.download_and_write_file( url=read_url, output_path=output_path, request_kwargs=dict(timeout=timeout), ) def get_compute_worker_run_checkpoint_url( self, run: DockerRunData, ) -> str: """Gets the download url of the last training checkpoint from a run. See our docs for more information regarding checkpoints: https://docs.lightly.ai/docs/train-a-self-supervised-model#checkpoints Args: run: Run from which to download the checkpoint. Returns: The url from which the checkpoint can be downloaded. Raises: ArtifactNotExist: If the run has no checkpoint artifact or the checkpoint has not yet been uploaded. Examples: >>> # schedule run >>> scheduled_run_id = client.schedule_compute_worker_run(...) >>> >>> # wait until run completed >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id=scheduled_run_id): >>> pass >>> >>> # get checkpoint read_url >>> run = client.get_compute_worker_run_from_scheduled_run(scheduled_run_id=scheduled_run_id) >>> checkpoint_read_url = client.get_compute_worker_run_checkpoint_url(run=run) """ artifact = self._get_artifact_by_type( artifact_type=DockerRunArtifactType.CHECKPOINT, run=run ) read_url = self._compute_worker_api.get_docker_run_artifact_read_url_by_id( run_id=run.id, artifact_id=artifact.id ) return read_url
15,450
34.356979
139
py
lightly
lightly-master/lightly/api/api_workflow_client.py
import os import platform import warnings from io import IOBase from typing import * import requests from requests import Response from lightly.__init__ import __version__ from lightly.api import utils, version_checking from lightly.api.api_workflow_artifacts import _ArtifactsMixin from lightly.api.api_workflow_collaboration import _CollaborationMixin from lightly.api.api_workflow_compute_worker import _ComputeWorkerMixin from lightly.api.api_workflow_datasets import _DatasetsMixin from lightly.api.api_workflow_datasources import _DatasourcesMixin from lightly.api.api_workflow_download_dataset import _DownloadDatasetMixin from lightly.api.api_workflow_export import _ExportDatasetMixin from lightly.api.api_workflow_predictions import _PredictionsMixin from lightly.api.api_workflow_selection import _SelectionMixin from lightly.api.api_workflow_tags import _TagsMixin from lightly.api.api_workflow_upload_embeddings import _UploadEmbeddingsMixin from lightly.api.api_workflow_upload_metadata import _UploadCustomMetadataMixin from lightly.api.swagger_api_client import LightlySwaggerApiClient from lightly.api.utils import DatasourceType from lightly.api.version_checking import LightlyAPITimeoutException from lightly.openapi_generated.swagger_client.api import ( CollaborationApi, DatasetsApi, DatasourcesApi, DockerApi, EmbeddingsApi, JobsApi, MappingsApi, MetaDataConfigurationsApi, PredictionsApi, QuotaApi, SamplesApi, SamplingsApi, ScoresApi, TagsApi, ) from lightly.openapi_generated.swagger_client.models import Creator, DatasetData from lightly.openapi_generated.swagger_client.rest import ApiException from lightly.utils import reordering # Env variable for server side encryption on S3 LIGHTLY_S3_SSE_KMS_KEY = "LIGHTLY_S3_SSE_KMS_KEY" class ApiWorkflowClient( _UploadEmbeddingsMixin, _SelectionMixin, _DownloadDatasetMixin, _DatasetsMixin, _UploadCustomMetadataMixin, _TagsMixin, _DatasourcesMixin, _ComputeWorkerMixin, _CollaborationMixin, _PredictionsMixin, _ArtifactsMixin, _ExportDatasetMixin, ): """Provides a uniform interface to communicate with the Lightly API. The APIWorkflowClient is used to communicate with the Lightly API. The client can run also more complex workflows which include multiple API calls at once. The client can be used in combination with the active learning agent. Args: token: The token of the user. If it is not passed in during initialization, the token will be read from the environment variable LIGHTLY_TOKEN. For further information on how to get a token, see: https://docs.lightly.ai/docs/install-lightly#api-token dataset_id: The id of the dataset. If it is not set, but used by a workflow, the last modfied dataset is taken by default. embedding_id: The id of the embedding to use. If it is not set, but used by a workflow, the newest embedding is taken by default creator: Creator passed to API requests. """ def __init__( self, token: Optional[str] = None, dataset_id: Optional[str] = None, embedding_id: Optional[str] = None, creator: str = Creator.USER_PIP, ): try: if not version_checking.is_compatible_version(__version__): warnings.warn( UserWarning( ( f"Incompatible version of lightly pip package. " f"Please upgrade to the latest version " f"to be able to access the api." ) ) ) except ( ValueError, ApiException, LightlyAPITimeoutException, AttributeError, ): pass configuration = utils.get_api_client_configuration(token=token) self.api_client = LightlySwaggerApiClient(configuration=configuration) self.api_client.user_agent = f"Lightly/{__version__} ({platform.system()}/{platform.release()}; {platform.platform()}; {platform.processor()};) python/{platform.python_version()}" self.token = configuration.api_key["ApiKeyAuth"] if dataset_id is not None: self._dataset_id = dataset_id if embedding_id is not None: self.embedding_id = embedding_id self._creator = creator self._collaboration_api = CollaborationApi(api_client=self.api_client) self._compute_worker_api = DockerApi(api_client=self.api_client) self._datasets_api = DatasetsApi(api_client=self.api_client) self._datasources_api = DatasourcesApi(api_client=self.api_client) self._selection_api = SamplingsApi(api_client=self.api_client) self._jobs_api = JobsApi(api_client=self.api_client) self._tags_api = TagsApi(api_client=self.api_client) self._embeddings_api = EmbeddingsApi(api_client=self.api_client) self._mappings_api = MappingsApi(api_client=self.api_client) self._scores_api = ScoresApi(api_client=self.api_client) self._samples_api = SamplesApi(api_client=self.api_client) self._quota_api = QuotaApi(api_client=self.api_client) self._metadata_configurations_api = MetaDataConfigurationsApi( api_client=self.api_client ) self._predictions_api = PredictionsApi(api_client=self.api_client) @property def dataset_id(self) -> str: """The current dataset ID. Future requests with the client will automatically use this dataset ID. If the dataset ID is set, it is returned. Otherwise, the ID of the last modified dataset is selected. """ try: return self._dataset_id except AttributeError: all_datasets: List[DatasetData] = self.get_datasets() datasets_sorted = sorted( all_datasets, key=lambda dataset: dataset.last_modified_at ) last_modified_dataset = datasets_sorted[-1] self._dataset_id = last_modified_dataset.id warnings.warn( UserWarning( f"Dataset has not been specified, " f"taking the last modified dataset {last_modified_dataset.name} as default dataset." ) ) return self._dataset_id @dataset_id.setter def dataset_id(self, dataset_id: str) -> None: """Sets the current dataset ID for the client. Args: dataset_id: The new dataset id. Raises: ValueError if the dataset does not exist. """ if not self.dataset_exists(dataset_id): raise ValueError( f"A dataset with the id {dataset_id} does not exist on the web" f"platform." ) self._dataset_id = dataset_id def _order_list_by_filenames( self, filenames_for_list: List[str], list_to_order: List[object] ) -> List[object]: """Orders a list such that it is in the order of the filenames specified on the server. Args: filenames_for_list: The filenames of samples in a specific order list_to_order: Some values belonging to the samples Returns: The list reordered. The same reorder applied on the filenames_for_list would put them in the order of the filenames in self.filenames_on_server. every filename in self.filenames_on_server must be in the filenames_for_list. """ filenames_on_server = self.get_filenames() list_ordered = reordering.sort_items_by_keys( filenames_for_list, list_to_order, filenames_on_server ) return list_ordered def get_filenames(self) -> List[str]: """Downloads the list of filenames from the server. This is an expensive operation, especially for large datasets. Returns: Names of files in the current dataset. """ filenames_on_server = self._mappings_api.get_sample_mappings_by_dataset_id( dataset_id=self.dataset_id, field="fileName" ) return filenames_on_server def upload_file_with_signed_url( self, file: IOBase, signed_write_url: str, headers: Optional[Dict] = None, session: Optional[requests.Session] = None, ) -> Response: """Uploads a file to a url via a put request. Args: file: The file to upload. signed_write_url: The url to upload the file to. As no authorization is used, the url must be a signed write url. headers: Specific headers for the request. Defaults to None. session: Optional requests session used to upload the file. Returns: The response of the put request. """ # check to see if server side encryption for S3 is desired # see https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingServerSideEncryption.html # see https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html lightly_s3_sse_kms_key = os.environ.get(LIGHTLY_S3_SSE_KMS_KEY, "").strip() # Only set s3 related headers when we are talking with s3 if ( utils.get_signed_url_destination(signed_write_url) == DatasourceType.S3 and lightly_s3_sse_kms_key ): if headers is None: headers = {} # don't override previously set SSE if "x-amz-server-side-encryption" not in headers: if lightly_s3_sse_kms_key.lower() == "true": # enable SSE with the key of amazon headers["x-amz-server-side-encryption"] = "AES256" else: # enable SSE with specific customer KMS key headers["x-amz-server-side-encryption"] = "aws:kms" headers[ "x-amz-server-side-encryption-aws-kms-key-id" ] = lightly_s3_sse_kms_key # start requests session and make put request sess = session or requests if headers is not None: response = sess.put(signed_write_url, data=file, headers=headers) else: response = sess.put(signed_write_url, data=file) response.raise_for_status() return response
10,750
37.53405
187
py
lightly
lightly-master/lightly/api/api_workflow_collaboration.py
from typing import List from lightly.openapi_generated.swagger_client.models import ( SharedAccessConfigCreateRequest, SharedAccessConfigData, SharedAccessType, ) class _CollaborationMixin: def share_dataset_only_with(self, dataset_id: str, user_emails: List[str]) -> None: """Shares a dataset with a list of users. This method overwrites the list of users that have had access to the dataset before. If you want to add someone new to the list, make sure you first fetch the list of users with access and include them in the `user_emails` parameter. Args: dataset_id: ID of the dataset to be shared. user_emails: List of email addresses of users who will get access to the dataset. Examples: >>> # share a dataset with a user >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> client.share_dataset_only_with(dataset_id="MY_DATASET_ID", user_emails=["user@something.com"]) >>> >>> # share dataset with a user while keep sharing it with previous users >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> user_emails = client.get_shared_users(dataset_id="MY_DATASET_ID") >>> user_emails.append("additional_user2@something.com") >>> client.share_dataset_only_with(dataset_id="MY_DATASET_ID", user_emails=user_emails) >>> >>> # revoke access to all users >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> client.share_dataset_only_with(dataset_id="MY_DATASET_ID", user_emails=[]) """ body = SharedAccessConfigCreateRequest( access_type=SharedAccessType.WRITE, users=user_emails, creator=self._creator ) self._collaboration_api.create_or_update_shared_access_config_by_dataset_id( shared_access_config_create_request=body, dataset_id=dataset_id ) def get_shared_users(self, dataset_id: str) -> List[str]: """Fetches a list of users that have access to the dataset. Args: dataset_id: Dataset ID. Returns: List of email addresses of users that have write access to the dataset. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> client.get_shared_users(dataset_id="MY_DATASET_ID") >>> ["user@something.com"] """ access_configs: List[ SharedAccessConfigData ] = self._collaboration_api.get_shared_access_configs_by_dataset_id( dataset_id=dataset_id ) user_emails = [] # iterate through configs and find first WRITE config # we use the same hard rule in the frontend to communicate with the API # as we currently only support WRITE access for access_config in access_configs: if access_config.access_type == SharedAccessType.WRITE: user_emails.extend(access_config.users) break return user_emails
3,132
38.658228
108
py
lightly
lightly-master/lightly/api/api_workflow_compute_worker.py
import copy import dataclasses import difflib import json import time from functools import partial from typing import Any, Callable, Dict, Iterator, List, Optional, Type, TypeVar, Union from lightly.api import utils from lightly.openapi_generated.swagger_client.api_client import ApiClient from lightly.openapi_generated.swagger_client.models import ( CreateDockerWorkerRegistryEntryRequest, DockerRunData, DockerRunScheduledCreateRequest, DockerRunScheduledData, DockerRunScheduledPriority, DockerRunScheduledState, DockerRunState, DockerWorkerConfigV3, DockerWorkerConfigV3CreateRequest, DockerWorkerConfigV3Docker, DockerWorkerConfigV3Lightly, DockerWorkerRegistryEntryData, DockerWorkerType, SelectionConfig, SelectionConfigEntry, SelectionConfigEntryInput, SelectionConfigEntryStrategy, TagData, ) from lightly.openapi_generated.swagger_client.rest import ApiException STATE_SCHEDULED_ID_NOT_FOUND = "CANCELED_OR_NOT_EXISTING" class InvalidConfigurationError(RuntimeError): pass @dataclasses.dataclass class ComputeWorkerRunInfo: """Information about a Lightly Worker run. Attributes: state: The state of the Lightly Worker run. message: The last message of the Lightly Worker run. """ state: Union[ DockerRunState, DockerRunScheduledState.OPEN, STATE_SCHEDULED_ID_NOT_FOUND ] message: str def in_end_state(self) -> bool: """Checks whether the Lightly Worker run has ended.""" return self.state in [ DockerRunState.COMPLETED, DockerRunState.ABORTED, DockerRunState.FAILED, DockerRunState.CRASHED, STATE_SCHEDULED_ID_NOT_FOUND, ] def ended_successfully(self) -> bool: """Checkes whether the Lightly Worker run ended successfully or failed. Returns: A boolean value indicating if the Lightly Worker run was successful. True if the run was successful. Raises: ValueError: If the Lightly Worker run is still in progress. """ if not self.in_end_state(): raise ValueError("Lightly Worker run is still in progress.") return self.state == DockerRunState.COMPLETED class _ComputeWorkerMixin: def register_compute_worker( self, name: str = "Default", labels: Optional[List[str]] = None ) -> str: """Registers a new Lightly Worker. The ID of the registered worker will be returned. If a worker with the same name already exists, the ID of the existing worker is returned. Args: name: The name of the Lightly Worker. labels: The labels of the Lightly Worker. See our docs for more information regarding the labels parameter: https://docs.lightly.ai/docs/assign-scheduled-runs-to-specific-workers Returns: ID of the registered Lightly Worker. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> worker_id = client.register_compute_worker(name="my-worker", labels=["worker-label"]) >>> worker_id '64709eac61e9ce68180a6529' """ if labels is None: labels = [] request = CreateDockerWorkerRegistryEntryRequest( name=name, worker_type=DockerWorkerType.FULL, labels=labels, creator=self._creator, ) response = self._compute_worker_api.register_docker_worker(request) return response.id def get_compute_worker_ids(self) -> List[str]: """Fetches the IDs of all registered Lightly Workers. Returns: A list of worker IDs. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> worker_ids = client.get_compute_worker_ids() >>> worker_ids ['64709eac61e9ce68180a6529', '64709f8f61e9ce68180a652a'] """ entries = self._compute_worker_api.get_docker_worker_registry_entries() return [entry.id for entry in entries] def get_compute_workers(self) -> List[DockerWorkerRegistryEntryData]: """Fetches details of all registered Lightly Workers. Returns: A list of Lightly Worker details. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> workers = client.get_compute_workers() >>> workers [{'created_at': 1685102336056, 'docker_version': '2.6.0', 'id': '64709eac61e9ce68180a6529', 'labels': [], ... }] """ entries: list[ DockerWorkerRegistryEntryData ] = self._compute_worker_api.get_docker_worker_registry_entries() return entries def delete_compute_worker(self, worker_id: str) -> None: """Removes a Lightly Worker. Args: worker_id: ID of the worker to be removed. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> worker_ids = client.get_compute_worker_ids() >>> worker_ids ['64709eac61e9ce68180a6529'] >>> client.delete_compute_worker(worker_id="64709eac61e9ce68180a6529") >>> client.get_compute_worker_ids() [] """ self._compute_worker_api.delete_docker_worker_registry_entry_by_id(worker_id) def create_compute_worker_config( self, worker_config: Optional[Dict[str, Any]] = None, lightly_config: Optional[Dict[str, Any]] = None, selection_config: Optional[Union[Dict[str, Any], SelectionConfig]] = None, ) -> str: """Creates a new configuration for a Lightly Worker run. See our docs for more information regarding the different configurations: https://docs.lightly.ai/docs/all-configuration-options Args: worker_config: Lightly Worker configuration. lightly_config: Lightly configuration. selection_config: Selection configuration. Returns: The ID of the created config. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> selection_config = { ... "n_samples": 3, ... "strategies": [ ... { ... "input": {"type": "RANDOM", "random_seed": 42}, ... "strategy": {"type": "WEIGHTS"}, ... } ... ], ... } >>> config_id = client.create_compute_worker_config( ... selection_config=selection_config, ... ) """ if isinstance(selection_config, dict): selection = selection_config_from_dict(cfg=selection_config) else: selection = selection_config if worker_config is not None: worker_config_cc = _config_to_camel_case(cfg=worker_config) deserialize_worker_config = _get_deserialize( api_client=self.api_client, klass=DockerWorkerConfigV3Docker, ) docker = deserialize_worker_config(worker_config_cc) _validate_config(cfg=worker_config, obj=docker) else: docker = None if lightly_config is not None: lightly_config_cc = _config_to_camel_case(cfg=lightly_config) deserialize_lightly_config = _get_deserialize( api_client=self.api_client, klass=DockerWorkerConfigV3Lightly, ) lightly = deserialize_lightly_config(lightly_config_cc) _validate_config(cfg=lightly_config, obj=lightly) else: lightly = None config = DockerWorkerConfigV3( worker_type=DockerWorkerType.FULL, docker=docker, lightly=lightly, selection=selection, ) request = DockerWorkerConfigV3CreateRequest( config=config, creator=self._creator ) try: response = self._compute_worker_api.create_docker_worker_config_v3(request) return response.id except ApiException as e: if e.body is None: raise e eb = json.loads(e.body) eb_code = eb.get("code") eb_error = eb.get("error") if str(e.status)[0] == "4" and eb_code is not None and eb_error is not None: raise ValueError( f"Trying to schedule your job resulted in\n" f">> {eb_code}\n>> {json.dumps(eb_error, indent=4)}\n" f">> Please fix the issue mentioned above and see our docs " f"https://docs.lightly.ai/docs/all-configuration-options for more help." ) from e else: raise e def schedule_compute_worker_run( self, worker_config: Optional[Dict[str, Any]] = None, lightly_config: Optional[Dict[str, Any]] = None, selection_config: Optional[Union[Dict[str, Any], SelectionConfig]] = None, priority: str = DockerRunScheduledPriority.MID, runs_on: Optional[List[str]] = None, ) -> str: """Schedules a run with the given configurations. See our docs for more information regarding the different configurations: https://docs.lightly.ai/docs/all-configuration-options Args: worker_config: Lightly Worker configuration. lightly_config: Lightly configuration. selection_config: Selection configuration. runs_on: The required labels the Lightly Worker must have to take the job. See our docs for more information regarding the runs_on paramter: https://docs.lightly.ai/docs/assign-scheduled-runs-to-specific-workers Returns: The id of the scheduled run. Raises: ApiException: If the API call returns a status code other than 200. 400: Missing or invalid parameters 402: Insufficient plan 403: Not authorized for this resource or invalid token 404: Resource (dataset or config) not found 422: Missing or invalid file in datasource InvalidConfigError: If one of the configurations is invalid. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> selection_config = {...} >>> worker_labels = ["worker-label"] >>> run_id = client.schedule_compute_worker_run( ... selection_config=selection_config, runs_on=worker_labels ... ) """ if runs_on is None: runs_on = [] config_id = self.create_compute_worker_config( worker_config=worker_config, lightly_config=lightly_config, selection_config=selection_config, ) request = DockerRunScheduledCreateRequest( config_id=config_id, priority=priority, runs_on=runs_on, creator=self._creator, ) response = self._compute_worker_api.create_docker_run_scheduled_by_dataset_id( docker_run_scheduled_create_request=request, dataset_id=self.dataset_id, ) return response.id def get_compute_worker_runs_iter( self, dataset_id: Optional[str] = None, ) -> Iterator[DockerRunData]: """Returns an iterator over all Lightly Worker runs for the user. Args: dataset_id: Target dataset ID. Optional. If set, only runs with the given dataset will be returned. Returns: Runs iterator. """ if dataset_id is not None: return utils.paginate_endpoint( self._compute_worker_api.get_docker_runs_query_by_dataset_id, dataset_id=dataset_id, ) else: return utils.paginate_endpoint( self._compute_worker_api.get_docker_runs, ) def get_compute_worker_runs( self, dataset_id: Optional[str] = None, ) -> List[DockerRunData]: """Fetches all Lightly Worker runs for the user. Args: dataset_id: Target dataset ID. Optional. If set, only runs with the given dataset will be returned. Returns: Runs sorted by creation time from the oldest to the latest. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> client.get_compute_worker_runs() [{'artifacts': [...], 'config_id': '6470a16461e9ce68180a6530', 'created_at': 1679479418110, 'dataset_id': '6470a36361e9ce68180a6531', 'docker_version': '2.6.0', ... }] """ runs: List[DockerRunData] = list(self.get_compute_worker_runs_iter(dataset_id)) sorted_runs = sorted(runs, key=lambda run: run.created_at or -1) return sorted_runs def get_compute_worker_run(self, run_id: str) -> DockerRunData: """Fetches a Lightly Worker run. Args: run_id: Run ID. Returns: Details of the Lightly Worker run. Raises: ApiException: If no run with the given ID exists. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> client.get_compute_worker_run(run_id="6470a20461e9ce68180a6530") {'artifacts': [...], 'config_id': '6470a16461e9ce68180a6530', 'created_at': 1679479418110, 'dataset_id': '6470a36361e9ce68180a6531', 'docker_version': '2.6.0', ... } """ return self._compute_worker_api.get_docker_run_by_id(run_id=run_id) def get_compute_worker_run_from_scheduled_run( self, scheduled_run_id: str, ) -> DockerRunData: """Fetches a Lightly Worker run given its scheduled run ID. Args: scheduled_run_id: Scheduled run ID. Returns: Details of the Lightly Worker run. Raises: ApiException: If no run with the given scheduled run ID exists or if the scheduled run is not yet picked up by a worker. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> client.get_compute_worker_run_from_scheduled_run(scheduled_run_id="646f338a8a5613b57d8b73a1") {'artifacts': [...], 'config_id': '6470a16461e9ce68180a6530', 'created_at': 1679479418110, 'dataset_id': '6470a36361e9ce68180a6531', 'docker_version': '2.6.0', ... } """ return self._compute_worker_api.get_docker_run_by_scheduled_id( scheduled_id=scheduled_run_id ) def get_scheduled_compute_worker_runs( self, state: Optional[str] = None, ) -> List[DockerRunScheduledData]: """Returns a list of scheduled Lightly Worker runs with the current dataset. Args: state: DockerRunScheduledState value. If specified, then only runs in the given state are returned. If omitted, then runs which have not yet finished (neither 'DONE' nor 'CANCELED') are returned. Valid states are 'OPEN', 'LOCKED', 'DONE', and 'CANCELED'. Returns: A list of scheduled Lightly Worker runs. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> client.get_scheduled_compute_worker_runs(state="OPEN") [{'config_id': '646f34608a5613b57d8b73cc', 'created_at': 1685009508254, 'dataset_id': '6470a36361e9ce68180a6531', 'id': '646f338a8a5613b57d8b73a1', 'last_modified_at': 1685009542667, 'owner': '643d050b8bcb91967ded65df', 'priority': 'MID', 'runs_on': ['worker-label'], 'state': 'OPEN'}] """ if state is not None: return self._compute_worker_api.get_docker_runs_scheduled_by_dataset_id( dataset_id=self.dataset_id, state=state, ) return self._compute_worker_api.get_docker_runs_scheduled_by_dataset_id( dataset_id=self.dataset_id, ) def _get_scheduled_run_by_id(self, scheduled_run_id: str) -> DockerRunScheduledData: """Returns the schedule run data given the id of the scheduled run. TODO (MALTE, 09/2022): Have a proper API endpoint for doing this. Args: scheduled_run_id: The ID with which the run was scheduled. Returns: Defails of the scheduled run. """ try: run: DockerRunScheduledData = next( run for run in utils.retry( lambda: self._compute_worker_api.get_docker_runs_scheduled_by_dataset_id( self.dataset_id ) ) if run.id == scheduled_run_id ) return run except StopIteration: raise ApiException( f"No scheduled run found for run with scheduled_run_id='{scheduled_run_id}'." ) def get_compute_worker_run_info( self, scheduled_run_id: str ) -> ComputeWorkerRunInfo: """Returns information about the Lightly Worker run. Args: scheduled_run_id: ID of the scheduled run. Returns: Details of the Lightly Worker run. Examples: >>> # Scheduled a Lightly Worker run and get its state >>> scheduled_run_id = client.schedule_compute_worker_run(...) >>> run_info = client.get_compute_worker_run_info(scheduled_run_id) >>> print(run_info) """ """ Because we currently (09/2022) have different Database entries for a ScheduledRun and DockerRun, the logic is more complicated and covers three cases. """ try: # Case 1: DockerRun exists. docker_run: DockerRunData = ( self._compute_worker_api.get_docker_run_by_scheduled_id( scheduled_id=scheduled_run_id ) ) info = ComputeWorkerRunInfo( state=docker_run.state, message=docker_run.message ) except ApiException: try: # Case 2: DockerRun does NOT exist, but ScheduledRun exists. _ = self._get_scheduled_run_by_id(scheduled_run_id) info = ComputeWorkerRunInfo( state=DockerRunScheduledState.OPEN, message="Waiting for pickup by Lightly Worker. " "Make sure to start a Lightly Worker connected to your " "user token to process the job.", ) except ApiException: # Case 3: NEITHER the DockerRun NOR the ScheduledRun exist. info = ComputeWorkerRunInfo( state=STATE_SCHEDULED_ID_NOT_FOUND, message=f"Could not find a job for the given run_id: '{scheduled_run_id}'. " "The scheduled run does not exist or was canceled before " "being picked up by a Lightly Worker.", ) return info def compute_worker_run_info_generator( self, scheduled_run_id: str ) -> Iterator[ComputeWorkerRunInfo]: """Pulls information about a Lightly Worker run continuously. Polls the Lightly Worker status every 30s. If the status changed, an update pops up. If the Lightly Worker run finished, the generator stops. Args: scheduled_run_id: The id with which the run was scheduled. Returns: Generator of information about the Lightly Worker run status. Examples: >>> # Scheduled a Lightly Worker run and monitor its state >>> scheduled_run_id = client.schedule_compute_worker_run(...) >>> for run_info in client.compute_worker_run_info_generator(scheduled_run_id): >>> print(f"Lightly Worker run is now in state='{run_info.state}' with message='{run_info.message}'") >>> """ last_run_info = None while True: run_info = self.get_compute_worker_run_info( scheduled_run_id=scheduled_run_id ) # Only yield new run_info if run_info != last_run_info: yield run_info # Break if the scheduled run is in one of the end states. if run_info.in_end_state(): break # Wait before polling the state again time.sleep(30) # Keep this at 30s or larger to prevent rate limiting. last_run_info = run_info def get_compute_worker_run_tags(self, run_id: str) -> List[TagData]: """Returns all tags from a run with the current dataset. Only returns tags for runs made with Lightly Worker version >=2.4.2. Args: run_id: Run ID from which to return tags. Returns: List of tags created by the run. The tags are ordered by creation date from newest to oldest. Examples: >>> # Get filenames from last run. >>> >>> from lightly.api import ApiWorkflowClient >>> client = ApiWorkflowClient( >>> token="MY_LIGHTLY_TOKEN", dataset_id="MY_DATASET_ID" >>> ) >>> tags = client.get_compute_worker_run_tags(run_id="MY_LAST_RUN_ID") >>> filenames = client.export_filenames_by_tag_name(tag_name=tags[0].name) """ tags = self._compute_worker_api.get_docker_run_tags(run_id=run_id) tags_in_dataset = [tag for tag in tags if tag.dataset_id == self.dataset_id] return tags_in_dataset def selection_config_from_dict(cfg: Dict[str, Any]) -> SelectionConfig: """Recursively converts selection config from dict to a SelectionConfig instance.""" strategies = [] for entry in cfg.get("strategies", []): new_entry = copy.deepcopy(entry) new_entry["input"] = SelectionConfigEntryInput(**entry["input"]) new_entry["strategy"] = SelectionConfigEntryStrategy(**entry["strategy"]) strategies.append(SelectionConfigEntry(**new_entry)) new_cfg = copy.deepcopy(cfg) new_cfg["strategies"] = strategies return SelectionConfig(**new_cfg) _T = TypeVar("_T") def _get_deserialize( api_client: ApiClient, klass: Type[_T], ) -> Callable[[Dict[str, Any]], _T]: """Returns the deserializer of the ApiClient class for class klass. TODO(Philipp, 02/23): We should replace this by our own deserializer which accepts snake case strings as input. The deserializer takes a dictionary and and returns an instance of klass. """ deserialize = getattr(api_client, "_ApiClient__deserialize") return partial(deserialize, klass=klass) def _config_to_camel_case(cfg: Dict[str, Any]) -> Dict[str, Any]: """Converts all keys in the cfg dictionary to camelCase.""" cfg_camel_case = {} for key, value in cfg.items(): key_camel_case = _snake_to_camel_case(key) if isinstance(value, dict): cfg_camel_case[key_camel_case] = _config_to_camel_case(value) else: cfg_camel_case[key_camel_case] = value return cfg_camel_case def _snake_to_camel_case(snake: str) -> str: """Converts the snake_case input to camelCase.""" components = snake.split("_") return components[0] + "".join(component.title() for component in components[1:]) def _validate_config( cfg: Optional[Dict[str, Any]], obj: Any, ) -> None: """Validates that all keys in cfg are legitimate configuration options. Recursively checks if the keys in the cfg dictionary match the attributes of the DockerWorkerConfigV2Docker/DockerWorkerConfigV2Lightly instances. If not, suggests a best match. Raises: InvalidConfigurationError: If obj is not a valid config. """ if cfg is None: return for key, item in cfg.items(): if not hasattr(obj, key): possible_options = list(obj.__fields__.keys()) closest_match = difflib.get_close_matches( word=key, possibilities=possible_options, n=1, cutoff=0.0 )[0] error_msg = ( f"Option '{key}' does not exist! Did you mean '{closest_match}'?" ) raise InvalidConfigurationError(error_msg) if isinstance(item, dict): _validate_config(item, getattr(obj, key))
25,577
34.773427
117
py
lightly
lightly-master/lightly/api/api_workflow_datasets.py
import warnings from itertools import chain from typing import Iterator, List, Optional, Set from lightly.api import utils from lightly.openapi_generated.swagger_client.models import ( CreateEntityResponse, DatasetCreateRequest, DatasetData, DatasetType, ) from lightly.openapi_generated.swagger_client.rest import ApiException class _DatasetsMixin: @property def dataset_type(self) -> str: """Returns the dataset type of the current dataset.""" dataset = self._get_current_dataset() return dataset.type #  type: ignore def _get_current_dataset(self) -> DatasetData: """Returns the dataset with id == self.dataset_id.""" return self.get_dataset_by_id(dataset_id=self.dataset_id) def dataset_exists(self, dataset_id: str) -> bool: """Checks if a dataset exists. Args: dataset_id: Dataset ID. Returns: True if the dataset exists and False otherwise. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> client.create_dataset("your-dataset-name", dataset_type=DatasetType.IMAGES) >>> dataset_id = client.dataset_id >>> client.dataset_exists(dataset_id=dataset_id) True """ try: self.get_dataset_by_id(dataset_id) return True except ApiException as exception: if exception.status == 404: # Not Found return False raise exception def dataset_name_exists( self, dataset_name: str, shared: Optional[bool] = False ) -> bool: """Checks if a dataset with the given name exists. There can be multiple datasets with the same name accessible to the current user. This can happen if either: * A dataset has been explicitly shared with the user * The user has access to team datasets The `shared` flag controls whether these datasets are checked. Args: dataset_name: Name of the dataset. shared: * If False (default), checks only datasets owned by the user. * If True, checks datasets which have been shared with the user, including team datasets. Excludes user's own datasets. * If None, checks all datasets the users has access to. Returns: A boolean value indicating whether any dataset with the given name exists. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> client.create_dataset("your-dataset-name", dataset_type=DatasetType.IMAGES) >>> client.dataset_name_exists(dataset_name="your-dataset-name") True """ return bool(self.get_datasets_by_name(dataset_name=dataset_name, shared=shared)) def get_dataset_by_id(self, dataset_id: str) -> DatasetData: """Fetches a dataset by ID. Args: dataset_id: Dataset ID. Returns: The dataset with the given dataset id. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> client.create_dataset("your-dataset-name", dataset_type=DatasetType.IMAGES) >>> dataset_id = client.dataset_id >>> client.get_dataset_by_id(dataset_id=dataset_id) {'created_at': 1685009504596, 'datasource_processed_until_timestamp': 1685009513, 'datasources': ['646f346004d77b4e1424e67e', '646f346004d77b4e1424e695'], 'id': '646f34608a5613b57d8b73c9', 'img_type': 'full', 'type': 'Images', ...} """ dataset: DatasetData = self._datasets_api.get_dataset_by_id(dataset_id) return dataset def get_datasets_by_name( self, dataset_name: str, shared: Optional[bool] = False, ) -> List[DatasetData]: """Fetches datasets by name. There can be multiple datasets with the same name accessible to the current user. This can happen if either: * A dataset has been explicitly shared with the user * The user has access to team datasets The `shared` flag controls whether these datasets are returned. Args: dataset_name: Name of the target dataset. shared: * If False (default), returns only datasets owned by the user. In this case at most one dataset will be returned. * If True, returns datasets which have been shared with the user, including team datasets. Excludes user's own datasets. Can return multiple datasets. * If None, returns all datasets the users has access to. Can return multiple datasets. Returns: A list of datasets that match the name. If no datasets with the name exist, an empty list is returned. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> client.create_dataset("your-dataset-name", dataset_type=DatasetType.IMAGES) >>> client.get_datasets_by_name(dataset_name="your-dataset-name") [{'created_at': 1685009504596, 'datasource_processed_until_timestamp': 1685009513, 'datasources': ['646f346004d77b4e1424e67e', '646f346004d77b4e1424e695'], 'id': '646f34608a5613b57d8b73c9', 'img_type': 'full', 'type': 'Images', ...}] >>> >>> # Non-existent dataset >>> client.get_datasets_by_name(dataset_name="random-name") [] """ datasets: List[DatasetData] = [] if not shared or shared is None: datasets.extend( list( utils.paginate_endpoint( self._datasets_api.get_datasets_query_by_name, dataset_name=dataset_name, exact=True, shared=False, ) ) ) if shared or shared is None: datasets.extend( list( utils.paginate_endpoint( self._datasets_api.get_datasets_query_by_name, dataset_name=dataset_name, exact=True, shared=True, ) ) ) datasets.extend( list( utils.paginate_endpoint( self._datasets_api.get_datasets_query_by_name, dataset_name=dataset_name, exact=True, get_assets_of_team=True, ) ) ) # De-duplicate datasets because results from shared=True and # those from get_assets_of_team=True might overlap dataset_ids: Set[str] = set() filtered_datasets: List[DatasetData] = [] for dataset in datasets: if dataset.id not in dataset_ids: dataset_ids.add(dataset.id) filtered_datasets.append(dataset) return filtered_datasets def get_datasets_iter( self, shared: Optional[bool] = False ) -> Iterator[DatasetData]: """Returns an iterator over all datasets owned by the current user. There can be multiple datasets with the same name accessible to the current user. This can happen if either: * A dataset has been explicitly shared with the user * The user has access to team datasets The `shared` flag controls whether these datasets are returned. Args: shared: * If False (default), returns only datasets owned by the user. In this case at most one dataset will be returned. * If True, returns datasets which have been shared with the user, including team datasets. Excludes user's own datasets. Can return multiple datasets. * If None, returns all datasets the users has access to. Can return multiple datasets. Returns: An iterator over datasets owned by the current user. """ dataset_iterable: Iterator[DatasetData] = (_ for _ in ()) if not shared or shared is None: dataset_iterable = utils.paginate_endpoint( self._datasets_api.get_datasets, shared=False, ) if shared or shared is None: dataset_iterable = chain( dataset_iterable, utils.paginate_endpoint( self._datasets_api.get_datasets, shared=True, ), ) dataset_iterable = chain( dataset_iterable, utils.paginate_endpoint( self._datasets_api.get_datasets, get_assets_of_team=True, ), ) # De-duplicate datasets because results from shared=True and # those from get_assets_of_team=True might overlap dataset_ids: Set[str] = set() for dataset in dataset_iterable: if dataset.id not in dataset_ids: dataset_ids.add(dataset.id) yield dataset def get_datasets(self, shared: Optional[bool] = False) -> List[DatasetData]: """Returns all datasets owned by the current user. There can be multiple datasets with the same name accessible to the current user. This can happen if either: * A dataset has been explicitly shared with the user * The user has access to team datasets The `shared` flag controls whether these datasets are returned. Args: shared: * If False (default), returns only datasets owned by the user. In this case at most one dataset will be returned. * If True, returns datasets which have been shared with the user, including team datasets. Excludes user's own datasets. Can return multiple datasets. * If None, returns all datasets the users has access to. Can return multiple datasets. Returns: A list of datasets owned by the current user. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> client.create_dataset("your-dataset-name", dataset_type=DatasetType.IMAGES) >>> client.get_datasets() [{'created_at': 1685009504596, 'datasource_processed_until_timestamp': 1685009513, 'datasources': ['646f346004d77b4e1424e67e', '646f346004d77b4e1424e695'], 'id': '646f34608a5613b57d8b73c9', 'img_type': 'full', 'type': 'Images', ...}] """ return list(self.get_datasets_iter(shared)) def get_all_datasets(self) -> List[DatasetData]: """Returns all datasets the user has access to. DEPRECATED in favour of get_datasets(shared=None) and will be removed in the future. """ warnings.warn( "get_all_datasets() is deprecated in favour of get_datasets(shared=None) " "and will be removed in the future.", DeprecationWarning, ) owned_datasets = self.get_datasets(shared=None) return owned_datasets def set_dataset_id_by_name( self, dataset_name: str, shared: Optional[bool] = False ) -> None: """Sets the dataset ID in the API client given the name of the desired dataset. There can be multiple datasets with the same name accessible to the current user. This can happen if either: * A dataset has been explicitly shared with the user * The user has access to team datasets The `shared` flag controls whether these datasets are also checked. If multiple datasets with the given name are found, the API client uses the ID of the first dataset and prints a warning message. Args: dataset_name: The name of the target dataset. shared: * If False (default), checks only datasets owned by the user. * If True, returns datasets which have been shared with the user, including team datasets. Excludes user's own datasets. There can be multiple candidate datasets. * If None, returns all datasets the users has access to. There can be multiple candidate datasets. Raises: ValueError: If no dataset with the given name exists. Examples: >>> # A new session. Dataset "old-dataset" was created before. >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> client.set_dataset_id_by_name("old-dataset") """ datasets = self.get_datasets_by_name(dataset_name=dataset_name, shared=shared) if not datasets: raise ValueError( f"A dataset with the name '{dataset_name}' does not exist on the " f"Lightly Platform. Please create it first." ) self._dataset_id = datasets[0].id if len(datasets) > 1: msg = ( f"Found {len(datasets)} datasets with the name '{dataset_name}'. Their " f"ids are {[dataset.id for dataset in datasets]}. " f"The dataset_id of the client was set to '{self._dataset_id}'. " ) if shared or shared is None: msg += ( f"We noticed that you set shared={shared} which also retrieves " f"datasets shared with you. Set shared=False to only consider " "datasets you own." ) warnings.warn(msg) def create_dataset( self, dataset_name: str, dataset_type: str = DatasetType.IMAGES, ) -> None: """Creates a dataset on the Lightly Platform. The dataset_id of the created dataset is stored in the client.dataset_id attribute and all further requests with the client will use the created dataset by default. Args: dataset_name: The name of the dataset to be created. dataset_type: The type of the dataset. We recommend to use the API provided constants `DatasetType.IMAGES` and `DatasetType.VIDEOS`. Raises: ValueError: If a dataset with dataset_name already exists. Examples: >>> from lightly.api import ApiWorkflowClient >>> from lightly.openapi_generated.swagger_client.models import DatasetType >>> >>> client = lightly.api.ApiWorkflowClient(token="YOUR_TOKEN") >>> client.create_dataset('your-dataset-name', dataset_type=DatasetType.IMAGES) >>> >>> # or to work with videos >>> client.create_dataset('your-dataset-name', dataset_type=DatasetType.VIDEOS) >>> >>> # retrieving dataset_id of the created dataset >>> dataset_id = client.dataset_id >>> >>> # future client requests use the created dataset by default >>> client.dataset_type 'Videos' """ if self.dataset_name_exists(dataset_name=dataset_name): raise ValueError( f"A dataset with the name '{dataset_name}' already exists! Please use " f"the `set_dataset_id_by_name()` method instead if you intend to reuse " f"an existing dataset." ) self._create_dataset_without_check_existing( dataset_name=dataset_name, dataset_type=dataset_type, ) def _create_dataset_without_check_existing( self, dataset_name: str, dataset_type: str ) -> None: """Creates a dataset on the Lightly Platform. No checking if a dataset with such a name already exists is performed. Args: dataset_name: The name of the dataset to be created. dataset_type: The type of the dataset. We recommend to use the API provided constants `DatasetType.IMAGES` and `DatasetType.VIDEOS`. """ body = DatasetCreateRequest( name=dataset_name, type=dataset_type, creator=self._creator ) response: CreateEntityResponse = self._datasets_api.create_dataset( dataset_create_request=body ) self._dataset_id = response.id def create_new_dataset_with_unique_name( self, dataset_basename: str, dataset_type: str = DatasetType.IMAGES, ) -> None: """Creates a new dataset on the Lightly Platform. If a dataset with the specified name already exists, the name is suffixed by a counter value. Args: dataset_basename: The name of the dataset to be created. dataset_type: The type of the dataset. We recommend to use the API provided constants `DatasetType.IMAGES` and `DatasetType.VIDEOS`. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Create a dataset with a brand new name. >>> client.create_new_dataset_with_unique_name("new-dataset") >>> client.get_dataset_by_id(client.dataset_id) {'id': '6470abef4f0eb7e635c30954', 'name': 'new-dataset', ...} >>> >>> # Create another dataset with the same name. This time, the >>> # new dataset should have a suffix `_1`. >>> client.create_new_dataset_with_unique_name("new-dataset") >>> client.get_dataset_by_id(client.dataset_id) {'id': '6470ac194f0eb7e635c30990', 'name': 'new-dataset_1', ...} """ if not self.dataset_name_exists(dataset_name=dataset_basename): self._create_dataset_without_check_existing( dataset_name=dataset_basename, dataset_type=dataset_type, ) else: existing_datasets = list( utils.paginate_endpoint( self._datasets_api.get_datasets_query_by_name, dataset_name=dataset_basename, exact=False, shared=False, ) ) existing_dataset_names = {dataset.name for dataset in existing_datasets} counter = 1 dataset_name = f"{dataset_basename}_{counter}" while dataset_name in existing_dataset_names: counter += 1 dataset_name = f"{dataset_basename}_{counter}" self._create_dataset_without_check_existing( dataset_name=dataset_name, dataset_type=dataset_type, ) def delete_dataset_by_id(self, dataset_id: str) -> None: """Deletes a dataset on the Lightly Platform. Args: dataset_id: The ID of the dataset to be deleted. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> client.create_dataset("your-dataset-name", dataset_type=DatasetType.IMAGES) >>> dataset_id = client.dataset_id >>> client.dataset_exists(dataset_id=dataset_id) True >>> >>> # Delete the dataset >>> client.delete_dataset_by_id(dataset_id=dataset_id) >>> client.dataset_exists(dataset_id=dataset_id) False """ self._datasets_api.delete_dataset_by_id(dataset_id=dataset_id) del self._dataset_id
20,205
38.697446
91
py
lightly
lightly-master/lightly/api/api_workflow_datasources.py
import time import warnings from typing import Dict, List, Optional, Tuple, Union import tqdm from lightly.openapi_generated.swagger_client.models import ( DatasourceConfig, DatasourceConfigVerifyDataErrors, DatasourceProcessedUntilTimestampRequest, DatasourceProcessedUntilTimestampResponse, DatasourcePurpose, DatasourceRawSamplesData, ) class _DatasourcesMixin: def _download_raw_files( self, download_function: Union[ "DatasourcesApi.get_list_of_raw_samples_from_datasource_by_dataset_id", "DatasourcesApi.get_list_of_raw_samples_predictions_from_datasource_by_dataset_id", "DatasourcesApi.get_list_of_raw_samples_metadata_from_datasource_by_dataset_id", ], from_: int = 0, to: Optional[int] = None, relevant_filenames_file_name: Optional[str] = None, use_redirected_read_url: bool = False, progress_bar: Optional[tqdm.tqdm] = None, **kwargs, ) -> List[Tuple[str, str]]: if to is None: to = int(time.time()) relevant_filenames_kwargs = ( {"relevant_filenames_file_name": relevant_filenames_file_name} if relevant_filenames_file_name else dict() ) response: DatasourceRawSamplesData = download_function( dataset_id=self.dataset_id, var_from=from_, to=to, use_redirected_read_url=use_redirected_read_url, **relevant_filenames_kwargs, **kwargs, ) cursor = response.cursor samples = response.data if progress_bar is not None: progress_bar.update(len(response.data)) while response.has_more: response: DatasourceRawSamplesData = download_function( dataset_id=self.dataset_id, cursor=cursor, use_redirected_read_url=use_redirected_read_url, **relevant_filenames_kwargs, **kwargs, ) cursor = response.cursor samples.extend(response.data) if progress_bar is not None: progress_bar.update(len(response.data)) sample_map = {} for idx, s in enumerate(samples): if s.file_name.startswith("/"): warnings.warn( UserWarning( f"Absolute file paths like {s.file_name} are not supported" f" in relevant filenames file {relevant_filenames_file_name} due to blob storage" ) ) elif s.file_name.startswith(("./", "../")): warnings.warn( UserWarning( f"Using dot notation ('./', '../') like in {s.file_name} is not supported" f" in relevant filenames file {relevant_filenames_file_name} due to blob storage" ) ) elif s.file_name in sample_map: warnings.warn( UserWarning( f"Duplicate filename {s.file_name} in relevant" f" filenames file {relevant_filenames_file_name}" ) ) else: sample_map[s.file_name] = s.read_url return [(file_name, read_url) for file_name, read_url in sample_map.items()] def download_raw_samples( self, from_: int = 0, to: Optional[int] = None, relevant_filenames_file_name: Optional[str] = None, use_redirected_read_url: bool = False, progress_bar: Optional[tqdm.tqdm] = None, ) -> List[Tuple[str, str]]: """Downloads filenames and read urls from the datasource. Only samples with timestamp between `from_` (inclusive) and `to` (inclusive) will be downloaded. Args: from_: Unix timestamp from which on samples are downloaded. Defaults to the very beginning (timestamp 0). to: Unix timestamp up to and including which samples are downloaded. Defaults to the current timestamp. relevant_filenames_file_name: Path to the relevant filenames text file in the cloud bucket. The path is relative to the datasource root. Optional. use_redirected_read_url: Flag for redirected read urls. When this flag is true, RedirectedReadUrls are returned instead of ReadUrls, meaning that the returned URLs have unlimited access to the file. Defaults to False. When S3DelegatedAccess is configured, this flag has no effect because RedirectedReadUrls are always returned. progress_bar: Tqdm progress bar to show how many samples have already been retrieved. Returns: A list of (filename, url) tuples where each tuple represents a sample. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> client.download_raw_samples() [('image-1.png', 'https://......'), ('image-2.png', 'https://......')] """ samples = self._download_raw_files( download_function=self._datasources_api.get_list_of_raw_samples_from_datasource_by_dataset_id, from_=from_, to=to, relevant_filenames_file_name=relevant_filenames_file_name, use_redirected_read_url=use_redirected_read_url, progress_bar=progress_bar, ) return samples def download_raw_predictions( self, task_name: str, from_: int = 0, to: Optional[int] = None, relevant_filenames_file_name: Optional[str] = None, run_id: Optional[str] = None, relevant_filenames_artifact_id: Optional[str] = None, use_redirected_read_url: bool = False, progress_bar: Optional[tqdm.tqdm] = None, ) -> List[Tuple[str, str]]: """Downloads prediction filenames and read urls from the datasource. Only samples with timestamp between `from_` (inclusive) and `to` (inclusive) will be downloaded. Args: task_name: Name of the prediction task. from_: Unix timestamp from which on samples are downloaded. Defaults to the very beginning (timestamp 0). to: Unix timestamp up to and including which samples are downloaded. Defaults to the current timestamp. relevant_filenames_file_name: Path to the relevant filenames text file in the cloud bucket. The path is relative to the datasource root. Optional. run_id: Run ID. Optional. Should be given along with `relevant_filenames_artifact_id` to download relevant files only. relevant_filenames_artifact_id: ID of the relevant filename artifact. Optional. Should be given along with `run_id` to download relevant files only. Note that this is different from `relevant_filenames_file_name`. use_redirected_read_url: Flag for redirected read urls. When this flag is true, RedirectedReadUrls are returned instead of ReadUrls, meaning that the returned URLs have unlimited access to the file. Defaults to False. When S3DelegatedAccess is configured, this flag has no effect because RedirectedReadUrls are always returned. progress_bar: Tqdm progress bar to show how many prediction files have already been retrieved. Returns: A list of (filename, url) tuples where each tuple represents a sample. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> task_name = "object-detection" >>> client.set_dataset_id_by_name("my-dataset") >>> client.download_raw_predictions(task_name=task_name) [('.lightly/predictions/object-detection/image-1.json', 'https://......'), ('.lightly/predictions/object-detection/image-2.json', 'https://......')] """ if run_id is not None and relevant_filenames_artifact_id is None: raise ValueError( "'relevant_filenames_artifact_id' should not be `None` when 'run_id' " "is specified." ) if run_id is None and relevant_filenames_artifact_id is not None: raise ValueError( "'run_id' should not be `None` when 'relevant_filenames_artifact_id' " "is specified." ) relevant_filenames_kwargs = {} if run_id is not None and relevant_filenames_artifact_id is not None: relevant_filenames_kwargs["relevant_filenames_run_id"] = run_id relevant_filenames_kwargs[ "relevant_filenames_artifact_id" ] = relevant_filenames_artifact_id samples = self._download_raw_files( download_function=self._datasources_api.get_list_of_raw_samples_predictions_from_datasource_by_dataset_id, from_=from_, to=to, relevant_filenames_file_name=relevant_filenames_file_name, use_redirected_read_url=use_redirected_read_url, task_name=task_name, progress_bar=progress_bar, **relevant_filenames_kwargs, ) return samples def download_raw_metadata( self, from_: int = 0, to: Optional[int] = None, run_id: Optional[str] = None, relevant_filenames_artifact_id: Optional[str] = None, relevant_filenames_file_name: Optional[str] = None, use_redirected_read_url: bool = False, progress_bar: Optional[tqdm.tqdm] = None, ) -> List[Tuple[str, str]]: """Downloads all metadata filenames and read urls from the datasource. Only samples with timestamp between `from_` (inclusive) and `to` (inclusive) will be downloaded. Args: from_: Unix timestamp from which on samples are downloaded. Defaults to the very beginning (timestamp 0). to: Unix timestamp up to and including which samples are downloaded. Defaults to the current timestamp. relevant_filenames_file_name: Path to the relevant filenames text file in the cloud bucket. The path is relative to the datasource root. Optional. run_id: Run ID. Optional. Should be given along with `relevant_filenames_artifact_id` to download relevant files only. relevant_filenames_artifact_id: ID of the relevant filename artifact. Optional. Should be given along with `run_id` to download relevant files only. Note that this is different from `relevant_filenames_file_name`. use_redirected_read_url: Flag for redirected read urls. When this flag is true, RedirectedReadUrls are returned instead of ReadUrls, meaning that the returned URLs have unlimited access to the file. Defaults to False. When S3DelegatedAccess is configured, this flag has no effect because RedirectedReadUrls are always returned. progress_bar: Tqdm progress bar to show how many metadata files have already been retrieved. Returns: A list of (filename, url) tuples where each tuple represents a sample. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> client.download_raw_metadata() [('.lightly/metadata/object-detection/image-1.json', 'https://......'), ('.lightly/metadata/object-detection/image-2.json', 'https://......')] """ if run_id is not None and relevant_filenames_artifact_id is None: raise ValueError( "'relevant_filenames_artifact_id' should not be `None` when 'run_id' " "is specified." ) if run_id is None and relevant_filenames_artifact_id is not None: raise ValueError( "'run_id' should not be `None` when 'relevant_filenames_artifact_id' " "is specified." ) relevant_filenames_kwargs = {} if run_id is not None and relevant_filenames_artifact_id is not None: relevant_filenames_kwargs["relevant_filenames_run_id"] = run_id relevant_filenames_kwargs[ "relevant_filenames_artifact_id" ] = relevant_filenames_artifact_id samples = self._download_raw_files( self._datasources_api.get_list_of_raw_samples_metadata_from_datasource_by_dataset_id, from_=from_, to=to, relevant_filenames_file_name=relevant_filenames_file_name, use_redirected_read_url=use_redirected_read_url, progress_bar=progress_bar, **relevant_filenames_kwargs, ) return samples def download_new_raw_samples( self, use_redirected_read_url: bool = False, ) -> List[Tuple[str, str]]: """Downloads filenames and read urls of unprocessed samples from the datasource. All samples after the timestamp of `ApiWorkflowClient.get_processed_until_timestamp()` are fetched. After downloading the samples, the timestamp is updated to the current time. This function can be repeatedly called to retrieve new samples from the datasource. Args: use_redirected_read_url: Flag for redirected read urls. When this flag is true, RedirectedReadUrls are returned instead of ReadUrls, meaning that the returned URLs have unlimited access to the file. Defaults to False. When S3DelegatedAccess is configured, this flag has no effect because RedirectedReadUrls are always returned. Returns: A list of (filename, url) tuples where each tuple represents a sample. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> client.download_new_raw_samples() [('image-3.png', 'https://......'), ('image-4.png', 'https://......')] """ from_ = self.get_processed_until_timestamp() if from_ != 0: # We already processed samples at some point. # Add 1 because the samples with timestamp == from_ # have already been processed from_ += 1 to = int(time.time()) data = self.download_raw_samples( from_=from_, to=to, relevant_filenames_file_name=None, use_redirected_read_url=use_redirected_read_url, ) self.update_processed_until_timestamp(timestamp=to) return data def get_processed_until_timestamp(self) -> int: """Returns the timestamp until which samples have been processed. Returns: Unix timestamp of last processed sample. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> client.get_processed_until_timestamp() 1684750513 """ response: DatasourceProcessedUntilTimestampResponse = self._datasources_api.get_datasource_processed_until_timestamp_by_dataset_id( dataset_id=self.dataset_id ) timestamp = int(response.processed_until_timestamp) return timestamp def update_processed_until_timestamp(self, timestamp: int) -> None: """Sets the timestamp until which samples have been processed. Args: timestamp: Unix timestamp of last processed sample. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset. >>> # All samples are processed at this moment. >>> client.set_dataset_id_by_name("my-dataset") >>> client.download_new_raw_samples() [] >>> >>> # Set timestamp to an earlier moment to reprocess samples >>> client.update_processed_until_timestamp(1684749813) >>> client.download_new_raw_samples() [('image-3.png', 'https://......'), ('image-4.png', 'https://......')] """ body = DatasourceProcessedUntilTimestampRequest( processed_until_timestamp=timestamp ) self._datasources_api.update_datasource_processed_until_timestamp_by_dataset_id( dataset_id=self.dataset_id, datasource_processed_until_timestamp_request=body, ) def get_datasource(self) -> DatasourceConfig: """Returns the datasource of the current dataset. Returns: Datasource data of the datasource of the current dataset. Raises: ApiException if no datasource was configured. """ return self._datasources_api.get_datasource_by_dataset_id(self.dataset_id) def set_azure_config( self, container_name: str, account_name: str, sas_token: str, thumbnail_suffix: Optional[ str ] = ".lightly/thumbnails/[filename]_thumb.[extension]", purpose: str = DatasourcePurpose.INPUT_OUTPUT, ) -> None: """Sets the Azure configuration for the datasource of the current dataset. See our docs for a detailed explanation on how to setup Lightly with Azure: https://docs.lightly.ai/docs/azure Args: container_name: Container name of the dataset, for example: "my-container/path/to/my/data". account_name: Azure account name. sas_token: Secure Access Signature token. thumbnail_suffix: Where to save thumbnails of the images in the dataset, for example ".lightly/thumbnails/[filename]_thumb.[extension]". Set to None to disable thumbnails and use the full images from the datasource instead. purpose: Datasource purpose, determines if datasource is read only (INPUT) or can be written to as well (LIGHTLY, INPUT_OUTPUT). The latter is required when Lightly extracts frames from input videos. """ # TODO: Use DatasourceConfigAzure once we switch/update the api generator. self._datasources_api.update_datasource_by_dataset_id( datasource_config=DatasourceConfig.from_dict( { "type": "AZURE", "fullPath": container_name, "thumbSuffix": thumbnail_suffix, "accountName": account_name, "accountKey": sas_token, "purpose": purpose, } ), dataset_id=self.dataset_id, ) def set_gcs_config( self, resource_path: str, project_id: str, credentials: str, thumbnail_suffix: Optional[ str ] = ".lightly/thumbnails/[filename]_thumb.[extension]", purpose: str = DatasourcePurpose.INPUT_OUTPUT, ) -> None: """Sets the Google Cloud Storage configuration for the datasource of the current dataset. See our docs for a detailed explanation on how to setup Lightly with Google Cloud Storage: https://docs.lightly.ai/docs/google-cloud-storage Args: resource_path: GCS url of your dataset, for example: "gs://my_bucket/path/to/my/data" project_id: GCS project id. credentials: Content of the credentials JSON file stringified which you download from Google Cloud Platform. thumbnail_suffix: Where to save thumbnails of the images in the dataset, for example ".lightly/thumbnails/[filename]_thumb.[extension]". Set to None to disable thumbnails and use the full images from the datasource instead. purpose: Datasource purpose, determines if datasource is read only (INPUT) or can be written to as well (LIGHTLY, INPUT_OUTPUT). The latter is required when Lightly extracts frames from input videos. """ # TODO: Use DatasourceConfigGCS once we switch/update the api generator. self._datasources_api.update_datasource_by_dataset_id( datasource_config=DatasourceConfig.from_dict( { "type": "GCS", "fullPath": resource_path, "thumbSuffix": thumbnail_suffix, "gcsProjectId": project_id, "gcsCredentials": credentials, "purpose": purpose, } ), dataset_id=self.dataset_id, ) def set_local_config( self, resource_path: str, thumbnail_suffix: Optional[ str ] = ".lightly/thumbnails/[filename]_thumb.[extension]", ) -> None: """Sets the local configuration for the datasource of the current dataset. Find a detailed explanation on how to setup Lightly with a local file server in our docs: https://docs.lightly.ai/getting_started/dataset_creation/dataset_creation_local_server.html Args: resource_path: Url to your local file server, for example: "http://localhost:1234/path/to/my/data". thumbnail_suffix: Where to save thumbnails of the images in the dataset, for example ".lightly/thumbnails/[filename]_thumb.[extension]". Set to None to disable thumbnails and use the full images from the datasource instead. """ # TODO: Use DatasourceConfigLocal once we switch/update the api generator. self._datasources_api.update_datasource_by_dataset_id( datasource_config=DatasourceConfig.from_dict( { "type": "LOCAL", "fullPath": resource_path, "thumbSuffix": thumbnail_suffix, "purpose": DatasourcePurpose.INPUT_OUTPUT, } ), dataset_id=self.dataset_id, ) def set_s3_config( self, resource_path: str, region: str, access_key: str, secret_access_key: str, thumbnail_suffix: Optional[ str ] = ".lightly/thumbnails/[filename]_thumb.[extension]", purpose: str = DatasourcePurpose.INPUT_OUTPUT, ) -> None: """Sets the S3 configuration for the datasource of the current dataset. See our docs for a detailed explanation on how to setup Lightly with AWS S3: https://docs.lightly.ai/docs/aws-s3 Args: resource_path: S3 url of your dataset, for example "s3://my_bucket/path/to/my/data". region: S3 region where the dataset bucket is located, for example "eu-central-1". access_key: S3 access key. secret_access_key: Secret for the S3 access key. thumbnail_suffix: Where to save thumbnails of the images in the dataset, for example ".lightly/thumbnails/[filename]_thumb.[extension]". Set to None to disable thumbnails and use the full images from the datasource instead. purpose: Datasource purpose, determines if datasource is read only (INPUT) or can be written to as well (LIGHTLY, INPUT_OUTPUT). The latter is required when Lightly extracts frames from input videos. """ # TODO: Use DatasourceConfigS3 once we switch/update the api generator. self._datasources_api.update_datasource_by_dataset_id( datasource_config=DatasourceConfig.from_dict( { "type": "S3", "fullPath": resource_path, "thumbSuffix": thumbnail_suffix, "s3Region": region, "s3AccessKeyId": access_key, "s3SecretAccessKey": secret_access_key, "purpose": purpose, } ), dataset_id=self.dataset_id, ) def set_s3_delegated_access_config( self, resource_path: str, region: str, role_arn: str, external_id: str, thumbnail_suffix: Optional[ str ] = ".lightly/thumbnails/[filename]_thumb.[extension]", purpose: str = DatasourcePurpose.INPUT_OUTPUT, ) -> None: """Sets the S3 configuration for the datasource of the current dataset. See our docs for a detailed explanation on how to setup Lightly with AWS S3 and delegated access: https://docs.lightly.ai/docs/aws-s3#delegated-access Args: resource_path: S3 url of your dataset, for example "s3://my_bucket/path/to/my/data". region: S3 region where the dataset bucket is located, for example "eu-central-1". role_arn: Unique ARN identifier of the role. external_id: External ID of the role. thumbnail_suffix: Where to save thumbnails of the images in the dataset, for example ".lightly/thumbnails/[filename]_thumb.[extension]". Set to None to disable thumbnails and use the full images from the datasource instead. purpose: Datasource purpose, determines if datasource is read only (INPUT) or can be written to as well (LIGHTLY, INPUT_OUTPUT). The latter is required when Lightly extracts frames from input videos. """ # TODO: Use DatasourceConfigS3 once we switch/update the api generator. self._datasources_api.update_datasource_by_dataset_id( datasource_config=DatasourceConfig.from_dict( { "type": "S3DelegatedAccess", "fullPath": resource_path, "thumbSuffix": thumbnail_suffix, "s3Region": region, "s3ARN": role_arn, "s3ExternalId": external_id, "purpose": purpose, } ), dataset_id=self.dataset_id, ) def set_obs_config( self, resource_path: str, obs_endpoint: str, obs_access_key_id: str, obs_secret_access_key: str, thumbnail_suffix: Optional[ str ] = ".lightly/thumbnails/[filename]_thumb.[extension]", purpose: str = DatasourcePurpose.INPUT_OUTPUT, ) -> None: """Sets the Telekom OBS configuration for the datasource of the current dataset. Args: resource_path: OBS url of your dataset. For example, "obs://my_bucket/path/to/my/data". obs_endpoint: OBS endpoint. obs_access_key_id: OBS access key id. obs_secret_access_key: OBS secret access key. thumbnail_suffix: Where to save thumbnails of the images in the dataset, for example ".lightly/thumbnails/[filename]_thumb.[extension]". Set to None to disable thumbnails and use the full images from the datasource instead. purpose: Datasource purpose, determines if datasource is read only (INPUT) or can be written to as well (LIGHTLY, INPUT_OUTPUT). The latter is required when Lightly extracts frames from input videos. """ # TODO: Use DatasourceConfigOBS once we switch/update the api generator. self._datasources_api.update_datasource_by_dataset_id( datasource_config=DatasourceConfig.from_dict( { "type": "OBS", "fullPath": resource_path, "thumbSuffix": thumbnail_suffix, "obsEndpoint": obs_endpoint, "obsAccessKeyId": obs_access_key_id, "obsSecretAccessKey": obs_secret_access_key, "purpose": purpose, } ), dataset_id=self.dataset_id, ) def get_prediction_read_url( self, filename: str, ): """Returns a read-url for .lightly/predictions/{filename}. Args: filename: Filename for which to get the read-url. Returns: A read-url to the file. Note that a URL will be returned even if the file does not exist. """ return self._datasources_api.get_prediction_file_read_url_from_datasource_by_dataset_id( dataset_id=self.dataset_id, file_name=filename, ) def get_metadata_read_url( self, filename: str, ): """Returns a read-url for .lightly/metadata/{filename}. Args: filename: Filename for which to get the read-url. Returns: A read-url to the file. Note that a URL will be returned even if the file does not exist. """ return self._datasources_api.get_metadata_file_read_url_from_datasource_by_dataset_id( dataset_id=self.dataset_id, file_name=filename, ) def get_custom_embedding_read_url( self, filename: str, ) -> str: """Returns a read-url for .lightly/embeddings/{filename}. Args: filename: Filename for which to get the read-url. Returns: A read-url to the file. Note that a URL will be returned even if the file does not exist. """ return self._datasources_api.get_custom_embedding_file_read_url_from_datasource_by_dataset_id( dataset_id=self.dataset_id, file_name=filename, ) def list_datasource_permissions( self, ) -> Dict[str, Union[bool, Dict[str, str]]]: """Lists granted access permissions for the datasource set up with a dataset. Returns a string dictionary, with each permission mapped to a boolean value, see the example below. An additional ``errors`` key is present if any permission errors have been encountered. Permission errors are stored in a dictionary where permission names are keys and error messages are values. >>> from lightly.api import ApiWorkflowClient >>> client = ApiWorkflowClient( ... token="MY_LIGHTLY_TOKEN", dataset_id="MY_DATASET_ID" ... ) >>> client.list_datasource_permissions() { 'can_read': True, 'can_write': True, 'can_list': False, 'can_overwrite': True, 'errors': {'can_list': 'error message'} } """ return self._datasources_api.verify_datasource_by_dataset_id( dataset_id=self.dataset_id, ).to_dict()
32,700
40.237074
139
py
lightly
lightly-master/lightly/api/api_workflow_download_dataset.py
import io import os import urllib.request import warnings from concurrent.futures.thread import ThreadPoolExecutor from typing import Dict, List, Optional from urllib.request import Request import tqdm from PIL import Image from lightly.api import download, utils from lightly.api.bitmask import BitMask from lightly.openapi_generated.swagger_client.models import ( DatasetEmbeddingData, ImageType, ) from lightly.utils.hipify import bcolors def _make_dir_and_save_image(output_dir: str, filename: str, img: Image): """Saves the images and creates necessary subdirectories.""" path = os.path.join(output_dir, filename) head = os.path.split(path)[0] if not os.path.exists(head): os.makedirs(head) img.save(path) img.close() def _get_image_from_read_url(read_url: str): """Makes a get request to the signed read url and returns the image.""" request = Request(read_url, method="GET") with urllib.request.urlopen(request) as response: blob = response.read() img = Image.open(io.BytesIO(blob)) return img class _DownloadDatasetMixin: def download_dataset( self, output_dir: str, tag_name: str = "initial-tag", max_workers: int = 8, verbose: bool = True, ) -> None: """Downloads images from the web-app and stores them in output_dir. Args: output_dir: Where to store the downloaded images. tag_name: Name of the tag which should be downloaded. max_workers: Maximum number of workers downloading images in parallel. verbose: Whether or not to show the progress bar. Raises: ValueError: If the specified tag does not exist on the dataset. RuntimeError: If the connection to the server failed. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> client.download_dataset("/tmp/data") Downloading 3 images (with 3 workers): 100%|██████████████████████████████████| 3/3 [00:01<00:00, 1.99imgs/s] """ # check if images are available dataset = self._datasets_api.get_dataset_by_id(self.dataset_id) if dataset.img_type != ImageType.FULL: # only thumbnails or metadata available raise ValueError( f"Dataset with id {self.dataset_id} has no downloadable images!" ) # check if tag exists available_tags = self.get_all_tags() try: tag = next(tag for tag in available_tags if tag.name == tag_name) except StopIteration: raise ValueError( f"Dataset with id {self.dataset_id} has no tag {tag_name}!" ) # get sample ids sample_ids = self._mappings_api.get_sample_mappings_by_dataset_id( self.dataset_id, field="_id" ) indices = BitMask.from_hex(tag.bit_mask_data).to_indices() sample_ids = [sample_ids[i] for i in indices] filenames_on_server = self.get_filenames() filenames = [filenames_on_server[i] for i in indices] downloadables = zip(sample_ids, filenames) # handle the case where len(sample_ids) < max_workers max_workers = min(len(sample_ids), max_workers) max_workers = max(max_workers, 1) if verbose: print( f"Downloading {bcolors.OKGREEN}{len(sample_ids)}{bcolors.ENDC} images (with {bcolors.OKGREEN}{max_workers}{bcolors.ENDC} workers):", flush=True, ) pbar = tqdm.tqdm(unit="imgs", total=len(sample_ids)) tqdm_lock = tqdm.tqdm.get_lock() # define lambda function for concurrent download def lambda_(i): sample_id, filename = i # try to download image try: read_url = self._samples_api.get_sample_image_read_url_by_id( dataset_id=self.dataset_id, sample_id=sample_id, type="full", ) img = _get_image_from_read_url(read_url) _make_dir_and_save_image(output_dir, filename, img) success = True except Exception as e: # pylint: disable=broad-except warnings.warn(f"Downloading of image {filename} failed with error {e}") success = False # update the progress bar if verbose: tqdm_lock.acquire() pbar.update(1) tqdm_lock.release() # return whether the download was successful return success with ThreadPoolExecutor(max_workers=max_workers) as executor: results = list(executor.map(lambda_, downloadables, chunksize=1)) if not all(results): msg = "Warning: Unsuccessful download! " msg += "Failed at image: {}".format(results.index(False)) warnings.warn(msg) def get_all_embedding_data(self) -> List[DatasetEmbeddingData]: """Fetches embedding data of all embeddings for this dataset. Returns: A list of embedding data. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> client.get_all_embedding_data() [{'created_at': 1684750552181, 'id': '646b40d88355e2f54c6d2235', 'is2d': False, 'is_processed': True, 'name': 'default_20230522_10h15m50s'}] """ return self._embeddings_api.get_embeddings_by_dataset_id( dataset_id=self.dataset_id ) def get_embedding_data_by_name(self, name: str) -> DatasetEmbeddingData: """Fetches embedding data with the given name for this dataset. Args: name: Embedding name. Returns: Embedding data. Raises: ValueError: If no embedding with this name exists. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> client.get_embedding_data_by_name("embedding-data") [{'created_at': 1654756552401, 'id': '646f346004d77b4e1424e67e', 'is2d': False, 'is_processed': True, 'name': 'embedding-data'}] """ for embedding_data in self.get_all_embedding_data(): if embedding_data.name == name: return embedding_data raise ValueError( f"There are no embeddings with name '{name}' for dataset with id " f"'{self.dataset_id}'." ) def download_embeddings_csv_by_id( self, embedding_id: str, output_path: str, ) -> None: """Downloads embeddings with the given embedding id from the dataset. Args: embedding_id: ID of the embedding data to be downloaded. output_path: Where the downloaded embedding data should be stored. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> client.download_embeddings_csv_by_id( ... embedding_id="646f346004d77b4e1424e67e", ... output_path="/tmp/embeddings.csv" ... ) >>> >>> # File content: >>> # filenames,embedding_0,embedding_1,embedding_...,labels >>> # image-1.png,0.2124302,-0.26934767,...,0 """ read_url = self._embeddings_api.get_embeddings_csv_read_url_by_id( dataset_id=self.dataset_id, embedding_id=embedding_id ) download.download_and_write_file(url=read_url, output_path=output_path) def download_embeddings_csv(self, output_path: str) -> None: """Downloads the latest embeddings from the dataset. Args: output_path: Where the downloaded embedding data should be stored. Raises: RuntimeError: If no embeddings could be found for the dataset. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> client.download_embeddings_csv(output_path="/tmp/embeddings.csv") >>> >>> # File content: >>> # filenames,embedding_0,embedding_1,embedding_...,labels >>> # image-1.png,0.2124302,-0.26934767,...,0 """ last_embedding = _get_latest_default_embedding_data( embeddings=self.get_all_embedding_data() ) if last_embedding is None: raise RuntimeError( f"Could not find embeddings for dataset with id '{self.dataset_id}'." ) self.download_embeddings_csv_by_id( embedding_id=last_embedding.id, output_path=output_path, ) def export_label_studio_tasks_by_tag_id( self, tag_id: str, ) -> List[Dict]: """Exports samples in a format compatible with Label Studio. The format is documented here: https://labelstud.io/guide/tasks.html#Basic-Label-Studio-JSON-format Args: tag_id: Id of the tag which should exported. Returns: A list of dictionaries in a format compatible with Label Studio. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> client.export_label_studio_tasks_by_tag_id(tag_id="646f34608a5613b57d8b73cc") [{'id': 0, 'data': {'image': '...', ...}}] """ label_studio_tasks = list( utils.paginate_endpoint( self._tags_api.export_tag_to_label_studio_tasks, page_size=20000, dataset_id=self.dataset_id, tag_id=tag_id, ) ) return label_studio_tasks def _get_latest_default_embedding_data( embeddings: List[DatasetEmbeddingData], ) -> Optional[DatasetEmbeddingData]: """Returns the latest embedding data with a default name or None if no such default embedding exists. """ default_embeddings = [e for e in embeddings if e.name.startswith("default")] if default_embeddings: last_embedding = sorted(default_embeddings, key=lambda e: e.created_at)[-1] return last_embedding else: return None
11,378
34.783019
148
py
lightly
lightly-master/lightly/api/api_workflow_export.py
import warnings from typing import Dict, List from lightly.api import utils from lightly.openapi_generated.swagger_client.models import ( FileNameFormat, LabelBoxDataRow, LabelBoxV4DataRow, LabelStudioTask, ) class _ExportDatasetMixin: def export_label_studio_tasks_by_tag_id( self, tag_id: str, ) -> List[Dict]: """Fetches samples in a format compatible with Label Studio. The format is documented here: https://labelstud.io/guide/tasks.html#Basic-Label-Studio-JSON-format More information: https://docs.lightly.ai/docs/labelstudio-integration Args: tag_id: ID of the tag which should exported. Returns: A list of dictionaries in a format compatible with Label Studio. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> client.export_label_studio_tasks_by_tag_id(tag_id="646f34608a5613b57d8b73cc") [{'id': 0, 'data': {'image': '...', ...}}] """ label_studio_tasks: List[LabelStudioTask] = list( utils.paginate_endpoint( self._tags_api.export_tag_to_label_studio_tasks, page_size=20000, dataset_id=self.dataset_id, tag_id=tag_id, ) ) return [task.to_dict(by_alias=True) for task in label_studio_tasks] def export_label_studio_tasks_by_tag_name( self, tag_name: str, ) -> List[Dict]: """Fetches samples in a format compatible with Label Studio. The format is documented here: https://labelstud.io/guide/tasks.html#Basic-Label-Studio-JSON-format More information: https://docs.lightly.ai/docs/labelstudio-integration Args: tag_name: Name of the tag which should exported. Returns: A list of dictionaries in a format compatible with Label Studio. Examples: >>> # write json file which can be imported in Label Studio >>> tasks = client.export_label_studio_tasks_by_tag_name( >>> 'initial-tag' >>> ) >>> >>> with open('my-label-studio-tasks.json', 'w') as f: >>> json.dump(tasks, f) """ tag = self.get_tag_by_name(tag_name) return self.export_label_studio_tasks_by_tag_id(tag.id) def export_label_box_data_rows_by_tag_id( self, tag_id: str, ) -> List[Dict]: """Fetches samples in a format compatible with Labelbox v3. The format is documented here: https://docs.labelbox.com/docs/images-json More information: https://docs.lightly.ai/docs/labelbox Args: tag_id: ID of the tag which should exported. Returns: A list of dictionaries in a format compatible with Labelbox v3. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> client.export_label_box_data_rows_by_tag_id(tag_id="646f34608a5613b57d8b73cc") [{'externalId': '2218961434_7916358f53_z.jpg', 'imageUrl': ...}] """ warnings.warn( DeprecationWarning( "This method exports data in the deprecated Labelbox v3 format and " "will be removed in the future. Use export_label_box_v4_data_rows_by_tag_id " "to export data in the Labelbox v4 format instead." ) ) label_box_data_rows: List[LabelBoxDataRow] = list( utils.paginate_endpoint( self._tags_api.export_tag_to_label_box_data_rows, page_size=20000, dataset_id=self.dataset_id, tag_id=tag_id, ) ) return [row.to_dict(by_alias=True) for row in label_box_data_rows] def export_label_box_data_rows_by_tag_name( self, tag_name: str, ) -> List[Dict]: """Fetches samples in a format compatible with Labelbox v3. The format is documented here: https://docs.labelbox.com/docs/images-json More information: https://docs.lightly.ai/docs/labelbox Args: tag_name: Name of the tag which should exported. Returns: A list of dictionaries in a format compatible with Labelbox v3. Examples: >>> # write json file which can be imported in Label Studio >>> tasks = client.export_label_box_data_rows_by_tag_name( >>> 'initial-tag' >>> ) >>> >>> with open('my-labelbox-rows.json', 'w') as f: >>> json.dump(tasks, f) """ warnings.warn( DeprecationWarning( "This method exports data in the deprecated Labelbox v3 format and " "will be removed in the future. Use export_label_box_v4_data_rows_by_tag_name " "to export data in the Labelbox v4 format instead." ) ) tag = self.get_tag_by_name(tag_name) return self.export_label_box_data_rows_by_tag_id(tag.id) def export_label_box_v4_data_rows_by_tag_id( self, tag_id: str, ) -> List[Dict]: """Fetches samples in a format compatible with Labelbox v4. The format is documented here: https://docs.labelbox.com/docs/images-json More information: https://docs.lightly.ai/docs/labelbox Args: tag_id: ID of the tag which should exported. Returns: A list of dictionaries in a format compatible with Labelbox v4. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> client.export_label_box_v4_data_rows_by_tag_id(tag_id="646f34608a5613b57d8b73cc") [{'row_data': '...', 'global_key': 'image-1.jpg', 'media_type': 'IMAGE'} """ label_box_data_rows: List[LabelBoxV4DataRow] = list( utils.paginate_endpoint( self._tags_api.export_tag_to_label_box_v4_data_rows, page_size=20000, dataset_id=self.dataset_id, tag_id=tag_id, ) ) return [row.to_dict() for row in label_box_data_rows] def export_label_box_v4_data_rows_by_tag_name( self, tag_name: str, ) -> List[Dict]: """Fetches samples in a format compatible with Labelbox. The format is documented here: https://docs.labelbox.com/docs/images-json More information: https://docs.lightly.ai/docs/labelbox Args: tag_name: Name of the tag which should exported. Returns: A list of dictionaries in a format compatible with Labelbox. Examples: >>> # write json file which can be imported in Label Studio >>> tasks = client.export_label_box_v4_data_rows_by_tag_name( >>> 'initial-tag' >>> ) >>> >>> with open('my-labelbox-rows.json', 'w') as f: >>> json.dump(tasks, f) """ tag = self.get_tag_by_name(tag_name) return self.export_label_box_v4_data_rows_by_tag_id(tag.id) def export_filenames_by_tag_id( self, tag_id: str, ) -> str: """Fetches samples filenames within a certain tag by tag ID. More information: https://docs.lightly.ai/docs/filenames-and-readurls Args: tag_id: ID of the tag which should exported. Returns: A list of filenames of samples within a certain tag. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> client.export_filenames_by_tag_id("646b40d6c06aae1b91294a9e") 'image-1.jpg\nimage-2.jpg\nimage-3.jpg' """ filenames = "\n".join( utils.paginate_endpoint( self._tags_api.export_tag_to_basic_filenames, dataset_id=self.dataset_id, tag_id=tag_id, ) ) return filenames def export_filenames_by_tag_name( self, tag_name: str, ) -> str: """Fetches samples filenames within a certain tag by tag name. More information: https://docs.lightly.ai/docs/filenames-and-readurls Args: tag_name: Name of the tag which should exported. Returns: A list of filenames of samples within a certain tag. Examples: >>> # write json file which can be imported in Label Studio >>> filenames = client.export_filenames_by_tag_name( >>> 'initial-tag' >>> ) >>> >>> with open('filenames-of-initial-tag.txt', 'w') as f: >>> f.write(filenames) """ tag = self.get_tag_by_name(tag_name) return self.export_filenames_by_tag_id(tag.id) def export_filenames_and_read_urls_by_tag_id( self, tag_id: str, ) -> List[Dict[str, str]]: """Fetches filenames, read URLs, and datasource URLs from the given tag. More information: https://docs.lightly.ai/docs/filenames-and-readurls Args: tag_id: ID of the tag which should exported. Returns: A list of dictionaries with the keys "filename", "readUrl" and "datasourceUrl". An example: [ { "fileName": "sample1.jpg", "readUrl": "s3://my_datasource/sample1.jpg?read_url_key=EAIFUIENDLFN", "datasourceUrl": "s3://my_datasource/sample1.jpg", }, { "fileName": "sample2.jpg", "readUrl": "s3://my_datasource/sample2.jpg?read_url_key=JSBFIEUHVSJ", "datasourceUrl": "s3://my_datasource/sample2.jpg", }, ] """ filenames_string = "\n".join( utils.paginate_endpoint( self._tags_api.export_tag_to_basic_filenames, dataset_id=self.dataset_id, tag_id=tag_id, file_name_format=FileNameFormat.NAME, ) ) read_urls_string = "\n".join( utils.paginate_endpoint( self._tags_api.export_tag_to_basic_filenames, dataset_id=self.dataset_id, tag_id=tag_id, file_name_format=FileNameFormat.REDIRECTED_READ_URL, ) ) datasource_urls_string = "\n".join( utils.paginate_endpoint( self._tags_api.export_tag_to_basic_filenames, dataset_id=self.dataset_id, tag_id=tag_id, file_name_format=FileNameFormat.DATASOURCE_FULL, ) ) # The endpoint exportTagToBasicFilenames returns a plain string so we # have to split it by newlines in order to get the individual entries. # The order of the fileNames and readUrls and datasourceUrls is guaranteed to be the same # by the API so we can simply zip them. filenames = filenames_string.split("\n") read_urls = read_urls_string.split("\n") datasource_urls = datasource_urls_string.split("\n") return [ { "fileName": filename, "readUrl": read_url, "datasourceUrl": datasource_url, } for filename, read_url, datasource_url in zip( filenames, read_urls, datasource_urls ) ] def export_filenames_and_read_urls_by_tag_name( self, tag_name: str, ) -> List[Dict[str, str]]: """Fetches filenames, read URLs, and datasource URLs from the given tag name. More information: https://docs.lightly.ai/docs/filenames-and-readurls Args: tag_name: Name of the tag which should exported. Returns: A list of dictionaries with keys "filename", "readUrl" and "datasourceUrl". Examples: >>> # write json file which can be used to access the actual file contents. >>> mappings = client.export_filenames_and_read_urls_by_tag_name( >>> 'initial-tag' >>> ) >>> >>> with open('my-samples.json', 'w') as f: >>> json.dump(mappings, f) """ tag = self.get_tag_by_name(tag_name) return self.export_filenames_and_read_urls_by_tag_id(tag.id)
13,415
33.488432
97
py
lightly
lightly-master/lightly/api/api_workflow_predictions.py
from typing import Sequence from lightly.openapi_generated.swagger_client.models import ( PredictionSingleton, PredictionTaskSchema, ) class _PredictionsMixin: def create_or_update_prediction_task_schema( self, schema: PredictionTaskSchema, prediction_version_id: int = -1, ) -> None: """Creates or updates the prediction task schema. Args: schema: The prediction task schema. prediction_version_id: A numerical ID (e.g., timestamp) to distinguish different predictions of different model versions. Use the same ID if you don't require versioning or if you wish to overwrite the previous schema. Example: >>> import time >>> from lightly.api import ApiWorkflowClient >>> from lightly.openapi_generated.swagger_client.models import ( >>> PredictionTaskSchema, >>> TaskType, >>> PredictionTaskSchemaCategory, >>> ) >>> >>> client = ApiWorkflowClient( >>> token="MY_LIGHTLY_TOKEN", dataset_id="MY_DATASET_ID" >>> ) >>> >>> schema = PredictionTaskSchema( >>> name="my-object-detection", >>> type=TaskType.OBJECT_DETECTION, >>> categories=[ >>> PredictionTaskSchemaCategory(id=0, name="dog"), >>> PredictionTaskSchemaCategory(id=1, name="cat"), >>> ], >>> ) >>> client.create_or_update_prediction_task_schema(schema=schema) """ self._predictions_api.create_or_update_prediction_task_schema_by_dataset_id( prediction_task_schema=schema, dataset_id=self.dataset_id, prediction_uuid_timestamp=prediction_version_id, ) def create_or_update_prediction( self, sample_id: str, prediction_singletons: Sequence[PredictionSingleton], prediction_version_id: int = -1, ) -> None: """Creates or updates predictions for one specific sample. Args: sample_id The ID of the sample. prediction_version_id: A numerical ID (e.g., timestamp) to distinguish different predictions of different model versions. Use the same id if you don't require versioning or if you wish to overwrite the previous schema. This ID must match the ID of a prediction task schema. prediction_singletons: Predictions to be uploaded for the designated sample. """ self._predictions_api.create_or_update_prediction_by_sample_id( prediction_singleton=prediction_singletons, dataset_id=self.dataset_id, sample_id=sample_id, prediction_uuid_timestamp=prediction_version_id, )
2,932
35.209877
114
py
lightly
lightly-master/lightly/api/api_workflow_selection.py
import time import warnings from typing import Dict, List, Optional, Union import numpy as np from numpy.typing import NDArray from lightly.active_learning.config.selection_config import SelectionConfig from lightly.openapi_generated.swagger_client.models import ( ActiveLearningScoreCreateRequest, JobState, JobStatusData, SamplingConfig, SamplingConfigStoppingCondition, SamplingCreateRequest, TagData, ) def _parse_active_learning_scores(scores: Union[np.ndarray, List]): """Makes list/np.array of active learning scores serializable.""" # the api only accepts float64s if isinstance(scores, np.ndarray): scores = scores.astype(np.float64) # convert to list and return return list(scores) class _SelectionMixin: def upload_scores( self, al_scores: Dict[str, NDArray[np.float_]], query_tag_id: str ) -> None: """Uploads active learning scores for a tag. Args: al_scores: Active learning scores. Must be a mapping between score names and score arrays. The length of each score array must match samples in the designated tag. query_tag_id: ID of the desired tag. """ # iterate over all available score types and upload them for score_type, score_values in al_scores.items(): body = ActiveLearningScoreCreateRequest( score_type=score_type, scores=_parse_active_learning_scores(score_values), ) self._scores_api.create_or_update_active_learning_score_by_tag_id( active_learning_score_create_request=body, dataset_id=self.dataset_id, tag_id=query_tag_id, ) def selection( self, selection_config: SelectionConfig, preselected_tag_id: Optional[str] = None, query_tag_id: Optional[str] = None, ) -> TagData: """Performs a selection given the arguments. Args: selection_config: The configuration of the selection. preselected_tag_id: The tag defining the already chosen samples (e.g., already labelled ones). Optional. query_tag_id: ID of the tag where samples should be fetched. None resolves to `initial-tag`. Defaults to None. Returns: The newly created tag of the selection. Raises: RuntimeError: When a tag with the tag name specified in the selection config already exists. When `initial-tag` does not exist in the dataset. When the selection task fails. """ warnings.warn( DeprecationWarning( "ApiWorkflowClient.selection() is deprecated " "and will be removed in the future." ), ) # make sure the tag name does not exist yet tags = self.get_all_tags() if selection_config.name in [tag.name for tag in tags]: raise RuntimeError( f"There already exists a tag with tag_name {selection_config.name}." ) if len(tags) == 0: raise RuntimeError("There exists no initial-tag for this dataset.") # make sure we have an embedding id try: self.embedding_id except AttributeError: self.set_embedding_id_to_latest() # trigger the selection payload = self._create_selection_create_request( selection_config, preselected_tag_id, query_tag_id ) payload.row_count = self.get_all_tags()[0].tot_size response = self._selection_api.trigger_sampling_by_id( sampling_create_request=payload, dataset_id=self.dataset_id, embedding_id=self.embedding_id, ) job_id = response.job_id # poll the job status till the job is not running anymore exception_counter = 0 # TODO; remove after solving https://github.com/lightly-ai/lightly-core/issues/156 job_status_data = None wait_time_till_next_poll = getattr(self, "wait_time_till_next_poll", 1) while ( job_status_data is None or job_status_data.status == JobState.RUNNING or job_status_data.status == JobState.WAITING or job_status_data.status == JobState.UNKNOWN ): # sleep before polling again time.sleep(wait_time_till_next_poll) # try to read the sleep time until the next poll from the status data try: job_status_data: JobStatusData = self._jobs_api.get_job_status_by_id( job_id=job_id ) wait_time_till_next_poll = job_status_data.wait_time_till_next_poll except Exception as err: exception_counter += 1 if exception_counter == 20: print( f"Selection job with job_id {job_id} could not be started because of error: {err}" ) raise err if job_status_data.status == JobState.FAILED: raise RuntimeError( f"Selection job with job_id {job_id} failed with error {job_status_data.error}" ) # get the new tag from the job status new_tag_id = job_status_data.result.data if new_tag_id is None: raise RuntimeError(f"TagId returned by job with job_id {job_id} is None.") new_tag_data = self._tags_api.get_tag_by_tag_id( dataset_id=self.dataset_id, tag_id=new_tag_id ) return new_tag_data def _create_selection_create_request( self, selection_config: SelectionConfig, preselected_tag_id: Optional[str], query_tag_id: Optional[str], ) -> SamplingCreateRequest: """Creates a SamplingCreateRequest First, it checks how many samples are already labeled by getting the number of samples in the preselected_tag_id. Then the stopping_condition.n_samples is set to be the number of already labeled samples + the selection_config.batch_size. Last the SamplingCreateRequest is created with the necessary nested class instances. """ sampling_config = SamplingConfig( stopping_condition=SamplingConfigStoppingCondition( n_samples=selection_config.n_samples, min_distance=selection_config.min_distance, ) ) sampling_create_request = SamplingCreateRequest( new_tag_name=selection_config.name, method=selection_config.method, config=sampling_config, preselected_tag_id=preselected_tag_id, query_tag_id=query_tag_id, ) return sampling_create_request
6,982
35.752632
113
py
lightly
lightly-master/lightly/api/api_workflow_tags.py
from typing import * from lightly.api.bitmask import BitMask from lightly.openapi_generated.swagger_client.models import ( TagArithmeticsOperation, TagArithmeticsRequest, TagBitMaskResponse, TagCreateRequest, TagData, ) class TagDoesNotExistError(ValueError): pass class _TagsMixin: def get_all_tags(self) -> List[TagData]: """Gets all tags in the Lightly Platform from the current dataset. Returns: A list of tags. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> client.get_all_tags() [{'created_at': 1684750550014, 'dataset_id': '646b40a18355e2f54c6d2200', 'id': '646b40d6c06aae1b91294a9e', 'last_modified_at': 1684750550014, 'name': 'cool-tag', 'preselected_tag_id': None, ...}] """ return self._tags_api.get_tags_by_dataset_id(self.dataset_id) def get_tag_by_id(self, tag_id: str) -> TagData: """Gets a tag from the current dataset by tag ID. Args: tag_id: ID of the requested tag. Returns: Tag data for the requested tag. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> client.get_tag_by_id("646b40d6c06aae1b91294a9e") {'created_at': 1684750550014, 'dataset_id': '646b40a18355e2f54c6d2200', 'id': '646b40d6c06aae1b91294a9e', 'last_modified_at': 1684750550014, 'name': 'cool-tag', 'preselected_tag_id': None, ...} """ tag_data = self._tags_api.get_tag_by_tag_id( dataset_id=self.dataset_id, tag_id=tag_id ) return tag_data def get_tag_by_name(self, tag_name: str) -> TagData: """Gets a tag from the current dataset by tag name. Args: tag_name: Name of the requested tag. Returns: Tag data for the requested tag. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> client.get_tag_by_name("cool-tag") {'created_at': 1684750550014, 'dataset_id': '646b40a18355e2f54c6d2200', 'id': '646b40d6c06aae1b91294a9e', 'last_modified_at': 1684750550014, 'name': 'cool-tag', 'preselected_tag_id': None, ...} """ tag_name_id_dict = {tag.name: tag.id for tag in self.get_all_tags()} tag_id = tag_name_id_dict.get(tag_name, None) if tag_id is None: raise TagDoesNotExistError(f"Your tag_name does not exist: {tag_name}.") return self.get_tag_by_id(tag_id) def get_filenames_in_tag( self, tag_data: TagData, filenames_on_server: List[str] = None, exclude_parent_tag: bool = False, ) -> List[str]: """Gets the filenames of samples under a tag. Args: tag_data: Information about the tag. filenames_on_server: List of all filenames on the server. If they are not given, they need to be downloaded, which is a time-consuming operation. exclude_parent_tag: Excludes the parent tag in the returned filenames. Returns: Filenames of all samples under the tag. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> tag = client.get_tag_by_name("cool-tag") >>> client.get_filenames_in_tag(tag_data=tag) ['image-1.png', 'image-2.png'] """ if exclude_parent_tag: parent_tag_id = tag_data.prev_tag_id tag_arithmetics_request = TagArithmeticsRequest( tag_id1=tag_data.id, tag_id2=parent_tag_id, operation=TagArithmeticsOperation.DIFFERENCE, ) bit_mask_response: TagBitMaskResponse = ( self._tags_api.perform_tag_arithmetics_bitmask( tag_arithmetics_request=tag_arithmetics_request, dataset_id=self.dataset_id, ) ) bit_mask_data = bit_mask_response.bit_mask_data else: bit_mask_data = tag_data.bit_mask_data if not filenames_on_server: filenames_on_server = self.get_filenames() filenames_tag = BitMask.from_hex(bit_mask_data).masked_select_from_list( filenames_on_server ) return filenames_tag def create_tag_from_filenames( self, fnames_new_tag: List[str], new_tag_name: str, parent_tag_id: str = None ) -> TagData: """Creates a new tag from a list of filenames. Args: fnames_new_tag: A list of filenames to be included in the new tag. new_tag_name: The name of the new tag. parent_tag_id: The tag defining where to sample from, default: None resolves to the initial-tag. Returns: The newly created tag. Raises: RuntimeError: When a tag with the desired tag name already exists. When `initial-tag` does not exist. When any of the given files does not exist. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> filenames = ['image-1.png', 'image-2.png'] >>> client.create_tag_from_filenames(fnames_new_tag=filenames, new_tag_name='new-tag') {'id': '6470c4c1060894655c5a8ed5'} """ # make sure the tag name does not exist yet tags = self.get_all_tags() if new_tag_name in [tag.name for tag in tags]: raise RuntimeError( f"There already exists a tag with tag_name {new_tag_name}." ) if len(tags) == 0: raise RuntimeError("There exists no initial-tag for this dataset.") # fallback to initial tag if no parent tag is provided if parent_tag_id is None: parent_tag_id = next(tag.id for tag in tags if tag.name == "initial-tag") # get list of filenames from tag fnames_server = self.get_filenames() tot_size = len(fnames_server) # create new bitmask for the new tag bitmask = BitMask(0) fnames_new_tag = set(fnames_new_tag) for i, fname in enumerate(fnames_server): if fname in fnames_new_tag: bitmask.set_kth_bit(i) # quick sanity check num_selected_samples = len(bitmask.to_indices()) if num_selected_samples != len(fnames_new_tag): raise RuntimeError( "An error occured when creating the new subset! " f"Out of the {len(fnames_new_tag)} filenames you provided " f"to create a new tag, only {num_selected_samples} have been " "found on the server. " "Make sure you use the correct filenames. " f"Valid filename example from the dataset: {fnames_server[0]}" ) # create new tag tag_data_dict = { "name": new_tag_name, "prevTagId": parent_tag_id, "bitMaskData": bitmask.to_hex(), "totSize": tot_size, "creator": self._creator, } new_tag = self._tags_api.create_tag_by_dataset_id( tag_create_request=TagCreateRequest.from_dict(tag_data_dict), dataset_id=self.dataset_id, ) return new_tag def delete_tag_by_id(self, tag_id: str) -> None: """Deletes a tag from the current dataset. Args: tag_id: The id of the tag to be deleted. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> filenames = ['image-1.png', 'image-2.png'] >>> tag_id = client.create_tag_from_filenames(fnames_new_tag=filenames, new_tag_name='new-tag')["id"] >>> client.delete_tag_by_id(tag_id=tag_id) """ self._tags_api.delete_tag_by_tag_id(dataset_id=self.dataset_id, tag_id=tag_id) def delete_tag_by_name(self, tag_name: str) -> None: """Deletes a tag from the current dataset. Args: tag_name: The name of the tag to be deleted. Examples: >>> client = ApiWorkflowClient(token="MY_AWESOME_TOKEN") >>> >>> # Already created some Lightly Worker runs with this dataset >>> client.set_dataset_id_by_name("my-dataset") >>> filenames = ['image-1.png', 'image-2.png'] >>> client.create_tag_from_filenames(fnames_new_tag=filenames, new_tag_name='new-tag') >>> client.delete_tag_by_name(tag_name="new-tag") """ tag_data = self.get_tag_by_name(tag_name=tag_name) self.delete_tag_by_id(tag_data.id)
10,007
35.392727
113
py
lightly
lightly-master/lightly/api/api_workflow_upload_embeddings.py
import csv import io import tempfile import urllib.request from datetime import datetime from typing import List from urllib.request import Request from lightly.api.utils import retry from lightly.openapi_generated.swagger_client.models import ( DatasetEmbeddingData, DimensionalityReductionMethod, Trigger2dEmbeddingJobRequest, WriteCSVUrlData, ) from lightly.utils import io as io_utils class EmbeddingDoesNotExistError(ValueError): pass class _UploadEmbeddingsMixin: def _get_csv_reader_from_read_url(self, read_url: str) -> None: """Makes a get request to the signed read url and returns the .csv file.""" request = Request(read_url, method="GET") with urllib.request.urlopen(request) as response: buffer = io.StringIO(response.read().decode("utf-8")) reader = csv.reader(buffer) return reader def set_embedding_id_to_latest(self) -> None: """Sets the embedding ID in the API client to the latest embedding ID in the current dataset.""" embeddings_on_server: List[ DatasetEmbeddingData ] = self._embeddings_api.get_embeddings_by_dataset_id( dataset_id=self.dataset_id ) if len(embeddings_on_server) == 0: raise RuntimeError( f"There are no known embeddings for dataset_id {self.dataset_id}." ) # return first entry as the API returns newest first self.embedding_id = embeddings_on_server[0].id def get_embedding_by_name( self, name: str, ignore_suffix: bool = True ) -> DatasetEmbeddingData: """Fetches an embedding in the current dataset by name. Args: name: The name of the desired embedding. ignore_suffix: If true, a suffix of the embedding name in the current dataset is ignored. Returns: The embedding data. Raises: EmbeddingDoesNotExistError: If the name does not match the name of an embedding on the server. """ embeddings_on_server: List[ DatasetEmbeddingData ] = self._embeddings_api.get_embeddings_by_dataset_id( dataset_id=self.dataset_id ) try: if ignore_suffix: embedding = next( embedding for embedding in embeddings_on_server if embedding.name.startswith(name) ) else: embedding = next( embedding for embedding in embeddings_on_server if embedding.name == name ) except StopIteration: raise EmbeddingDoesNotExistError( f"Embedding with the specified name " f"does not exist on the server: {name}" ) return embedding def upload_embeddings(self, path_to_embeddings_csv: str, name: str) -> None: """Uploads embeddings to the Lightly Platform. First checks that the specified embedding name is not on the server. If it is, the upload is aborted. Then creates a new csv file with the embeddings in the order specified on the server. Next uploads it to the Lightly Platform. The received embedding ID is stored in the API client. Args: path_to_embeddings_csv: The path to the .csv containing the embeddings, e.g. "path/to/embeddings.csv" name: The name of the embedding. If an embedding with such a name already exists on the server, the upload is aborted. """ io_utils.check_embeddings( path_to_embeddings_csv, remove_additional_columns=True ) # Try to append the embeddings on the server, if they exist try: embedding = self.get_embedding_by_name(name, ignore_suffix=True) # -> append rows from server print("Appending embeddings from server.") self.append_embeddings(path_to_embeddings_csv, embedding.id) now = datetime.now().strftime("%Y%m%d_%Hh%Mm%Ss") name = f"{name}_{now}" except EmbeddingDoesNotExistError: pass # create a new csv with the filenames in the desired order rows_csv = self._order_csv_by_filenames( path_to_embeddings_csv=path_to_embeddings_csv ) # get the URL to upload the csv to response: WriteCSVUrlData = ( self._embeddings_api.get_embeddings_csv_write_url_by_id( self.dataset_id, name=name ) ) self.embedding_id = response.embedding_id signed_write_url = response.signed_write_url # save the csv rows in a temporary in-memory string file # using a csv writer and then read them as bytes with tempfile.SpooledTemporaryFile(mode="rw") as f: writer = csv.writer(f) writer.writerows(rows_csv) f.seek(0) embeddings_csv_as_bytes = f.read().encode("utf-8") # write the bytes to a temporary in-memory byte file with tempfile.SpooledTemporaryFile(mode="r+b") as f_bytes: f_bytes.write(embeddings_csv_as_bytes) f_bytes.seek(0) retry( self.upload_file_with_signed_url, file=f_bytes, signed_write_url=signed_write_url, ) # trigger the 2d embeddings job for dimensionality_reduction_method in [ DimensionalityReductionMethod.PCA, DimensionalityReductionMethod.TSNE, DimensionalityReductionMethod.UMAP, ]: body = Trigger2dEmbeddingJobRequest( dimensionality_reduction_method=dimensionality_reduction_method ) self._embeddings_api.trigger2d_embeddings_job( trigger2d_embedding_job_request=body, dataset_id=self.dataset_id, embedding_id=self.embedding_id, ) def append_embeddings(self, path_to_embeddings_csv: str, embedding_id: str) -> None: """Concatenates embeddings from the Lightly Platform to the local ones. Loads the embedding csv file with the corresponding embedding ID in the current dataset and appends all of its rows to the local embeddings file located at 'path_to_embeddings_csv'. Args: path_to_embeddings_csv: The path to the csv containing the local embeddings. embedding_id: ID of the embedding summary of the embeddings on the Lightly Platform. Raises: RuntimeError: If the number of columns in the local embeddings file and that of the remote embeddings file mismatch. """ # read embedding from API embedding_read_url = self._embeddings_api.get_embeddings_csv_read_url_by_id( self.dataset_id, embedding_id ) embedding_reader = self._get_csv_reader_from_read_url(embedding_read_url) rows = list(embedding_reader) header, online_rows = rows[0], rows[1:] # read local embedding with open(path_to_embeddings_csv, "r") as f: local_rows = list(csv.reader(f)) if len(local_rows[0]) != len(header): raise RuntimeError( "Column mismatch! Number of columns in local and remote" f" embeddings files must match but are {len(local_rows[0])}" f" and {len(header)} respectively." ) local_rows = local_rows[1:] # combine online and local embeddings total_rows = [header] filename_to_local_row = {row[0]: row for row in local_rows} for row in online_rows: # pick local over online filename if it exists total_rows.append(filename_to_local_row.pop(row[0], row)) # add all local rows which were not added yet total_rows.extend(list(filename_to_local_row.values())) # save embeddings again with open(path_to_embeddings_csv, "w") as f: writer = csv.writer(f) writer.writerows(total_rows) def _order_csv_by_filenames(self, path_to_embeddings_csv: str) -> List[str]: """Orders the rows in a csv according to the order specified on the server and saves it as a new file. Args: path_to_embeddings_csv: the path to the csv to order Returns: the filepath to the new csv """ with open(path_to_embeddings_csv, "r") as f: data = csv.reader(f) rows = list(data) header_row = rows[0] rows_without_header = rows[1:] index_filenames = header_row.index("filenames") filenames = [row[index_filenames] for row in rows_without_header] filenames_on_server = self.get_filenames() if len(filenames) != len(filenames_on_server): raise ValueError( f"There are {len(filenames)} rows in the embedding file, but " f"{len(filenames_on_server)} filenames/samples on the server." ) if set(filenames) != set(filenames_on_server): raise ValueError( f"The filenames in the embedding file and " f"the filenames on the server do not align" ) io_utils.check_filenames(filenames) rows_without_header_ordered = self._order_list_by_filenames( filenames, rows_without_header ) rows_csv = [header_row] rows_csv += rows_without_header_ordered return rows_csv
9,941
36.235955
110
py
lightly
lightly-master/lightly/api/api_workflow_upload_metadata.py
from concurrent.futures import ThreadPoolExecutor from typing import Any, Dict, List, Union from requests import Response from tqdm import tqdm from lightly.api.utils import paginate_endpoint, retry from lightly.openapi_generated.swagger_client.models import ( ConfigurationEntry, ConfigurationSetRequest, SampleDataModes, SamplePartialMode, SampleUpdateRequest, ) from lightly.utils import hipify from lightly.utils.io import COCO_ANNOTATION_KEYS class InvalidCustomMetadataWarning(Warning): pass def _assert_key_exists_in_custom_metadata(key: str, dictionary: Dict[str, Any]): """Raises a formatted KeyError if key is not a key of the dictionary.""" if key not in dictionary.keys(): raise KeyError( f"Key {key} not found in custom metadata.\n" f"Found keys: {dictionary.keys()}" ) class _UploadCustomMetadataMixin: """Mixin of helpers to allow upload of custom metadata.""" def verify_custom_metadata_format(self, custom_metadata: Dict) -> None: """Verifies that the custom metadata is in the correct format. Args: custom_metadata: Dictionary of custom metadata, see upload_custom_metadata for the required format. Raises: KeyError: If "images" or "metadata" aren't a key of custom_metadata. """ _assert_key_exists_in_custom_metadata( COCO_ANNOTATION_KEYS.images, custom_metadata ) _assert_key_exists_in_custom_metadata( COCO_ANNOTATION_KEYS.custom_metadata, custom_metadata ) def index_custom_metadata_by_filename( self, custom_metadata: Dict[str, Any] ) -> Dict[str, Union[Dict, None]]: """Creates an index to lookup custom metadata by filename. Args: custom_metadata: Dictionary of custom metadata, see upload_custom_metadata for the required format. Returns: A dictionary mapping from filenames to custom metadata. If there are no annotations for a filename, the custom metadata is None instead. """ # The mapping is filename -> image_id -> custom_metadata # This mapping is created in linear time. filename_to_image_id = { image_info[COCO_ANNOTATION_KEYS.images_filename]: image_info[ COCO_ANNOTATION_KEYS.images_id ] for image_info in custom_metadata[COCO_ANNOTATION_KEYS.images] } image_id_to_custom_metadata = { metadata[COCO_ANNOTATION_KEYS.custom_metadata_image_id]: metadata for metadata in custom_metadata[COCO_ANNOTATION_KEYS.custom_metadata] } filename_to_metadata = { filename: image_id_to_custom_metadata.get(image_id, None) for (filename, image_id) in filename_to_image_id.items() } return filename_to_metadata def upload_custom_metadata( self, custom_metadata: Dict[str, Any], verbose: bool = False, max_workers: int = 8, ) -> None: """Uploads custom metadata to the Lightly Platform. The custom metadata is expected in a format similar to the COCO annotations: Under the key "images" there should be a list of dictionaries, each with a file_name and id. Under the key "metadata", the custom metadata is stored as a list of dictionaries, each with an image ID that corresponds to an image under the key "images". Example: >>> custom_metadata = { >>> "images": [ >>> { >>> "file_name": "image0.jpg", >>> "id": 0, >>> }, >>> { >>> "file_name": "image1.jpg", >>> "id": 1, >>> } >>> ], >>> "metadata": [ >>> { >>> "image_id": 0, >>> "number_of_people": 3, >>> "weather": { >>> "scenario": "cloudy", >>> "temperature": 20.3 >>> } >>> }, >>> { >>> "image_id": 1, >>> "number_of_people": 1, >>> "weather": { >>> "scenario": "rainy", >>> "temperature": 15.0 >>> } >>> } >>> ] >>> } Args: custom_metadata: Custom metadata as described above. verbose: If True, displays a progress bar during the upload. max_workers: Maximum number of concurrent threads during upload. """ self.verify_custom_metadata_format(custom_metadata) # For each metadata, we need the corresponding sample_id # on the server. The mapping is: # metadata -> image_id -> filename -> sample_id image_id_to_filename = { image_info[COCO_ANNOTATION_KEYS.images_id]: image_info[ COCO_ANNOTATION_KEYS.images_filename ] for image_info in custom_metadata[COCO_ANNOTATION_KEYS.images] } samples: List[SampleDataModes] = list( paginate_endpoint( self._samples_api.get_samples_partial_by_dataset_id, page_size=25000, # as this information is rather small, we can request a lot of samples at once dataset_id=self.dataset_id, mode=SamplePartialMode.FILENAMES, ) ) filename_to_sample_id = {sample.file_name: sample.id for sample in samples} upload_requests = [] for metadata in custom_metadata[COCO_ANNOTATION_KEYS.custom_metadata]: image_id = metadata[COCO_ANNOTATION_KEYS.custom_metadata_image_id] filename = image_id_to_filename.get(image_id, None) if filename is None: hipify.print_as_warning( "No image found for custom metadata annotation " f"with image_id {image_id}. " "This custom metadata annotation is skipped. ", InvalidCustomMetadataWarning, ) continue sample_id = filename_to_sample_id.get(filename, None) if sample_id is None: hipify.print_as_warning( "You tried to upload custom metadata for a sample with " f"filename {{{filename}}}, " "but a sample with this filename " "does not exist on the server. " "This custom metadata annotation is skipped. ", InvalidCustomMetadataWarning, ) continue upload_request = (metadata, sample_id) upload_requests.append(upload_request) # retry upload if it times out def upload_sample_metadata(upload_request): metadata, sample_id = upload_request request = SampleUpdateRequest(custom_meta_data=metadata) return retry( self._samples_api.update_sample_by_id, sample_update_request=request, dataset_id=self.dataset_id, sample_id=sample_id, ) # Upload in parallel with a limit on the number of concurrent requests with ThreadPoolExecutor(max_workers=max_workers) as executor: # get iterator over results results = executor.map(upload_sample_metadata, upload_requests) if verbose: results = tqdm(results, unit="metadata", total=len(upload_requests)) # iterate over results to make sure they are completed list(results) def create_custom_metadata_config( self, name: str, configs: List[ConfigurationEntry] ) -> Response: """Creates custom metadata config from a list of configurations. Args: name: The name of the custom metadata configuration. configs: List of metadata configuration entries. Returns: The API response. Examples: >>> from lightly.openapi_generated.swagger_codegen.models.configuration_entry import ConfigurationEntry >>> entry = ConfigurationEntry( >>> name='Weather', >>> path='weather', >>> default_value='unknown', >>> value_data_type='CATEGORICAL_STRING', >>> ) >>> >>> client.create_custom_metadata_config( >>> 'My Custom Metadata', >>> [entry], >>> ) """ config_set_request = ConfigurationSetRequest(name=name, configs=configs) resp = self._metadata_configurations_api.create_meta_data_configuration( configuration_set_request=config_set_request, dataset_id=self.dataset_id, ) return resp
9,323
36
115
py
lightly
lightly-master/lightly/api/bitmask.py
""" Module to work with Lightly BitMasks """ # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved import copy from typing import List def _hex_to_int(hexstring: str) -> int: """Converts a hex string representation of an integer to an integer.""" return int(hexstring, 16) def _bin_to_int(binstring: str) -> int: """Converts a binary string representation of an integer to an integer.""" return int(binstring, 2) def _int_to_hex(x: int) -> str: """Converts an integer to a hex string representation.""" return hex(x) def _int_to_bin(x: int) -> str: """Converts an integer to a binary string representation.""" return bin(x) def _get_nonzero_bits(x: int) -> List[int]: """Returns a list of indices of nonzero bits in x.""" offset = 0 nonzero_bit_indices = [] while x > 0: # if the number is odd, there is a nonzero bit at offset if x % 2 > 0: nonzero_bit_indices.append(offset) # increment the offset and divide the number x by two (rounding down) offset += 1 x = x // 2 return nonzero_bit_indices def _invert(x: int, total_size: int) -> int: """Flips every bit of x as if x was an unsigned integer.""" # use XOR of x and 0xFFFFFF to get the inverse return x ^ (2**total_size - 1) def _union(x: int, y: int) -> int: """Uses bitwise OR to get the union of the two masks.""" return x | y def _intersection(x: int, y: int) -> int: """Uses bitwise AND to get the intersection of the two masks.""" return x & y def _get_kth_bit(x: int, k: int) -> int: """Returns the kth bit in the mask from the right.""" mask = 1 << k return x & mask def _set_kth_bit(x: int, k: int) -> int: """Sets the kth bit in the mask from the right.""" mask = 1 << k return x | mask def _unset_kth_bit(x: int, k: int) -> int: """Clears the kth bit in the mask from the right.""" mask = ~(1 << k) return x & mask class BitMask: """Utility class to represent and manipulate tags. Attributes: x: An integer representation of the binary mask. Examples: >>> # the following are equivalent >>> mask = BitMask(6) >>> mask = BitMask.from_hex('0x6') >>> mask = Bitmask.from_bin('0b0110') >>> # for a dataset with 10 images, assume the following tag >>> # 0001011001 where the 1st, 4th, 5th and 7th image are selected >>> # this tag would be stored as 0x59. >>> hexstring = '0x59' # what you receive from the api >>> mask = BitMask.from_hex(hexstring) # create a bitmask from it >>> indices = mask.to_indices() # get list of indices which are one >>> # indices is [0, 3, 4, 6] """ def __init__(self, x): self.x = x @classmethod def from_hex(cls, hexstring: str): """Creates a bit mask object from a hexstring.""" return cls(_hex_to_int(hexstring)) @classmethod def from_bin(cls, binstring: str): """Creates a BitMask from a binary string.""" return cls(_bin_to_int(binstring)) @classmethod def from_length(cls, length: int): """Creates a all-true bitmask of a predefined length""" binstring = "0b" + "1" * length return cls.from_bin(binstring) def to_hex(self): """Creates a BitMask from a hex string.""" return _int_to_hex(self.x) def to_bin(self): """Returns a binary string representing the bit mask.""" return _int_to_bin(self.x) def to_indices(self) -> List[int]: """Returns the list of indices bits which are set to 1 from the right. Examples: >>> mask = BitMask('0b0101') >>> indices = mask.to_indices() >>> # indices is [0, 2] """ return _get_nonzero_bits(self.x) def invert(self, total_size: int): """Sets every 0 to 1 and every 1 to 0 in the bitstring. Args: total_size: Total size of the tag. """ self.x = _invert(self.x, total_size) def complement(self): """Same as invert but with the appropriate name.""" self.invert() def union(self, other): """Calculates the union of two bit masks. Examples: >>> mask1 = BitMask.from_bin('0b0011') >>> mask2 = BitMask.from_bin('0b1100') >>> mask1.union(mask2) >>> # mask1.binstring is '0b1111' """ self.x = _union(self.x, other.x) def intersection(self, other): """Calculates the intersection of two bit masks. Examples: >>> mask1 = BitMask.from_bin('0b0011') >>> mask2 = BitMask.from_bin('0b1100') >>> mask1.intersection(mask2) >>> # mask1.binstring is '0b0000' """ self.x = _intersection(self.x, other.x) def difference(self, other): """Calculates the difference of two bit masks. Examples: >>> mask1 = BitMask.from_bin('0b0111') >>> mask2 = BitMask.from_bin('0b1100') >>> mask1.difference(mask2) >>> # mask1.binstring is '0b0011' """ self.union(other) self.x = self.x - other.x def __sub__(self, other): ret = copy.deepcopy(self) ret.difference(other) return ret def __eq__(self, other): return self.to_bin() == other.to_bin() def masked_select_from_list(self, list_: List): """Returns a subset of a list depending on the bitmask. The bitmask is read from right to left, i.e. the least significant bit corresponds to index 0. Examples: >>> list_to_subset = [4, 7, 9, 1] >>> mask = BitMask.from_bin("0b0101") >>> masked_list = mask.masked_select_from_list(list_to_subset) >>> # masked_list = [4, 9] """ indices = self.to_indices() return [list_[index] for index in indices] def get_kth_bit(self, k: int) -> bool: """Returns the boolean value of the kth bit from the right.""" return _get_kth_bit(self.x, k) > 0 def set_kth_bit(self, k: int): """Sets the kth bit from the right to '1'. Examples: >>> mask = BitMask('0b0000') >>> mask.set_kth_bit(2) >>> # mask.binstring is '0b0100' """ self.x = _set_kth_bit(self.x, k) def unset_kth_bit(self, k: int): """Unsets the kth bit from the right to '0'. Examples: >>> mask = BitMask('0b1111') >>> mask.unset_kth_bit(2) >>> # mask.binstring is '0b1011' """ self.x = _unset_kth_bit(self.x, k)
6,793
29.603604
83
py
lightly
lightly-master/lightly/api/download.py
import concurrent.futures import os import pathlib import shutil import threading import warnings from concurrent.futures import ThreadPoolExecutor from typing import Callable, Dict, Iterable, List, Optional, Tuple, Type, Union import PIL import requests import tqdm from lightly.api import utils try: import av except ModuleNotFoundError: av = ModuleNotFoundError( "PyAV is not installed on your system. Please install it to use the video" "functionalities. See https://github.com/mikeboers/PyAV#installation for" "installation instructions." ) DEFAULT_VIDEO_TIMEOUT = 60 * 5 # seconds def _check_av_available() -> None: if isinstance(av, Exception): raise av def download_image( url: str, session: requests.Session = None, retry_fn: Callable = utils.retry, request_kwargs: Optional[Dict] = None, ) -> PIL.Image.Image: """Downloads an image from a url. Args: url: The url where the image is downloaded from. session: Session object to persist certain parameters across requests. retry_fn: Retry function that handles failed downloads. request_kwargs: Additional parameters passed to requests.get(). Returns: The downloaded image. """ request_kwargs = request_kwargs or {} request_kwargs.setdefault("stream", True) request_kwargs.setdefault("timeout", 10) def load_image(url, req, request_kwargs): with req.get(url=url, **request_kwargs) as response: response.raise_for_status() image = PIL.Image.open(response.raw) image.load() return image req = requests if session is None else session image = retry_fn(load_image, url, req, request_kwargs) return image if not isinstance(av, ModuleNotFoundError): def download_all_video_frames( url: str, timestamp: Union[int, None] = None, as_pil_image: int = True, thread_type: av.codec.context.ThreadType = av.codec.context.ThreadType.AUTO, video_channel: int = 0, retry_fn: Callable = utils.retry, timeout: Optional[Union[float, Tuple[float, float]]] = DEFAULT_VIDEO_TIMEOUT, ) -> Iterable[Union[PIL.Image.Image, av.VideoFrame]]: """Lazily retrieves all frames from a video stored at the given url. Args: url: The url where video is downloaded from. timestamp: Timestamp in pts from the start of the video from which the frame download should start. See https://pyav.org/docs/develop/api/time.html#time for details on pts. as_pil_image: Whether to return the frame as PIL.Image. thread_type: Which multithreading method to use for decoding the video. See https://pyav.org/docs/stable/api/codec.html#av.codec.context.ThreadType for details. video_channel: The video channel from which frames are loaded. retry_fn: Retry function that handles errors when opening the video container. timeout: Time in seconds to wait for new video data before giving up. Timeout must either be an (open_timeout, read_timeout) tuple or a single value which will be used as open and read timeout. Timeouts only apply to individual steps during the download, the complete video download can take much longer. See https://pyav.org/docs/stable/api/_globals.html?highlight=av%20open#av.open for details. Returns: A generator that loads and returns a single frame per step. """ _check_av_available() timestamp = 0 if timestamp is None else timestamp if timestamp < 0: raise ValueError(f"Negative timestamp is not allowed: {timestamp}") with retry_fn(av.open, url, timeout=timeout) as container: stream = container.streams.video[video_channel] stream.thread_type = thread_type # seek to last keyframe before the timestamp container.seek(timestamp, any_frame=False, backward=True, stream=stream) frame = None for frame in container.decode(stream): # advance from keyframe until correct timestamp is reached if frame.pts < timestamp: continue # yield next frame if as_pil_image: yield frame.to_image() else: yield frame def download_video_frame( url: str, timestamp: int, *args, **kwargs ) -> Union[PIL.Image.Image, av.VideoFrame, None]: """ Wrapper around download_video_frames_at_timestamps for downloading only a single frame. """ frames = download_video_frames_at_timestamps( url, timestamps=[timestamp], *args, **kwargs ) frames = list(frames) return frames[0] def video_frame_count( url: str, video_channel: int = 0, thread_type: av.codec.context.ThreadType = av.codec.context.ThreadType.AUTO, ignore_metadata: bool = False, retry_fn: Callable = utils.retry, timeout: Optional[Union[float, Tuple[float, float]]] = DEFAULT_VIDEO_TIMEOUT, ) -> Optional[int]: """Returns the number of frames in the video from the given url. The video is only decoded if no information about the number of frames is stored in the video metadata. Args: url: The url of the video. video_channel: The video stream channel from which to find the number of frames. thread_type: Which multithreading method to use for decoding the video. See https://pyav.org/docs/stable/api/codec.html#av.codec.context.ThreadType for details. ignore_metadata: If True, frames are counted by iterating through the video instead of relying on the video metadata. timeout: Time in seconds to wait for new video data before giving up. Timeout must either be an (open_timeout, read_timeout) tuple or a single value which will be used as open and read timeout. Timeouts only apply to individual steps during the download, the complete video download can take much longer. See https://pyav.org/docs/stable/api/_globals.html?highlight=av%20open#av.open for details. Returns: The number of frames in the video. Can be None if the video could not be decoded. """ with retry_fn(av.open, url, timeout=timeout) as container: stream = container.streams.video[video_channel] num_frames = 0 if ignore_metadata else stream.frames # If number of frames not stored in the video file we have to decode all # frames and count them. if num_frames == 0: stream.thread_type = thread_type for _ in container.decode(stream): num_frames += 1 return num_frames def all_video_frame_counts( urls: List[str], max_workers: int = None, video_channel: int = 0, thread_type: av.codec.context.ThreadType = av.codec.context.ThreadType.AUTO, ignore_metadata: bool = False, retry_fn: Callable = utils.retry, exceptions_indicating_empty_video: Tuple[Type[BaseException], ...] = ( RuntimeError, ), progress_bar: Optional[tqdm.tqdm] = None, ) -> List[Optional[int]]: """Finds the number of frames in the videos at the given urls. Videos are only decoded if no information about the number of frames is stored in the video metadata. Args: urls: A list of video urls. max_workers: Maximum number of workers. If `None` the number of workers is chosen based on the number of available cores. video_channel: The video stream channel from which to find the number of frames. thread_type: Which multithreading method to use for decoding the video. See https://pyav.org/docs/stable/api/codec.html#av.codec.context.ThreadType for details. ignore_metadata: If True, frames are counted by iterating through the video instead of relying on the video metadata. retry_fn: Retry function that handles errors when loading a video. exceptions_indicating_empty_video: If an exception in exceptions_indicating_empty_video is raised, the video is considered as empty and None is returned as number of frames for the video. Returns: A list with the number of frames per video. Contains None for all videos that could not be decoded. """ def job(url): try: return retry_fn( video_frame_count, url=url, video_channel=video_channel, thread_type=thread_type, ignore_metadata=ignore_metadata, retry_fn=retry_fn, ) except exceptions_indicating_empty_video: return with ThreadPoolExecutor(max_workers=max_workers) as executor: frame_counts = [] total_count = 0 for count in executor.map(job, urls): frame_counts.append(count) if progress_bar is not None: if count is not None: total_count += count progress_bar.update(1) progress_bar.set_description(f"Total frames found: {total_count}") return frame_counts def download_video_frames_at_timestamps( url: str, timestamps: List[int], as_pil_image: int = True, thread_type: av.codec.context.ThreadType = av.codec.context.ThreadType.AUTO, video_channel: int = 0, seek_to_first_frame: bool = True, retry_fn: Callable = utils.retry, timeout: Optional[Union[float, Tuple[float, float]]] = DEFAULT_VIDEO_TIMEOUT, ) -> Iterable[Union[PIL.Image.Image, av.VideoFrame]]: """Lazily retrieves frames from a video at a specific timestamp stored at the given url. Args: url: The url where video is downloaded from. timestamps: Timestamps in pts from the start of the video. The images at these timestamps are returned. The timestamps must be strictly monotonically ascending. See https://pyav.org/docs/develop/api/time.html#time for details on pts. as_pil_image: Whether to return the frame as PIL.Image. thread_type: Which multithreading method to use for decoding the video. See https://pyav.org/docs/stable/api/codec.html#av.codec.context.ThreadType for details. video_channel: The video channel from which frames are loaded. seek_to_first_frame: Boolean indicating whether to seek to the first frame. retry_fn: Retry function that handles errors when opening the video container. timeout: Time in seconds to wait for new video data before giving up. Timeout must either be an (open_timeout, read_timeout) tuple or a single value which will be used as open and read timeout. Timeouts only apply to individual steps during the download, the complete video download can take much longer. See https://pyav.org/docs/stable/api/_globals.html?highlight=av%20open#av.open for details. Returns: A generator that loads and returns a single frame per step. """ _check_av_available() if len(timestamps) == 0: return [] if any(timestamps[i + 1] <= timestamps[i] for i in range(len(timestamps) - 1)): raise ValueError( "The timestamps must be sorted " "strictly monotonically ascending, but are not." ) min_timestamp = timestamps[0] if min_timestamp < 0: raise ValueError(f"Negative timestamp is not allowed: {min_timestamp}") with retry_fn(av.open, url, timeout=timeout) as container: stream = container.streams.video[video_channel] stream.thread_type = thread_type if seek_to_first_frame: # seek to last keyframe before the min_timestamp container.seek( min_timestamp, any_frame=False, backward=True, stream=stream ) index_timestamp = 0 for frame in container.decode(stream): # advance from keyframe until correct timestamp is reached if frame.pts > timestamps[index_timestamp]: # dropped frames! break # it's ok to check by equality because timestamps are ints if frame.pts == timestamps[index_timestamp]: # yield next frame if as_pil_image: yield frame.to_image() else: yield frame # update the timestamp index_timestamp += 1 if index_timestamp >= len(timestamps): return leftovers = timestamps[index_timestamp:] # sometimes frames are skipped when we seek to the first frame # let's retry downloading these frames without seeking retry_skipped_timestamps = seek_to_first_frame if retry_skipped_timestamps: warnings.warn( f"Timestamps {leftovers} could not be decoded! Retrying from the start..." ) frames = download_video_frames_at_timestamps( url, leftovers, as_pil_image=as_pil_image, thread_type=thread_type, video_channel=video_channel, seek_to_first_frame=False, retry_fn=retry_fn, ) for frame in frames: yield frame return raise RuntimeError( f"Timestamps {leftovers} in video {url} could not be decoded!" ) def download_and_write_file( url: str, output_path: str, session: requests.Session = None, retry_fn: Callable = utils.retry, request_kwargs: Optional[Dict] = None, ) -> None: """Downloads a file from a url and saves it to disk Args: url: Url of the file to download. output_path: Where to store the file, including filename and extension. session: Session object to persist certain parameters across requests. retry_fn: Retry function that handles failed downloads. request_kwargs: Additional parameters passed to requests.get(). """ request_kwargs = request_kwargs or {} request_kwargs.setdefault("stream", True) request_kwargs.setdefault("timeout", 10) req = requests if session is None else session out_path = pathlib.Path(output_path) out_path.parent.mkdir(parents=True, exist_ok=True) with retry_fn(req.get, url=url, **request_kwargs) as response: response.raise_for_status() with open(out_path, "wb") as file: shutil.copyfileobj(response.raw, file) def download_and_write_all_files( file_infos: List[Tuple[str, str]], output_dir: str, max_workers: int = None, verbose: bool = False, retry_fn: Callable = utils.retry, request_kwargs: Optional[Dict] = None, ) -> None: """Downloads all files and writes them to disk. Args: file_infos: List containing (filename, url) tuples. output_dir: Output directory where files will stored in. max_workers: Maximum number of workers. If `None` the number of workers is chosen based on the number of available cores. verbose: Shows progress bar if set to `True`. retry_fn: Retry function that handles failed downloads. request_kwargs: Additional parameters passed to requests.get(). """ def thread_download_and_write( file_info: Tuple[str, str], output_dir: str, lock: threading.Lock, sessions: Dict[str, requests.Session], **kwargs, ): filename, url = file_info output_path = os.path.join(output_dir, filename) thread_id = threading.get_ident() lock.acquire() session = sessions.get(thread_id) if session is None: session = requests.Session() sessions[thread_id] = session lock.release() download_and_write_file(url, output_path, session, **kwargs) # retry download if failed def job(**kwargs): retry_fn(thread_download_and_write, **kwargs) # dict where every thread stores its requests.Session sessions = dict() # use lock because sessions dict is shared between threads lock = threading.Lock() with ThreadPoolExecutor(max_workers=max_workers) as executor: futures_to_file_info = { executor.submit( job, file_info=file_info, output_dir=output_dir, lock=lock, sessions=sessions, retry_fn=retry_fn, request_kwargs=request_kwargs, ): file_info for file_info in file_infos } futures = concurrent.futures.as_completed(futures_to_file_info) if verbose: futures = tqdm.tqdm(futures) for future in futures: filename, url = futures_to_file_info[future] try: future.result() except Exception as ex: warnings.warn(f"Could not download {filename} from {url}") def download_prediction_file( url: str, session: requests.Session = None, request_kwargs: Optional[Dict] = None, ) -> Dict: """Same as download_json_file. Keep this for backwards compatability. See download_json_file. """ return download_json_file(url, session=session, request_kwargs=request_kwargs) def download_json_file( url: str, session: requests.Session = None, request_kwargs: Optional[Dict] = None, ) -> Dict: """Downloads a json file from the provided read-url. Args: url: Url of the file to download. session: Session object to persist certain parameters across requests. request_kwargs: Additional parameters passed to requests.get(). Returns the content of the json file as dictionary. Raises HTTPError in case of an error. """ request_kwargs = request_kwargs or {} request_kwargs.setdefault("stream", True) request_kwargs.setdefault("timeout", 10) req = requests if session is None else session response = req.get(url, **request_kwargs) response.raise_for_status() return response.json()
19,950
35.742173
96
py
lightly
lightly-master/lightly/api/patch.py
import logging from typing import Any, Dict, Type def make_swagger_configuration_picklable( configuration_cls: Type, ) -> None: """Adds __getstate__ and __setstate__ methods to swagger configuration to make it picklable. This doesn't make all swagger classes picklable. Notably, the ApiClient and and RESTClientObject classes are not picklable. Use the picklable LightlySwaggerApiClient and LightlySwaggerRESTClientObject classes instead. """ configuration_cls.__getstate__ = _Configuration__getstate__ configuration_cls.__setstate__ = _Configuration__setstate__ def _Configuration__getstate__(self: Type) -> Dict[str, Any]: state = self.__dict__.copy() # Remove all loggers as they are not picklable. This removes the package_logger # and urllib3_logger. Note that we cannot remove the with: # `del state["logger"]["package_logger"]` as this would modify self.__dict__ due to # shallow copy. state["logger"] = {} # formatter, stream_handler and file_handler are not picklable state["logger_formatter"] = None state["logger_stream_handler"] = None state["logger_file_handler"] = None return state def _Configuration__setstate__(self: Type, state: Dict[str, Any]) -> None: self.__dict__.update(state) # Recreate logger objects. self.logger["package_logger"] = logging.getLogger( "lightly.openapi_generated.swagger_client" ) self.logger["urllib3_logger"] = logging.getLogger("urllib3") # Set logger_format and logger_file explicitly because they have setter decoraters # defined on the Configuration class. These decorates have side effects and create # self.__logger_format, self.logger_formatter, self.__logger_file, # self.logger_file_handler, and self.logger_stream_handler under the hood. # # Note that the setter decorates are not called by the self.__dict__.update(state) # at the beginning of the function. # # The attributes are set to the class mangled values stored in the state dict. self.logger_format = state[ "_Configuration__logger_format" ] # set to self.__logger_format self.logger_file = state["_Configuration__logger_file"] # set to self.__logger_file # Set debug explicitly because it has a setter decorator with side effects. self.debug = state["_Configuration__debug"]
2,375
39.271186
88
py
lightly
lightly-master/lightly/api/swagger_api_client.py
from typing import Any, Dict, Tuple, Union from lightly.api.swagger_rest_client import LightlySwaggerRESTClientObject from lightly.openapi_generated.swagger_client.api_client import ApiClient, Configuration DEFAULT_API_TIMEOUT = 60 * 3 # seconds class PatchApiClientMixin: """Mixin that makes an ApiClient object picklable.""" def __getstate__(self) -> Dict[str, Any]: state = self.__dict__.copy() # Set _pool to None as ThreadPool is not picklable. It will be automatically # recreated once the pool is accessed after unpickling. state["_pool"] = None # Urllib3 response is not picklable. We can safely remove this as it only # serves as a cache. if "last_response" in state: del state["last_response"] return state class LightlySwaggerApiClient(PatchApiClientMixin, ApiClient): """Subclass of ApiClient with patches to make the client picklable. Uses a LightlySwaggerRESTClientObject instead of RESTClientObject for additional patches. See LightlySwaggerRESTClientObject for details. Attributes: configuration: Configuration. timeout: Timeout in seconds. Is either a single total_timeout value or a (connect_timeout, read_timeout) tuple. No timeout is applied if the value is None. See https://urllib3.readthedocs.io/en/stable/reference/urllib3.util.html?highlight=timeout#urllib3.util.Timeout for details on the different values. header_name: A header to pass when making calls to the API. header_value: A header value to pass when making calls to the API. cookie: A cookie to include in the header when making calls to the API. """ def __init__( self, configuration: Configuration, timeout: Union[None, int, Tuple[int, int]] = DEFAULT_API_TIMEOUT, header_name: Union[str, None] = None, header_value: Union[str, None] = None, cookie: Union[str, None] = None, ): super().__init__( configuration=configuration, header_name=header_name, header_value=header_value, cookie=cookie, ) self.rest_client = LightlySwaggerRESTClientObject( configuration=configuration, timeout=timeout )
2,391
35.8
123
py
lightly
lightly-master/lightly/api/swagger_rest_client.py
from typing import Any, Dict, Tuple, Union from lightly.openapi_generated.swagger_client.api_client import Configuration from lightly.openapi_generated.swagger_client.rest import RESTClientObject class PatchRESTClientObjectMixin: """Mixin that adds patches to a RESTClientObject. * Adds default timeout to all requests * Encodes list query parameters properly * Makes the client picklable Should only used in combination with RESTClientObject and must come before the RESTClientObject in the inheritance order. So this is ok: >>> class MyRESTClientObject(PatchRESTClientObjectMixin, RESTClientObject): pass while this doesn't work: >>> class MyRESTClientObject(RESTClientObject, PatchRESTClientObjectMixin): pass A wrong inheritance order will result in the super() calls no calling the correct parent classes. """ def __init__( self, configuration: Configuration, timeout: Union[None, int, Tuple[int, int]], pools_size: int = 4, maxsize: Union[None, int] = None, ): # Save args as attributes to make the class picklable. self.configuration = configuration self.timeout = timeout self.pools_size = pools_size self.maxsize = maxsize # Initialize RESTClientObject class super().__init__( configuration=configuration, pools_size=pools_size, maxsize=maxsize ) def request( self, method, url, query_params=None, headers=None, body=None, post_params=None, _preload_content=True, _request_timeout=None, ): # Set default timeout. This is necessary because the openapi client does not # respect timeouts configured by urllib3. Instead it expects a timeout to be # passed with every request. See code here: # https://github.com/lightly-ai/lightly/blob/ffbd32fe82f76b37c8ac497640355314474bfc3b/lightly/openapi_generated/swagger_client/rest.py#L141-L148 if _request_timeout is None: _request_timeout = self.timeout # Call RESTClientObject.request return super().request( method=method, url=url, query_params=query_params, headers=headers, body=body, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, ) def __getstate__(self) -> Dict[str, Any]: """__getstate__ method for pickling.""" state = self.__dict__.copy() # Delete pool_manager as it cannot be pickled. Note that it is not possible to # unpickle and use a LightlySwaggerRESTClientObject without either instantiating # the pool_manager manually again or calling the init method on the rest client. del state["pool_manager"] return state def __setstate__(self, state: Dict[str, Any]) -> None: """__setstate__ method for pickling.""" self.__dict__.update(state) # Calling init to recreate the pool_manager attribute. self.__init__( configuration=state["configuration"], timeout=state["timeout"], pools_size=state["pools_size"], maxsize=state["maxsize"], ) class LightlySwaggerRESTClientObject(PatchRESTClientObjectMixin, RESTClientObject): """Subclass of RESTClientObject which contains additional patches for the request method and making the client picklable. See PatchRESTClientObjectMixin for details. Attributes: configuration: Configuration. timeout: Timeout in seconds. Is either a single total_timeout value or a (connect_timeout, read_timeout) tuple. No timeout is applied if the value is None. See https://urllib3.readthedocs.io/en/stable/reference/urllib3.util.html?highlight=timeout#urllib3.util.Timeout for details on the different values. pools_size: Number of connection pools. Defaults to 4. maxsize: Maxsize is the number of requests to host that are allowed in parallel. Defaults to None. """ pass
4,271
34.89916
152
py
lightly
lightly-master/lightly/api/utils.py
""" Communication Utility """ # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved import io import os import random import threading import time from enum import Enum from typing import Iterator, List, Optional # the following two lines are needed because # PIL misidentifies certain jpeg images as MPOs from PIL import JpegImagePlugin JpegImagePlugin._getmp = lambda: None from lightly.openapi_generated.swagger_client.configuration import Configuration MAXIMUM_FILENAME_LENGTH = 255 RETRY_MAX_BACKOFF = 32 RETRY_MAX_RETRIES = 5 def retry(func, *args, **kwargs): """Repeats a function until it completes successfully or fails too often. Args: func: The function call to repeat. args: The arguments which are passed to the function. kwargs: Key-word arguments which are passed to the function. Returns: What func returns. Exceptions: RuntimeError when number of retries has been exceeded. """ # config backoff = 1.0 + random.random() * 0.1 max_backoff = RETRY_MAX_BACKOFF max_retries = RETRY_MAX_RETRIES # try to make the request current_retries = 0 while True: try: # return on success return func(*args, **kwargs) except Exception as e: # sleep on failure time.sleep(backoff) backoff = 2 * backoff if backoff < max_backoff else backoff current_retries += 1 # max retries exceeded if current_retries >= max_retries: raise RuntimeError( f"Maximum retries exceeded! Original exception: {type(e)}: {str(e)}" ) from e class Paginated(Iterator): def __init__(self, fn, page_size, *args, **kwargs): self.entries: List = [] self.last_chunk_size = page_size self.offset = 0 self.fn = fn self.page_size = page_size self.args = args self.kwargs = kwargs def __iter__(self): return self def __next__(self): if len(self.entries) == 0: # stop iteration if the last chunk was smaller than the page size if self.last_chunk_size < self.page_size: raise StopIteration chunk = retry( self.fn, page_offset=self.offset * self.page_size, page_size=self.page_size, *self.args, **self.kwargs, ) if len(chunk) == 0: raise StopIteration self.offset += 1 self.last_chunk_size = len(chunk) # Handle the case where the chunk is a string. In this case we want # to return the whole page as a single string instead of an interable # of characters. chunk = chunk if not isinstance(chunk, str) else [chunk] self.entries.extend(chunk) return self.entries.pop(0) def paginate_endpoint(fn, page_size=5000, *args, **kwargs) -> Iterator: """Paginates an API endpoint Args: fn: The endpoint which will be paginated until there is not any more data page_size: The size of the pages to pull """ return Paginated(fn, page_size, *args, **kwargs) def getenv(key: str, default: str): """Return the value of the environment variable key if it exists, or default if it doesn’t. """ try: return os.getenvb(key.encode(), default.encode()).decode() except Exception: pass try: return os.getenv(key, default) except Exception: pass return default def PIL_to_bytes(img, ext: str = "png", quality: int = None): """Return the PIL image as byte stream. Useful to send image via requests.""" bytes_io = io.BytesIO() if quality is not None: img.save(bytes_io, format=ext, quality=quality) else: subsampling = -1 if ext.lower() in ["jpg", "jpeg"] else 0 img.save(bytes_io, format=ext, quality=100, subsampling=subsampling) bytes_io.seek(0) return bytes_io def check_filename(basename): """Checks the length of the filename. Args: basename: Basename of the file. """ return len(basename) <= MAXIMUM_FILENAME_LENGTH def build_azure_signed_url_write_headers( content_length: str, x_ms_blob_type: str = "BlockBlob", accept: str = "*/*", accept_encoding: str = "*", ): """Builds the headers required for a SAS PUT to Azure blob storage. Args: content_length: Length of the content in bytes as string. x_ms_blob_type: Blob type (one of BlockBlob, PageBlob, AppendBlob) accept: Indicates which content types the client is able to understand. accept_encoding: Indicates the content encoding that the client can understand. Returns: Formatted header which should be passed to the PUT request. """ headers = { "x-ms-blob-type": x_ms_blob_type, "Accept": accept, "Content-Length": content_length, "x-ms-original-content-length": content_length, "Accept-Encoding": accept_encoding, } return headers class DatasourceType(Enum): S3 = "S3" GCS = "GCS" AZURE = "AZURE" LOCAL = "LOCAL" def get_signed_url_destination(signed_url: str = "") -> DatasourceType: """ Tries to figure out the of which cloud provider/datasource type a signed url comes from (S3, GCS, Azure) Args: signed_url: The signed url of a "bucket" provider Returns: DatasourceType """ assert isinstance(signed_url, str) if "storage.googleapis.com/" in signed_url: return DatasourceType.GCS if ".amazonaws.com/" in signed_url and ".s3." in signed_url: return DatasourceType.S3 if ".windows.net/" in signed_url: return DatasourceType.AZURE # default to local as it must be some special setup return DatasourceType.LOCAL def get_lightly_server_location_from_env() -> str: return ( getenv("LIGHTLY_SERVER_LOCATION", "https://api.lightly.ai").strip().rstrip("/") ) def get_api_client_configuration( token: Optional[str] = None, raise_if_no_token_specified: bool = True, ) -> Configuration: host = get_lightly_server_location_from_env() ssl_ca_cert = getenv("LIGHTLY_CA_CERTS", None) if token is None: token = getenv("LIGHTLY_TOKEN", None) if token is None and raise_if_no_token_specified: raise ValueError( "Either provide a 'token' argument or export a LIGHTLY_TOKEN environment variable" ) configuration = Configuration() configuration.api_key = {"ApiKeyAuth": token} configuration.ssl_ca_cert = ssl_ca_cert configuration.host = host return configuration
6,937
27.318367
108
py
lightly
lightly-master/lightly/api/version_checking.py
import signal import warnings from typing import Tuple from lightly.api import utils from lightly.api.swagger_api_client import LightlySwaggerApiClient from lightly.openapi_generated.swagger_client.api import VersioningApi from lightly.utils import version_compare class LightlyAPITimeoutException(Exception): pass class TimeoutDecorator: def __init__(self, seconds): self.seconds = seconds def handle_timeout_method(self, *args, **kwargs): raise LightlyAPITimeoutException def __enter__(self): signal.signal(signal.SIGALRM, self.handle_timeout_method) signal.alarm(self.seconds) def __exit__(self, exc_type, exc_val, exc_tb): signal.alarm(0) def is_latest_version(current_version: str) -> bool: with TimeoutDecorator(1): versioning_api = get_versioning_api() latest_version: str = versioning_api.get_latest_pip_version( current_version=current_version ) return version_compare.version_compare(current_version, latest_version) >= 0 def is_compatible_version(current_version: str) -> bool: with TimeoutDecorator(1): versioning_api = get_versioning_api() minimum_version: str = versioning_api.get_minimum_compatible_pip_version() return version_compare.version_compare(current_version, minimum_version) >= 0 def get_versioning_api() -> VersioningApi: configuration = utils.get_api_client_configuration( raise_if_no_token_specified=False, ) api_client = LightlySwaggerApiClient(configuration=configuration) versioning_api = VersioningApi(api_client=api_client) return versioning_api def get_latest_version(current_version: str) -> Tuple[None, str]: try: versioning_api = get_versioning_api() version_number: str = versioning_api.get_latest_pip_version( current_version=current_version ) return version_number except Exception as e: return None def get_minimum_compatible_version(): versioning_api = get_versioning_api() version_number: str = versioning_api.get_minimum_compatible_pip_version() return version_number def pretty_print_latest_version(current_version, latest_version, width=70): warning = ( f"You are using lightly version {current_version}. " f"There is a newer version of the package available. " f"For compatability reasons, please upgrade your current version: " f"pip install lightly=={latest_version}" ) warnings.warn(Warning(warning))
2,544
30.8125
82
py
lightly
lightly-master/lightly/cli/__init__.py
""" The lightly.cli module provides a console interface for training self-supervised models, embedding, and filtering datasets """ # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved from lightly.cli.crop_cli import crop_cli from lightly.cli.download_cli import download_cli from lightly.cli.embed_cli import embed_cli from lightly.cli.lightly_cli import lightly_cli from lightly.cli.train_cli import train_cli
444
30.785714
55
py
lightly
lightly-master/lightly/cli/_cli_simclr.py
""" SimCLR Model """ # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved import warnings import torch import torch.nn as nn from lightly.models.modules import SimCLRProjectionHead class _SimCLR(nn.Module): """Implementation of SimCLR used by the command-line interface. Provides backwards compatability with old checkpoints. """ def __init__(self, backbone: nn.Module, num_ftrs: int = 32, out_dim: int = 128): super(_SimCLR, self).__init__() self.backbone = backbone self.projection_head = SimCLRProjectionHead( num_ftrs, num_ftrs, out_dim, batch_norm=False ) def forward(self, x0: torch.Tensor, x1: torch.Tensor = None): """Embeds and projects the input images.""" # forward pass of first input x0 f0 = self.backbone(x0).flatten(start_dim=1) out0 = self.projection_head(f0) # return out0 if x1 is None if x1 is None: return out0 # forward pass of second input x1 f1 = self.backbone(x1).flatten(start_dim=1) out1 = self.projection_head(f1) # return both outputs return out0, out1
1,181
25.266667
84
py
lightly
lightly-master/lightly/cli/_helpers.py
""" Command-Line Interface Helpers """ # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved import os import hydra import torch from hydra import utils from torch import nn as nn from lightly.cli._cli_simclr import _SimCLR from lightly.embedding import SelfSupervisedEmbedding from lightly.models import ZOO as model_zoo from lightly.models import ResNetGenerator from lightly.models.batchnorm import get_norm_layer from lightly.utils.version_compare import version_compare def cpu_count(): """Returns the number of CPUs which are present in the system. This number is not equivalent to the number of available CPUs to the process. """ return os.cpu_count() def fix_input_path(path): """Fix broken relative paths.""" if not os.path.isabs(path): path = utils.to_absolute_path(path) return path def fix_hydra_arguments(config_path: str = "config", config_name: str = "config"): """Helper to make hydra arugments adaptive to installed hydra version Hydra introduced the `version_base` argument in version 1.2.0 We use this helper to provide backwards compatibility to older hydra verisons. """ hydra_args = {"config_path": config_path, "config_name": config_name} try: if version_compare(hydra.__version__, "1.1.2") > 0: hydra_args["version_base"] = "1.1" except ValueError: pass return hydra_args def is_url(checkpoint): """Check whether the checkpoint is a url or not.""" is_url = "https://storage.googleapis.com" in checkpoint return is_url def get_ptmodel_from_config(model): """Get a pre-trained model from the lightly model zoo.""" key = model["name"] key += "/simclr" key += "/d" + str(model["num_ftrs"]) key += "/w" + str(float(model["width"])) if key in model_zoo.keys(): return model_zoo[key], key else: return "", key def load_state_dict_from_url(url, map_location=None): """Try to load the checkopint from the given url.""" try: state_dict = torch.hub.load_state_dict_from_url(url, map_location=map_location) return state_dict except Exception: print("Not able to load state dict from %s" % (url)) print("Retrying with http:// prefix") try: url = url.replace("https", "http") state_dict = torch.hub.load_state_dict_from_url(url, map_location=map_location) return state_dict except Exception: print("Not able to load state dict from %s" % (url)) # in this case downloading the pre-trained model was not possible # notify the user and return return {"state_dict": None} def _maybe_expand_batchnorm_weights(model_dict, state_dict, num_splits): """Expands the weights of the BatchNorm2d to the size of SplitBatchNorm.""" running_mean = "running_mean" running_var = "running_var" for key, item in model_dict.items(): # not batchnorm -> continue if not running_mean in key and not running_var in key: continue state = state_dict.get(key, None) # not in dict -> continue if state is None: continue # same shape -> continue if item.shape == state.shape: continue # found running mean or running var with different shapes state_dict[key] = state.repeat(num_splits) return state_dict def _filter_state_dict(state_dict, remove_model_prefix_offset: int = 1): """Makes the state_dict compatible with the model. Prevents unexpected key error when loading PyTorch-Lightning checkpoints. Allows backwards compatability to checkpoints before v1.0.6. """ prev_backbone = "features" curr_backbone = "backbone" new_state_dict = {} for key, item in state_dict.items(): # remove the "model." prefix from the state dict key key_parts = key.split(".")[remove_model_prefix_offset:] # with v1.0.6 the backbone of the models will be renamed from # "features" to "backbone", ensure compatability with old ckpts key_parts = [k if k != prev_backbone else curr_backbone for k in key_parts] new_key = ".".join(key_parts) new_state_dict[new_key] = item return new_state_dict def _fix_projection_head_keys(state_dict): """Makes the state_dict compatible with the refactored projection heads. TODO: Remove once the models are refactored and the old checkpoints were replaced! Relevant issue: https://github.com/lightly-ai/lightly/issues/379 Prevents unexpected key error when loading old checkpoints. """ projection_head_identifier = "projection_head" prediction_head_identifier = "prediction_head" projection_head_insert = "layers" new_state_dict = {} for key, item in state_dict.items(): if ( projection_head_identifier in key or prediction_head_identifier in key ) and projection_head_insert not in key: # insert layers if it's not part of the key yet key_parts = key.split(".") key_parts.insert(1, projection_head_insert) new_key = ".".join(key_parts) else: new_key = key new_state_dict[new_key] = item return new_state_dict def load_from_state_dict( model, state_dict, strict: bool = True, apply_filter: bool = True, num_splits: int = 0, ): """Loads the model weights from the state dictionary.""" # step 1: filter state dict if apply_filter: state_dict = _filter_state_dict(state_dict) state_dict = _fix_projection_head_keys(state_dict) # step 2: expand batchnorm weights state_dict = _maybe_expand_batchnorm_weights( model.state_dict(), state_dict, num_splits ) # step 3: load from checkpoint model.load_state_dict(state_dict, strict=strict) def get_model_from_config(cfg, is_cli_call: bool = False) -> SelfSupervisedEmbedding: checkpoint = cfg["checkpoint"] if torch.cuda.is_available(): device = torch.device("cuda") else: device = torch.device("cpu") if not checkpoint: checkpoint, key = get_ptmodel_from_config(cfg["model"]) if not checkpoint: msg = "Cannot download checkpoint for key {} ".format(key) msg += "because it does not exist!" raise RuntimeError(msg) state_dict = load_state_dict_from_url(checkpoint, map_location=device)[ "state_dict" ] else: checkpoint = fix_input_path(checkpoint) if is_cli_call else checkpoint state_dict = torch.load(checkpoint, map_location=device)["state_dict"] # load model resnet = ResNetGenerator(cfg["model"]["name"], cfg["model"]["width"]) last_conv_channels = list(resnet.children())[-1].in_features features = nn.Sequential( get_norm_layer(3, 0), *list(resnet.children())[:-1], nn.Conv2d(last_conv_channels, cfg["model"]["num_ftrs"], 1), nn.AdaptiveAvgPool2d(1), ) model = _SimCLR( features, num_ftrs=cfg["model"]["num_ftrs"], out_dim=cfg["model"]["out_dim"] ).to(device) if state_dict is not None: load_from_state_dict(model, state_dict) encoder = SelfSupervisedEmbedding(model, None, None, None) return encoder
7,330
30.063559
87
py
lightly
lightly-master/lightly/cli/crop_cli.py
# -*- coding: utf-8 -*- """**Lightly Train:** Train a self-supervised model from the command-line. This module contains the entrypoint for the **lightly-train** command-line interface. """ # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved import os.path from typing import List import hydra import yaml from lightly.cli._helpers import fix_hydra_arguments, fix_input_path from lightly.data import LightlyDataset from lightly.utils.bounding_box import BoundingBox from lightly.utils.cropping.crop_image_by_bounding_boxes import ( crop_dataset_by_bounding_boxes_and_save, ) from lightly.utils.cropping.read_yolo_label_file import read_yolo_label_file from lightly.utils.hipify import bcolors def _crop_cli(cfg, is_cli_call=True): input_dir = cfg["input_dir"] if input_dir and is_cli_call: input_dir = fix_input_path(input_dir) output_dir = cfg["output_dir"] if output_dir and is_cli_call: output_dir = fix_input_path(output_dir) label_dir = cfg["label_dir"] if label_dir and is_cli_call: label_dir = fix_input_path(label_dir) label_names_file = cfg["label_names_file"] if label_names_file and len(label_names_file) > 0: if is_cli_call: label_names_file = fix_input_path(label_names_file) with open(label_names_file, "r") as file: label_names_file_dict = yaml.full_load(file) class_names = label_names_file_dict["names"] else: class_names = None dataset = LightlyDataset(input_dir) class_indices_list_list: List[List[int]] = [] bounding_boxes_list_list: List[List[BoundingBox]] = [] # YOLO-Specific for filename_image in dataset.get_filenames(): filepath_image_base, image_extension = os.path.splitext(filename_image) filepath_label = os.path.join(label_dir, filename_image).replace( image_extension, ".txt" ) class_indices, bounding_boxes = read_yolo_label_file( filepath_label, float(cfg["crop_padding"]) ) class_indices_list_list.append(class_indices) bounding_boxes_list_list.append(bounding_boxes) cropped_images_list_list = crop_dataset_by_bounding_boxes_and_save( dataset, output_dir, bounding_boxes_list_list, class_indices_list_list, class_names, ) print(f"Cropped images are stored at: {bcolors.OKBLUE}{output_dir}{bcolors.ENDC}") return cropped_images_list_list @hydra.main(**fix_hydra_arguments(config_path="config", config_name="config")) def crop_cli(cfg): """Crops images into one sub-image for each object. Args: cfg: The default configs are loaded from the config file. To overwrite them please see the section on the config file (.config.config.yaml). Command-Line Args: input_dir: Path to the input directory where images are stored. labels_dir: Path to the directory where the labels are stored. There must be one label file for each image. The label file must have the same name as the image file, but the extension .txt. For example, img_123.txt for img_123.jpg. The label file must be in YOLO format. output_dir: Path to the directory where the cropped images are stored. They are stored in one directory per input image. crop_padding: Optional The additonal padding about the bounding box. This makes the crops include the context of the object. The padding is relative and added to the width and height. label_names_file: Optional A yaml file including the names of the classes. If it is given, the filenames of the cropped images include the class names instead of the class id. This file is usually included when having a dataset in yolo format. Example contents of such a label_names_file.yaml: "names: ['class_name_a', 'class_name_b']" Examples: >>> # Crop images and set the crop to be 20% around the bounding box >>> lightly-crop input_dir=data/images label_dir=data/labels output_dir=data/cropped_images crop_padding=0.2 >>> # Crop images and use the class names in the filename >>> lightly-crop input_dir=data/images label_dir=data/labels output_dir=data/cropped_images label_names_file=data/data.yaml """ return _crop_cli(cfg) def entry(): crop_cli()
4,468
37.525862
131
py
lightly
lightly-master/lightly/cli/download_cli.py
# -*- coding: utf-8 -*- """**Lightly Download:** Download images from the Lightly platform. This module contains the entrypoint for the **lightly-download** command-line interface. """ # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved import os import hydra import lightly.data as data from lightly.api.api_workflow_client import ApiWorkflowClient from lightly.cli._helpers import cpu_count, fix_hydra_arguments, fix_input_path from lightly.openapi_generated.swagger_client.models import Creator from lightly.utils.hipify import bcolors, print_as_warning def _download_cli(cfg, is_cli_call=True): tag_name = str(cfg["tag_name"]) dataset_id = str(cfg["dataset_id"]) token = str(cfg["token"]) if not tag_name or not token or not dataset_id: print_as_warning( "Please specify all of the parameters tag_name, token and dataset_id" ) print_as_warning("For help, try: lightly-download --help") return # set the number of workers if unset if cfg["loader"]["num_workers"] < 0: # set the number of workers to the number of CPUs available, # but minimum of 8 num_workers = max(8, cpu_count()) num_workers = min(32, num_workers) cfg["loader"]["num_workers"] = num_workers api_workflow_client = ApiWorkflowClient( token=token, dataset_id=dataset_id, creator=Creator.USER_PIP_LIGHTLY_MAGIC ) # get tag id tag_data = api_workflow_client.get_tag_by_name(tag_name) filenames_tag = api_workflow_client.get_filenames_in_tag( tag_data, exclude_parent_tag=cfg["exclude_parent_tag"], ) # store sample names in a .txt file filename = tag_name + ".txt" with open(filename, "w") as f: for item in filenames_tag: f.write("%s\n" % item) filepath = os.path.join(os.getcwd(), filename) msg = f'The list of samples in tag {cfg["tag_name"]} is stored at: {bcolors.OKBLUE}{filepath}{bcolors.ENDC}' print(msg, flush=True) if not cfg["input_dir"] and cfg["output_dir"]: # download full images from api output_dir = fix_input_path(cfg["output_dir"]) api_workflow_client.download_dataset( output_dir, tag_name=tag_name, max_workers=cfg["loader"]["num_workers"] ) elif cfg["input_dir"] and cfg["output_dir"]: input_dir = fix_input_path(cfg["input_dir"]) output_dir = fix_input_path(cfg["output_dir"]) print( f"Copying files from {input_dir} to {bcolors.OKBLUE}{output_dir}{bcolors.ENDC}." ) # create a dataset from the input directory dataset = data.LightlyDataset(input_dir=input_dir) # dump the dataset in the output directory dataset.dump(output_dir, filenames_tag) @hydra.main(**fix_hydra_arguments(config_path="config", config_name="config")) def download_cli(cfg): """Download images from the Lightly platform. Args: cfg: The default configs are loaded from the config file. To overwrite them please see the section on the config file (.config.config.yaml). Command-Line Args: tag_name: Download all images from the requested tag. Use initial-tag to get all images from the dataset. token: User access token to the Lightly platform. If dataset_id and token are specified, the images and embeddings are uploaded to the platform. dataset_id: Identifier of the dataset on the Lightly platform. If dataset_id and token are specified, the images and embeddings are uploaded to the platform. input_dir: If input_dir and output_dir are specified, lightly will copy all images belonging to the tag from the input_dir to the output_dir. output_dir: If input_dir and output_dir are specified, lightly will copy all images belonging to the tag from the input_dir to the output_dir. Examples: >>> # download list of all files in the dataset from the Lightly platform >>> lightly-download token='123' dataset_id='XYZ' >>> >>> # download list of all files in tag 'my-tag' from the Lightly platform >>> lightly-download token='123' dataset_id='XYZ' tag_name='my-tag' >>> >>> # download all images in tag 'my-tag' from the Lightly platform >>> lightly-download token='123' dataset_id='XYZ' tag_name='my-tag' output_dir='my_data/' >>> >>> # copy all files in 'my-tag' to a new directory >>> lightly-download token='123' dataset_id='XYZ' tag_name='my-tag' input_dir='data/' output_dir='my_data/' """ _download_cli(cfg) def entry(): download_cli()
4,846
34.903704
115
py
lightly
lightly-master/lightly/cli/embed_cli.py
# -*- coding: utf-8 -*- """**Lightly Embed:** Embed images with one command. This module contains the entrypoint for the **lightly-embed** command-line interface. """ # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved import os from typing import List, Tuple, Union import hydra import numpy as np import torch import torchvision from lightly.cli._helpers import ( cpu_count, fix_hydra_arguments, fix_input_path, get_model_from_config, ) from lightly.data import LightlyDataset from lightly.utils.hipify import bcolors from lightly.utils.io import save_embeddings def _embed_cli( cfg, is_cli_call=True ) -> Union[Tuple[np.ndarray, List[int], List[str]], str]: """See embed_cli() for usage documentation is_cli_call: If True: Saves the embeddings as file and returns the filepath. If False: Returns the embeddings, labels, filenames as tuple. Embeddings are of shape (n_samples, embedding_size) len(labels) = len(filenames) = n_samples """ input_dir = cfg["input_dir"] if input_dir and is_cli_call: input_dir = fix_input_path(input_dir) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False if torch.cuda.is_available(): device = torch.device("cuda") else: device = torch.device("cpu") transform = torchvision.transforms.Compose( [ torchvision.transforms.Resize( (cfg["collate"]["input_size"], cfg["collate"]["input_size"]) ), torchvision.transforms.ToTensor(), torchvision.transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ), ] ) dataset = LightlyDataset(input_dir, transform=transform) # disable drop_last and shuffle cfg["loader"]["drop_last"] = False cfg["loader"]["shuffle"] = False cfg["loader"]["batch_size"] = min(cfg["loader"]["batch_size"], len(dataset)) # determine the number of available cores if cfg["loader"]["num_workers"] < 0: cfg["loader"]["num_workers"] = cpu_count() dataloader = torch.utils.data.DataLoader(dataset, **cfg["loader"]) encoder = get_model_from_config(cfg, is_cli_call) embeddings, labels, filenames = encoder.embed(dataloader, device=device) if is_cli_call: path = os.path.join(os.getcwd(), "embeddings.csv") save_embeddings(path, embeddings, labels, filenames) print(f"Embeddings are stored at {bcolors.OKBLUE}{path}{bcolors.ENDC}") os.environ[ cfg["environment_variable_names"]["lightly_last_embedding_path"] ] = path return path return embeddings, labels, filenames @hydra.main(**fix_hydra_arguments(config_path="config", config_name="config")) def embed_cli(cfg) -> str: """Embed images from the command-line. Args: cfg: The default configs are loaded from the config file. To overwrite them please see the section on the config file (.config.config.yaml). Command-Line Args: input_dir: Path to the input directory where images are stored. checkpoint: Path to the checkpoint of a pretrained model. If left empty, a pretrained model by lightly is used. Returns: The path to the created embeddings file. Examples: >>> # embed images with default settings and a lightly model >>> lightly-embed input_dir=data/ >>> >>> # embed images with default settings and a custom checkpoint >>> lightly-embed input_dir=data/ checkpoint=my_checkpoint.ckpt >>> >>> # embed images with custom settings >>> lightly-embed input_dir=data/ model.num_ftrs=32 """ return _embed_cli(cfg) def entry(): embed_cli()
3,907
28.606061
80
py
lightly
lightly-master/lightly/cli/lightly_cli.py
# -*- coding: utf-8 -*- """**Lightly Magic:** Train and embed in one command. This module contains the entrypoint for the **lightly-magic** command-line interface. """ # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved import hydra from omegaconf import DictConfig from lightly.cli._helpers import fix_hydra_arguments from lightly.cli.embed_cli import _embed_cli from lightly.cli.train_cli import _train_cli from lightly.utils.hipify import print_as_warning def _lightly_cli(cfg, is_cli_call=True): cfg["loader"]["shuffle"] = True cfg["loader"]["drop_last"] = True if cfg["trainer"]["max_epochs"] > 0: print("#" * 10 + " Starting to train an embedding model.") checkpoint = _train_cli(cfg, is_cli_call) else: checkpoint = "" cfg["loader"]["shuffle"] = False cfg["loader"]["drop_last"] = False cfg["checkpoint"] = checkpoint print("#" * 10 + " Starting to embed your dataset.") embeddings = _embed_cli(cfg, is_cli_call) cfg["embeddings"] = embeddings print("#" * 10 + " Finished") @hydra.main(**fix_hydra_arguments(config_path="config", config_name="config")) def lightly_cli(cfg): """Train a self-supervised model and use it to embed your dataset. Args: cfg: The default configs are loaded from the config file. To overwrite them please see the section on the config file (.config.config.yaml). Command-Line Args: input_dir: Path to the input directory where images are stored. Examples: >>> # train model and embed images with default settings >>> lightly-magic input_dir=data/ >>> >>> # train model for 10 epochs and embed images >>> lightly-magic input_dir=data/ trainer.max_epochs=10 """ return _lightly_cli(cfg) def entry(): lightly_cli()
1,887
26.362319
78
py
lightly
lightly-master/lightly/cli/train_cli.py
# -*- coding: utf-8 -*- """**Lightly Train:** Train a self-supervised model from the command-line. This module contains the entrypoint for the **lightly-train** command-line interface. """ # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved import copy import os import warnings import hydra import torch import torch.nn as nn from omegaconf import OmegaConf from lightly.cli._cli_simclr import _SimCLR from lightly.cli._helpers import ( cpu_count, fix_hydra_arguments, fix_input_path, get_ptmodel_from_config, is_url, load_from_state_dict, load_state_dict_from_url, ) from lightly.data import ImageCollateFunction, LightlyDataset from lightly.embedding import SelfSupervisedEmbedding from lightly.loss import NTXentLoss from lightly.models import ResNetGenerator from lightly.models.batchnorm import get_norm_layer from lightly.utils.hipify import bcolors def _train_cli(cfg, is_cli_call=True): input_dir = cfg["input_dir"] if input_dir and is_cli_call: input_dir = fix_input_path(input_dir) if "seed" in cfg.keys(): seed = cfg["seed"] torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False accelerator = "gpu" if torch.cuda.is_available() else "cpu" if accelerator == "gpu" and cfg["trainer"]["gpus"] > 1: devices = cfg["trainer"]["gpus"] strategy = "ddp" else: devices = 1 strategy = None if cfg["loader"]["batch_size"] < 64: msg = "Training a self-supervised model with a small batch size: {}! " msg = msg.format(cfg["loader"]["batch_size"]) msg += "Small batch size may harm embedding quality. " msg += "You can specify the batch size via the loader key-word: " msg += "loader.batch_size=BSZ" warnings.warn(msg) # determine the number of available cores if cfg["loader"]["num_workers"] < 0: cfg["loader"]["num_workers"] = cpu_count() state_dict = None checkpoint = cfg["checkpoint"] if cfg["pre_trained"] and not checkpoint: # if checkpoint wasn't specified explicitly and pre_trained is True # try to load the checkpoint from the model zoo checkpoint, key = get_ptmodel_from_config(cfg["model"]) if not checkpoint: msg = "Cannot download checkpoint for key {} ".format(key) msg += "because it does not exist! " msg += "Model will be trained from scratch." warnings.warn(msg) elif checkpoint: checkpoint = fix_input_path(checkpoint) if is_cli_call else checkpoint if checkpoint: # load the PyTorch state dictionary if is_url(checkpoint): state_dict = load_state_dict_from_url(checkpoint, map_location="cpu")[ "state_dict" ] else: state_dict = torch.load(checkpoint, map_location="cpu")["state_dict"] # load model resnet = ResNetGenerator(cfg["model"]["name"], cfg["model"]["width"]) last_conv_channels = list(resnet.children())[-1].in_features features = nn.Sequential( get_norm_layer(3, 0), *list(resnet.children())[:-1], nn.Conv2d(last_conv_channels, cfg["model"]["num_ftrs"], 1), nn.AdaptiveAvgPool2d(1), ) model = _SimCLR( features, num_ftrs=cfg["model"]["num_ftrs"], out_dim=cfg["model"]["out_dim"] ) if state_dict is not None: load_from_state_dict(model, state_dict) criterion = NTXentLoss(**cfg["criterion"]) optimizer = torch.optim.SGD(model.parameters(), **cfg["optimizer"]) dataset = LightlyDataset(input_dir) cfg["loader"]["batch_size"] = min(cfg["loader"]["batch_size"], len(dataset)) collate_fn = ImageCollateFunction(**cfg["collate"]) dataloader = torch.utils.data.DataLoader( dataset, **cfg["loader"], collate_fn=collate_fn ) encoder = SelfSupervisedEmbedding(model, criterion, optimizer, dataloader) # Create trainer config if isinstance(cfg, dict): trainer_kwargs = copy.deepcopy(cfg["trainer"]) else: trainer_kwargs = OmegaConf.to_container(cfg["trainer"]) if "gpus" in trainer_kwargs: # PyTorch Lightning >= 2.0 doesn't support the gpus trainer flag anymore. # We have to use accelerator and devices instead. del trainer_kwargs["gpus"] trainer_kwargs["accelerator"] = accelerator trainer_kwargs["devices"] = devices if strategy is not None: # Only add strategy if it is set because PyTorch Lightning used by default # strategy = None for version < 2.0 and strategy = "auto" for >= 2.0. None is # not supported for >= 2.0 and "auto" not supported for some versions < 2.0. trainer_kwargs["strategy"] = strategy trainer_config = OmegaConf.create(trainer_kwargs) encoder.train_embedding( trainer_config=trainer_config, checkpoint_callback_config=cfg["checkpoint_callback"], summary_callback_config=cfg["summary_callback"], ) print( f"Best model is stored at: {bcolors.OKBLUE}{encoder.checkpoint}{bcolors.ENDC}" ) os.environ[ cfg["environment_variable_names"]["lightly_last_checkpoint_path"] ] = encoder.checkpoint return encoder.checkpoint @hydra.main(**fix_hydra_arguments(config_path="config", config_name="config")) def train_cli(cfg): """Train a self-supervised model from the command-line. Args: cfg: The default configs are loaded from the config file. To overwrite them please see the section on the config file (.config.config.yaml). Command-Line Args: input_dir: Path to the input directory where images are stored. Examples: >>> # train model with default settings >>> lightly-train input_dir=data/ >>> >>> # train model with batches of size 128 >>> lightly-train input_dir=data/ loader.batch_size=128 >>> >>> # train model for 10 epochs >>> lightly-train input_dir=data/ trainer.max_epochs=10 >>> >>> # print a full summary of the model >>> lightly-train input_dir=data/ trainer.weights_summary=full """ return _train_cli(cfg) def entry(): train_cli()
6,371
32.893617
86
py
lightly
lightly-master/lightly/cli/version_cli.py
# -*- coding: utf-8 -*- """**Lightly Version:** Show the version of the installed package. Example: >>> # show the version of the installed package >>> lightly-version """ # Copyright (c) 2021. Lightly AG and its affiliates. # All Rights Reserved import hydra import lightly from lightly.cli._helpers import fix_hydra_arguments def _version_cli(): version = lightly.__version__ print(f"lightly version {version}", flush=True) @hydra.main(**fix_hydra_arguments(config_path="config", config_name="config")) def version_cli(cfg): """Prints the version of the used lightly package to the terminal.""" _version_cli() def entry(): version_cli()
677
20.870968
78
py
lightly
lightly-master/lightly/cli/config/__init__.py
""" lightly.cli.config The lightly.cli.config module holds default configs for the command-line interface. """ # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved
196
20.888889
76
py
lightly
lightly-master/lightly/cli/config/config.yaml
### i/o # The following arguments specify input and output locations # of images, embeddings, and checkpoints. input_dir: '' # Path to input directory which holds images. output_dir: '' # Path to directory which should store downloads. embeddings: '' # Path to csv file which holds embeddings. checkpoint: '' # Path to a model checkpoint. If left empty, a pre-trained model # will be used. label_dir: '' # Path to the input directory which holds the labels. label_names_file: '' # Path to a yaml file having the label names under the value 'names' custom_metadata: '' # Path to a json file in COCO format containing additional metadata ### Lightly platform # The following arguments are required for requests to the # Lightly platform. token: '' # User access token to the Lightly platform. dataset_id: '' # Identifier of the dataset on the Lightly platform. new_dataset_name: '' # Name of the new dataset to be created on the Lightly platform upload: 'full' # Whether to upload full images, thumbnails only, or metadata only. # Must be one of ['full', 'thumbnails', 'none'] append: False # Must be True if you want to append samples to an existing dataset. resize: -1 # Allow resizing of the images before uploading, usage =-1, =x, =[x,y] embedding_name: 'default' # Name of the embedding to be used on the Lightly platform. emb_upload_bsz: 32 # Number of embeddings which are uploaded in a single batch. tag_name: 'initial-tag' # Name of the requested tag on the Lightly platform. exclude_parent_tag: False # If true, only the samples in the defined tag, but without the parent tag, are taken. ### training and embeddings pre_trained: True # Whether to use a pre-trained model or not crop_padding: 0.1 # The padding to use when cropping # model namespace: Passed to lightly.models.ResNetGenerator. model: name: 'resnet-18' # Name of the model, currently supports popular variants: # resnet-18, resnet-34, resnet-50, resnet-101, resnet-152. out_dim: 128 # Dimensionality of output on which self-supervised loss is calculated. num_ftrs: 32 # Dimensionality of feature vectors (embedding size). width: 1 # Width of the resnet. # criterion namespace: Passed to lightly.loss.NTXentLoss. criterion: temperature: 0.5 # Number by which logits are divided. memory_bank_size: 0 # Size of the memory bank to use (e.g. for MoCo). 0 means no memory bank. # ^ slight abuse of notation, MoCo paper calls it momentum encoder # optimizer namespace: Passed to torch.optim.SGD. optimizer: lr: 1. # Learning rate of the optimizer. weight_decay: 0.00001 # L2 penalty. # collate namespace: Passed to lightly.data.ImageCollateFunction. collate: input_size: 64 # Size of the input images in pixels. cj_prob: 0.8 # Probability that color jitter is applied. cj_bright: 0.7 # Color_jitter intensity for brightness, cj_contrast: 0.7 # contrast, cj_sat: 0.7 # saturation, cj_hue: 0.2 # and hue. min_scale: 0.15 # Minimum size of random crop relative to input_size. random_gray_scale: 0.2 # Probability of converting image to gray scale. gaussian_blur: 0.5 # Probability of Gaussian blur. sigmas: [0.2, 2] # Sigmas of Gaussian blur kernel_size: null # Will be deprecated in favor of `sigmas` argument. If set, the old behavior # applies and `sigmas` is ignored. Used to calculate sigma of gaussian blur # with kernel_size * input_size. vf_prob: 0.0 # Probability that vertical flip is applied. hf_prob: 0.5 # Probability that horizontal flip is applied. rr_prob: 0.0 # Probability that random rotation is applied. rr_degrees: null # Range of degrees to select from for random rotation. # If rr_degrees is null, images are rotated by 90 degrees. # If rr_degrees is a [min, max] list, images are rotated # by a random angle in [min, max]. If rr_degrees is a # single number, images are rotated by a random angle in # [-rr_degrees, +rr_degrees]. All rotations are counter-clockwise. # loader namespace: Passed to torch.utils.data.DataLoader. loader: batch_size: 16 # Batch size for training / inference. shuffle: True # Whether to reshuffle data each epoch. num_workers: -1 # Number of workers pre-fetching batches. # -1 == number of available cores, # if -1, minimum of 8, maximum of 32 workers for upload. drop_last: True # Whether to drop the last batch during training. # trainer namespace: Passed to pytorch_lightning.Trainer. trainer: gpus: 1 # Number of gpus to use for training. max_epochs: 100 # Number of epochs to train for. precision: 32 # If set to 16, will use half-precision. enable_model_summary: True # Whether to enable model summarisation. weights_summary: # [deprecated] Use enable_model_summary # and summary_callback.max_depth. # checkpoint_callback namespace: Modify the checkpoint callback checkpoint_callback: save_last: True # Whether to save the checkpoint from the last epoch. save_top_k: 1 # Save the top k checkpoints. dirpath: # Where to store the checkpoints (empty field resolves to None). # If not set, checkpoints are stored in the hydra output dir. # summary_callback namespace: Modify the summary callback summary_callback: max_depth: 1 # The maximum depth of layer nesting that the summary will include. # environment variable namespace for saving artifacts environment_variable_names: lightly_last_checkpoint_path: LIGHTLY_LAST_CHECKPOINT_PATH lightly_last_embedding_path: LIGHTLY_LAST_EMBEDDING_PATH lightly_last_dataset_id: LIGHTLY_LAST_DATASET_ID # seed seed: 1 ### hydra # The arguments below are built-ins from the hydra-core Python package. hydra: run: dir: lightly_outputs/${now:%Y-%m-%d}/${now:%H-%M-%S} help: header: | == Description == The lightly Python package is a command-line tool for self-supervised learning. footer: | == Examples == Use a pre-trained resnet-18 to embed your images > lightly-embed input='path/to/image/folder' collate.input_size=224 Load a model from a custom checkpoint to embed your images > lightly-embed input_dir='path/to/image/folder' collate.input_size=224 checkpoint='path/to/checkpoint.ckpt' Train a self-supervised model on your image dataset from scratch > lightly-train input_dir='path/to/image/folder' loader.batch_size=128 collate.input_size=224 pre_trained=False Train a self-supervised model starting from the pre-trained checkpoint > lightly-train input_dir='path/to/image/folder' loader.batch_size=128 collate.input_size=224 Train a self-supervised model starting from a custom checkpoint > lightly-train input_dir='path/to/image/folder' loader.batch_size=128 collate.input_size=224 checkpoint='path/to/checkpoint.ckpt' Train using half-precision > lightly-train input_dir='path/to/image/folder' trainer.precision=16 Download a list of files in a given tag from the Lightly Platform > lightly-download tag_name='my-tag' dataset_id='your_dataset_id' token='your_access_token' Download a list of files in a given tag without filenames from the parent tag from the Lightly Platform > lightly-download tag_name='my-tag' dataset_id='your_dataset_id' token='your_access_token' exclude_parent_tag=True Copy all files in a given tag from a source directory to a target directory > lightly-download tag_name='my-tag' dataset_id='your_dataset_id' token='your_access_token' input_dir='data/' output_dir='new_data/' == Additional Information == Use self-supervised methods to understand and filter raw image data: Website: https://www.lightly.ai Documentation: https://docs.lightly.ai/self-supervised-learning/getting_started/command_line_tool.html
8,838
54.24375
138
yaml
lightly
lightly-master/lightly/cli/config/get_config.py
from pathlib import Path from omegaconf import DictConfig, OmegaConf def get_lightly_config() -> DictConfig: config_path = Path(__file__).with_name("config.yaml") conf = OmegaConf.load(config_path) # TODO(Huan, 05.04.2023): remove this when hydra is completely dropped if conf.get("hydra"): # This config entry is only for hydra; not referenced in any logic del conf["hydra"] return conf
427
29.571429
74
py
lightly
lightly-master/lightly/data/__init__.py
"""The lightly.data module provides a dataset wrapper and collate functions. """ # Copyright (c) 2020. Lightly AG and its affiliates. # All Rights Reserved from lightly.data._video import ( EmptyVideoError, NonIncreasingTimestampError, UnseekableTimestampError, VideoError, ) from lightly.data.collate import ( BaseCollateFunction, DINOCollateFunction, ImageCollateFunction, MAECollateFunction, MoCoCollateFunction, MSNCollateFunction, MultiCropCollateFunction, PIRLCollateFunction, SimCLRCollateFunction, SwaVCollateFunction, VICRegLCollateFunction, imagenet_normalize, ) from lightly.data.dataset import LightlyDataset
687
24.481481
80
py