-
Notifications
You must be signed in to change notification settings - Fork 342
SparK Implementation #1892
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
gabrielfruet
wants to merge
87
commits into
lightly-ai:master
Choose a base branch
from
gabrielfruet:feat/1462-spark-implementation
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
SparK Implementation #1892
Changes from all commits
Commits
Show all changes
87 commits
Select commit
Hold shift + click to select a range
bd0855c
Initial work on SparK
johnsutor 42bd849
feat(spark): More work on spark
johnsutor 7e73b83
Merge branch 'spark' of github.com:johnsutor/lightly
gabrielfruet 724819c
refactor: should not nest modules.
gabrielfruet b0023f0
refactor: removed empty file
gabrielfruet 8120990
refactor: adhered to correct directory structure.
gabrielfruet a7138d0
feat: put everything into the sparse spark module.
gabrielfruet 9b869e9
refactor: removed redundant super calls with class.
gabrielfruet 36cb94c
refactor: removed spark code.
gabrielfruet 0afc280
refactor: removing redundant super calls
gabrielfruet 280a479
refactor: remove empty file
gabrielfruet 7e0f2bc
refactor: porting original code. starting from scratch
gabrielfruet 9a9dff6
refactor: fixing type hint problems.
gabrielfruet 407a4c0
refactor: removing unecessary redundant super
gabrielfruet 47eecf3
fix: indentation
gabrielfruet 7a956b3
feat: working module
gabrielfruet 9d0f5c4
refactor: using library already implemente masking
gabrielfruet 4aa69f7
feat: using patchify
gabrielfruet 8b95a51
refactor: putting densification into a single module
gabrielfruet 014f724
typo: raito -> ratio
gabrielfruet de01b0a
feat: encapsulated logic to single dnesifier module
gabrielfruet 445bda7
refactor: cleaning code.
gabrielfruet 741d531
refactor: letting sparse encoder be repsonsible for sizes and etc
gabrielfruet fb5c90d
feat: resnet18
gabrielfruet deeb4ef
refactor: removing unused code
gabrielfruet 64df2e3
fix: bool tensor is inconvenient
gabrielfruet 45b6eb8
refactor: documenting
gabrielfruet fb7903a
refactor: masking as a module
gabrielfruet 138380f
refactor: removing unused variables
gabrielfruet 6b3dbdf
refactor: removing unecessary module dependency
gabrielfruet ed8691a
refactor: loss as module
gabrielfruet 3dcd5c3
refactor: spark visualization decoding logic as module
gabrielfruet 1c316da
refactor: remove unused
gabrielfruet 3ba1839
refactor
gabrielfruet 70d32dd
refactor: removed big module and refactored timm funcs
gabrielfruet 2f73d15
feat: example script
gabrielfruet b48d4eb
refactor: removed unused code and added opyrights
gabrielfruet 25687d3
doc: improved documentation and type hinting
gabrielfruet 96739fe
fix: type hinting
gabrielfruet ed70f9a
tests: testing active ex
gabrielfruet 4fb16d7
tests: sp conv forward test
gabrielfruet 6188aa4
refactor: using fixture instead of context manager
gabrielfruet 7cfc508
format: formatting
gabrielfruet 0098425
feat: moved patch recon loss to loss module
gabrielfruet dea0173
fix: no need of this sparse argument since its always sparse.
gabrielfruet 83bdd60
format
gabrielfruet 4b7f119
feat: init module access
gabrielfruet 86386b7
feat: removed sparse encoder since it adds no necessary logic.
gabrielfruet 92ebd99
refactor: removing dense model to sparse
gabrielfruet 93c7ee5
fix: renamin to unet decoder
gabrielfruet 2710f6b
format
gabrielfruet 3a59d6a
fix: removed inplace operation
gabrielfruet 34ed5f6
fix: using proper eps
gabrielfruet 2ff68e9
docs: rst for loss
gabrielfruet de92784
feat: annotations
gabrielfruet ad4c9ac
typos
gabrielfruet 8b2eca5
typing issues
liopeer b16c6b3
formatting
liopeer 1b9f53a
context manager for global tensor + typing
liopeer 4e9cde1
format
gabrielfruet 25e7fbb
Merge branch 'feat/1462-spark-implementation' of github.com:gabrielfr…
gabrielfruet 6abe8fc
refactor: better naming
gabrielfruet c9c99d2
refactor: lenght, not levels
gabrielfruet 73da36e
fix: remove unecessary target transform
gabrielfruet 708a18e
test: testing loss, comparing with reference and distributed testing
gabrielfruet 0c10ea0
doc: where i took the loss from
gabrielfruet bbe0b07
refactor: make example simpler
gabrielfruet bde5292
typo: spark masking output
gabrielfruet 73b0bb1
fix: imports according to #1895
gabrielfruet 86ea8a9
fix: format
gabrielfruet edbfdcf
fix: tests now uses context manager for sparse mask
gabrielfruet e28391a
fix: using Tensor instead of torch.Tensor
gabrielfruet a1f82a0
doc: referencing original author
gabrielfruet 9ce0f80
test: spark masking test
gabrielfruet e66d84a
doc: removed unecessary comment
gabrielfruet 86934d2
feat: testing densify block
gabrielfruet a984e0d
fix: removed unecessary none handling
gabrielfruet 09103d6
fix(test): sparse spark test with incorrect shapes
gabrielfruet e43d7a3
test: spark densifier
gabrielfruet ef88d62
format
gabrielfruet 5e8f28e
feat: notebook example
gabrielfruet 441e608
format and mypy
gabrielfruet f21faaa
fix: skipping tests on minimal and scoped imports
gabrielfruet 3e962a8
fix: missing trunc_normal_ import
gabrielfruet 4e5e067
Fix Python 3.7 type hints compatibility in sparse_spark tests
gabrielfruet e5f0b04
format
gabrielfruet 9687035
doc: removed copyright docstring, we already reference authoer on the…
gabrielfruet File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,302 @@ | ||
| { | ||
| "cells": [ | ||
| { | ||
| "cell_type": "markdown", | ||
| "id": "0", | ||
| "metadata": {}, | ||
| "source": [ | ||
| "This example requires the following dependencies to be installed:\n", | ||
| "pip install \"lightly[timm]\"" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": null, | ||
| "id": "1", | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "!pip install \"lightly[timm]\"" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "markdown", | ||
| "id": "2", | ||
| "metadata": {}, | ||
| "source": [ | ||
| "Note: The model and training settings do not follow the reference settings\n", | ||
| "from the paper. The settings are chosen such that the example can easily be\n", | ||
| "run on a small dataset with a single GPU." | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": null, | ||
| "id": "3", | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "import pytorch_lightning as pl\n", | ||
| "import timm\n", | ||
| "import torch\n", | ||
| "import torchvision\n", | ||
| "from pytorch_lightning import LightningModule\n", | ||
| "from torch import Tensor\n", | ||
| "from torch.nn import Module\n", | ||
| "from torchvision.transforms import v2" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": null, | ||
| "id": "4", | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "import lightly.models.utils as model_utils\n", | ||
| "from lightly.loss.sparse_spark import SparKPatchReconLoss\n", | ||
| "from lightly.models.modules import sparse_spark" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": null, | ||
| "id": "5", | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "## The global projection head is the same as the Barlow Twins one\n", | ||
| "from lightly.models.modules.sparse_spark import (\n", | ||
| " SparKDensifier,\n", | ||
| " SparKMasker,\n", | ||
| " SparKMaskingOutput,\n", | ||
| " SparKOutputDecoder,\n", | ||
| " UNetDecoder,\n", | ||
| " sparse_layer_context,\n", | ||
| ")" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": null, | ||
| "id": "6", | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "def _get_downsample_ratio_from_timm_model(model: Module) -> int:\n", | ||
| " if not hasattr(model, \"feature_info\"):\n", | ||
| " raise ValueError(\n", | ||
| " \"The provided model does not have the required 'feature_info' attribute.\"\n", | ||
| " )\n", | ||
| " return model.feature_info[-1][\"reduction\"]" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": null, | ||
| "id": "7", | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "def _get_enc_feat_map_chs_from_timm_model(model: Module) -> list[int]:\n", | ||
| " if not hasattr(model, \"feature_info\"):\n", | ||
| " raise ValueError(\n", | ||
| " \"The provided model does not have the required 'feature_info' attribute.\"\n", | ||
| " )\n", | ||
| " return [fi[\"num_chs\"] for fi in model.feature_info]" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": null, | ||
| "id": "8", | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "class SparseSparK(LightningModule):\n", | ||
| " def __init__(\n", | ||
| " self,\n", | ||
| " input_size: int = 416,\n", | ||
| " mask_ratio: float = 0.6,\n", | ||
| " densify_norm: str = \"bn\",\n", | ||
| " sbn=False,\n", | ||
| " ):\n", | ||
| " super().__init__()\n", | ||
| " backbone = timm.create_model(\n", | ||
| " model_name=\"resnet18\", drop_path_rate=0.05, features_only=True\n", | ||
| " )\n", | ||
| " downsample_ratio = _get_downsample_ratio_from_timm_model(backbone)\n", | ||
| " enc_feat_map_chs = _get_enc_feat_map_chs_from_timm_model(backbone)\n", | ||
| " self.sparse_encoder = sparse_spark.dense_model_to_sparse(\n", | ||
| " m=backbone, sbn=sbn, verbose=True\n", | ||
| " )\n", | ||
| " self.fmap_h = input_size // downsample_ratio\n", | ||
| " self.fmap_w = input_size // downsample_ratio\n", | ||
| " self.dense_decoder = UNetDecoder(\n", | ||
| " up_sample_ratio=downsample_ratio,\n", | ||
| " width=enc_feat_map_chs[-1],\n", | ||
| " )\n", | ||
| " self.masker = SparKMasker(\n", | ||
| " feature_map_size=(self.fmap_h, self.fmap_w),\n", | ||
| " downsample_ratio=downsample_ratio,\n", | ||
| " mask_ratio=mask_ratio,\n", | ||
| " )\n", | ||
| " self.densifier = SparKDensifier(\n", | ||
| " encoder_in_channels=enc_feat_map_chs,\n", | ||
| " decoder_in_channel=self.dense_decoder.width,\n", | ||
| " densify_norm_str=densify_norm.lower(),\n", | ||
| " sbn=sbn,\n", | ||
| " )\n", | ||
| " self.downsample_ratio = downsample_ratio\n", | ||
| " # loss module for patch reconstruction\n", | ||
| " self.recon_loss_fn = SparKPatchReconLoss()\n", | ||
| " # output decoder for visualization (pass minimal spatial props)\n", | ||
| " self.output_decoder = SparKOutputDecoder(\n", | ||
| " fmap_h=self.fmap_h,\n", | ||
| " fmap_w=self.fmap_w,\n", | ||
| " downsample_ratio=downsample_ratio,\n", | ||
| " )\n", | ||
| "\n", | ||
| " def forward(\n", | ||
| " self,\n", | ||
| " inp_bchw: Tensor,\n", | ||
| " vis=False,\n", | ||
| " ):\n", | ||
| " # step1. Mask\n", | ||
| " mask_out: SparKMaskingOutput = self.masker(inp_bchw)\n", | ||
| " masked_bchw, per_level_mask = mask_out\n", | ||
| " active_b1fHfW = per_level_mask[0]\n", | ||
| " active_b1hw = per_level_mask[-1]\n", | ||
| " # step2. Encode: get hierarchical encoded sparse features (a list containing 4 feature maps at 4 scales)\n", | ||
| " # Use sparse_layer_context to provide the mask to the sparse encoder and densifier.\n", | ||
| " with sparse_layer_context(active_mask=active_b1fHfW):\n", | ||
| " fea_bcffs: list[Tensor] = self.sparse_encoder(masked_bchw)\n", | ||
| " # step3. Densify: get hierarchical dense features for decoding\n", | ||
| " to_dec = self.densifier(fea_bcffs)\n", | ||
| " # step4. Decode and reconstruct\n", | ||
| " rec_bchw = self.dense_decoder(to_dec)\n", | ||
| " inp, rec = (\n", | ||
| " model_utils.patchify(inp_bchw, self.downsample_ratio),\n", | ||
| " model_utils.patchify(rec_bchw, self.downsample_ratio),\n", | ||
| " ) # inp and rec: (B, L = f*f, N = C*downsample_ratio**2)\n", | ||
| "\n", | ||
| " recon_loss, mean, var = self.recon_loss_fn(\n", | ||
| " inp_patches=inp, rec_patches=rec, active_mask=active_b1fHfW\n", | ||
| " )\n", | ||
| "\n", | ||
| " if vis:\n", | ||
| " return self.output_decoder(\n", | ||
| " rec_patches=rec,\n", | ||
| " mean=mean,\n", | ||
| " var=var,\n", | ||
| " inp_bchw=inp_bchw,\n", | ||
| " active_mask_full=active_b1hw,\n", | ||
| " )\n", | ||
| " else:\n", | ||
| " return recon_loss\n", | ||
| "\n", | ||
| " def training_step(self, batch: tuple[Tensor, Tensor], batch_index: int) -> Tensor:\n", | ||
| " img, _ = batch\n", | ||
| " recon_loss = self.forward(img)\n", | ||
| " # Log the training loss to logger and progress bar (per-step and per-epoch)\n", | ||
| " self.log(\n", | ||
| " \"train_loss\",\n", | ||
| " recon_loss,\n", | ||
| " on_step=True,\n", | ||
| " on_epoch=True,\n", | ||
| " prog_bar=True,\n", | ||
| " logger=True,\n", | ||
| " )\n", | ||
| " return recon_loss\n", | ||
| "\n", | ||
| " def configure_optimizers(self):\n", | ||
| " return torch.optim.SGD(\n", | ||
| " self.parameters(), lr=0.03, momentum=0.9, weight_decay=1e-4\n", | ||
| " )" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": null, | ||
| "id": "9", | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "model = SparseSparK(input_size=416)" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": null, | ||
| "id": "10", | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "dataset = torchvision.datasets.Caltech101(\n", | ||
| " \"datasets/caltech101\",\n", | ||
| " download=True,\n", | ||
| " transform=v2.Compose(\n", | ||
| " [\n", | ||
| " v2.Resize((416, 416)),\n", | ||
| " v2.RGB(),\n", | ||
| " v2.ToTensor(),\n", | ||
| " v2.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n", | ||
| " ]\n", | ||
| " ),\n", | ||
| ")\n", | ||
| "# or create a dataset from a folder containing images or videos:\n", | ||
| "# dataset = LightlyDataset(\"path/to/folder\")" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": null, | ||
| "id": "11", | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "dataloader = torch.utils.data.DataLoader(\n", | ||
| " dataset,\n", | ||
| " batch_size=4,\n", | ||
| " shuffle=True,\n", | ||
| " drop_last=True,\n", | ||
| " num_workers=8,\n", | ||
| ")" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": null, | ||
| "id": "12", | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "trainer = pl.Trainer(\n", | ||
| " max_epochs=30,\n", | ||
| ")" | ||
| ] | ||
| }, | ||
| { | ||
| "cell_type": "code", | ||
| "execution_count": null, | ||
| "id": "13", | ||
| "metadata": {}, | ||
| "outputs": [], | ||
| "source": [ | ||
| "trainer.fit(\n", | ||
| " model=model,\n", | ||
| " train_dataloaders=dataloader,\n", | ||
| ")" | ||
| ] | ||
| } | ||
| ], | ||
| "metadata": { | ||
| "jupytext": { | ||
| "cell_metadata_filter": "-all", | ||
| "main_language": "python", | ||
| "notebook_metadata_filter": "-all" | ||
| } | ||
| }, | ||
| "nbformat": 4, | ||
| "nbformat_minor": 5 | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The download of Caltech101 currently does not seem to work for me. If it worked for you, ignore this comment – might open an issue with torchvision after checking if it has something to do with my local setup.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I know that
torchvisionis deprecating some datasets. So, some links are broken pytorch/vision#9335