-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
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
integrate SAM (segment anything) encoder with Unet #757
Open
Rusteam
wants to merge
26
commits into
qubvel-org:main
Choose a base branch
from
Rusteam:sam
base: main
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.
+297
−18
Open
Changes from 23 commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
4beb571
add sam encoder and decoder
3dc3235
refactor sam vit encoder to common format
85565ce
refactor sam decoder init
1143668
add segmentation head to sam
48033cb
add sam to encoder and model docs
1f1eaca
remove sam encoders from test_models
f37c9b3
wip weights
6b36927
load pretrained sam state dict for a model
64a2516
update readme with sam model and encoders
4d1144e
use iou scaling to avoid errors with torch ddp
c1a9319
set unused sam modules to require grad False
2ed775d
set unused sam modules to None
9c93eb4
remove prompt encoder from sam
9731e8f
Merge pull request #1 from Rusteam/sam-ddp
Rusteam 500779e
add segment-anything to reqs
b301d30
integrate sam encoder to Unet model
12a0db6
ensure sam encoder weights loading
a049c88
update segment-anything package source in reqs
b8189e0
Integrate SAM's image encoder with Unet
Rusteam e6cfdc9
remove sam decoder as it's not stable yet
9b29124
minor changes from PR review
e968719
Merge branch 'master' into sam
qubvel 5edc0ee
use vit_depth to control sam vit depth
e5c4bc4
rm changes from pan model
c5bc356
implement skip connections for sam vit encoder
f1ac494
Merge branch 'master' into sam
qubvel 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 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 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 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 |
---|---|---|
|
@@ -36,5 +36,3 @@ DeepLabV3 | |
DeepLabV3+ | ||
~~~~~~~~~~ | ||
.. autoclass:: segmentation_models_pytorch.DeepLabV3Plus | ||
|
||
|
This file contains 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 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 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 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 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,106 @@ | ||
import math | ||
import warnings | ||
from typing import Mapping, Any | ||
|
||
import torch | ||
from segment_anything.modeling import ImageEncoderViT | ||
|
||
from segmentation_models_pytorch.encoders._base import EncoderMixin | ||
|
||
|
||
class SamVitEncoder(EncoderMixin, ImageEncoderViT): | ||
def __init__(self, **kwargs): | ||
self._vit_depth = kwargs.pop("vit_depth") | ||
self._encoder_depth = kwargs.get("depth", 5) | ||
kwargs.update({"depth": self._vit_depth}) | ||
super().__init__(**kwargs) | ||
self._out_chans = kwargs.get("out_chans", 256) | ||
self._patch_size = kwargs.get("patch_size", 16) | ||
self._validate() | ||
|
||
@property | ||
def output_stride(self): | ||
return 32 | ||
|
||
def _get_scale_factor(self) -> float: | ||
"""Input image will be downscale by this factor""" | ||
return int(math.log(self._patch_size, 2)) | ||
|
||
def _validate(self): | ||
# check vit depth | ||
if self._vit_depth not in [12, 24, 32]: | ||
raise ValueError(f"vit_depth must be one of [12, 24, 32], got {self._vit_depth}") | ||
# check output | ||
scale_factor = self._get_scale_factor() | ||
if scale_factor != self._encoder_depth: | ||
raise ValueError( | ||
f"With patch_size={self._patch_size} and depth={self._encoder_depth}, " | ||
"spatial dimensions of model output will not match input spatial dimensions. " | ||
"It is recommended to set encoder depth=4 with default vit patch_size=16." | ||
) | ||
|
||
@property | ||
def out_channels(self): | ||
# Fill up with leading zeros to be used in Unet | ||
scale_factor = self._get_scale_factor() | ||
return [0] * scale_factor + [self._out_chans] | ||
|
||
def forward(self, x: torch.Tensor) -> list[torch.Tensor]: | ||
# Return a list of tensors to match other encoders | ||
return [x, super().forward(x)] | ||
Rusteam marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
def load_state_dict(self, state_dict: Mapping[str, Any], strict: bool = True) -> None: | ||
# Exclude mask_decoder and prompt encoder weights | ||
# and remove 'image_encoder.' prefix | ||
state_dict = { | ||
k.replace("image_encoder.", ""): v | ||
for k, v in state_dict.items() | ||
if not k.startswith("mask_decoder") and not k.startswith("prompt_encoder") | ||
} | ||
missing, unused = super().load_state_dict(state_dict, strict=False) | ||
if len(missing) + len(unused) > 0: | ||
n_loaded = len(state_dict) - len(missing) - len(unused) | ||
warnings.warn( | ||
f"Only {n_loaded} out of pretrained {len(state_dict)} SAM image encoder modules are loaded. " | ||
f"Missing modules: {missing}. Unused modules: {unused}." | ||
) | ||
|
||
|
||
sam_vit_encoders = { | ||
"sam-vit_h": { | ||
"encoder": SamVitEncoder, | ||
"pretrained_settings": { | ||
"sa-1b": {"url": "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth"}, | ||
}, | ||
"params": dict( | ||
embed_dim=1280, | ||
vit_depth=32, | ||
num_heads=16, | ||
global_attn_indexes=[7, 15, 23, 31], | ||
), | ||
}, | ||
"sam-vit_l": { | ||
"encoder": SamVitEncoder, | ||
"pretrained_settings": { | ||
"sa-1b": {"url": "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth"}, | ||
}, | ||
"params": dict( | ||
embed_dim=1024, | ||
vit_depth=24, | ||
num_heads=16, | ||
global_attn_indexes=[5, 11, 17, 23], | ||
), | ||
}, | ||
"sam-vit_b": { | ||
"encoder": SamVitEncoder, | ||
"pretrained_settings": { | ||
"sa-1b": {"url": "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth"}, | ||
}, | ||
"params": dict( | ||
embed_dim=768, | ||
vit_depth=12, | ||
num_heads=12, | ||
global_attn_indexes=[2, 5, 8, 11], | ||
), | ||
}, | ||
} |
Empty file.
This file contains 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 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,74 @@ | ||
import pytest | ||
import torch | ||
|
||
import segmentation_models_pytorch as smp | ||
from segmentation_models_pytorch.encoders import get_encoder | ||
from tests.test_models import get_sample, _test_forward, _test_forward_backward | ||
|
||
|
||
@pytest.mark.parametrize("encoder_name", ["sam-vit_b", "sam-vit_l"]) | ||
@pytest.mark.parametrize("img_size", [64, 128]) | ||
@pytest.mark.parametrize("patch_size,depth", [(8, 3), (16, 4)]) | ||
@pytest.mark.parametrize("vit_depth", [12, 24]) | ||
def test_sam_encoder(encoder_name, img_size, patch_size, depth, vit_depth): | ||
encoder = get_encoder(encoder_name, img_size=img_size, patch_size=patch_size, depth=depth, vit_depth=vit_depth) | ||
assert encoder.output_stride == 32 | ||
|
||
sample = torch.ones(1, 3, img_size, img_size) | ||
with torch.no_grad(): | ||
out = encoder(sample) | ||
|
||
expected_patches = img_size // patch_size | ||
assert out[-1].size() == torch.Size([1, 256, expected_patches, expected_patches]) | ||
|
||
|
||
def test_sam_encoder_validation_error(): | ||
with pytest.raises(ValueError): | ||
get_encoder("sam-vit_b", img_size=64, patch_size=16, depth=5, vit_depth=12) | ||
get_encoder("sam-vit_b", img_size=64, patch_size=16, depth=4, vit_depth=None) | ||
get_encoder("sam-vit_b", img_size=64, patch_size=16, depth=4, vit_depth=6) | ||
|
||
|
||
@pytest.mark.skip(reason="Decoder has been removed, keeping this for future integration") | ||
@pytest.mark.parametrize("decoder_multiclass_output", [True, False]) | ||
@pytest.mark.parametrize("n_classes", [1, 3]) | ||
def test_sam(decoder_multiclass_output, n_classes): | ||
model = smp.SAM( | ||
"sam-vit_b", | ||
encoder_weights=None, | ||
weights=None, | ||
image_size=64, | ||
decoder_multimask_output=decoder_multiclass_output, | ||
classes=n_classes, | ||
) | ||
sample = get_sample(smp.SAM) | ||
model.eval() | ||
|
||
_test_forward(model, sample, test_shape=True) | ||
_test_forward_backward(model, sample, test_shape=True) | ||
|
||
|
||
@pytest.mark.parametrize("model_class", [smp.Unet]) | ||
@pytest.mark.parametrize("decoder_channels,encoder_depth", [([64, 32, 16, 8], 4), ([64, 32, 16, 8], 4)]) | ||
def test_sam_encoder_arch(model_class, decoder_channels, encoder_depth): | ||
img_size = 1024 | ||
model = model_class( | ||
"sam-vit_b", | ||
encoder_weights=None, | ||
encoder_depth=encoder_depth, | ||
decoder_channels=decoder_channels, | ||
) | ||
smp = torch.ones(1, 3, img_size, img_size) | ||
_test_forward_backward(model, smp, test_shape=True) | ||
|
||
|
||
@pytest.mark.skip(reason="Run this test manually as it needs to download weights") | ||
def test_sam_weights(): | ||
smp.create_model("sam", encoder_name="sam-vit_b", encoder_weights=None, weights="sa-1b") | ||
|
||
|
||
@pytest.mark.skip(reason="Run this test manually as it needs to download weights") | ||
def test_sam_encoder_weights(): | ||
smp.create_model( | ||
"unet", encoder_name="sam-vit_b", encoder_depth=4, encoder_weights="sa-1b", decoder_channels=[64, 32, 16, 8] | ||
) |
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.
well, this is probably out of the scope of this PR. Did you test that PAN works with a depth other than 5?
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.
let me try it
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.
tbh, I have changed this by mistake, although this change should not hurt. Do you want me to remove it? It does not work with SAM encoder
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.
Yes, could you remove this code pls?