-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Adding DPT #1079
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
Merged
Merged
Adding DPT #1079
Changes from all commits
Commits
Show all changes
45 commits
Select commit
Hold shift + click to select a range
78ba0e8
Initial timm vit encoder commit
vedantdalimkar 2c38de6
Add DPT model and update logic for TimmViTEncoder class
vedantdalimkar 5599409
Removed redudant documentation
vedantdalimkar c47bdfb
Added intitial test and some minor code modifications
vedantdalimkar 71e2acb
Code refactor
vedantdalimkar e85836d
Added weight conversion script
vedantdalimkar 35cb060
Moved conversion script to appropriate location
vedantdalimkar aa84f4e
Added logic in timm table generation for adding ViT encoders for DPT
67c4a75
Ruff formatting
vedantdalimkar 85f22fb
Code revision
vedantdalimkar ef48032
Remove unnecessary comment
vedantdalimkar 28204ad
Simplify ViT encoder
qubvel 1b9a6f6
Refactor ProjectionReadout
qubvel 334cfbb
Refactor modeling DPT
qubvel 7e1ef3b
Support more encoders
qubvel d65c0f7
Refactor a bit conversion, added validation
qubvel 0a62fe0
Fixup
qubvel e3238ae
Split forward for timm_vit
qubvel df4d087
Rename readout, remove feature_dim
qubvel 8bcb0ed
refactor + add transform
qubvel 6ba6746
Fixup
qubvel 8fd8c77
Refine docs a bit
qubvel 9bf1fd2
Refine docs
qubvel 0e9170f
Refine model size a bit and docs
qubvel a0aa5a8
Add to docs
qubvel 6cfd3be
Add note
qubvel d4b162d
Remove txt
qubvel 5fe80a5
Fix doc
qubvel 0a14972
Fix docstring
qubvel 5b28978
Fixing list in activation
qubvel 0ed621c
Fixing list
qubvel 6207310
Fixing list
qubvel 19eeebe
Fixup, fix type hint
qubvel f2e3f89
Merge branch 'main' into pr/vedantdalimkar/1079
qubvel 1257c4b
Add to README
qubvel 21a164a
Add example
qubvel 8d3ed4f
Add decoder_readout according to initial impl
qubvel 4eb6ec3
Tests update
vedantdalimkar 165b9c0
Fix encoder tests
qubvel 5603707
Fix DPT tests
qubvel 9518964
Refactor a bit
qubvel 38cb944
Tests
qubvel 17d3328
Update gen test models
qubvel 83b9655
Revert gitignore
qubvel 343fbe0
Fix test
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
Large diffs are not rendered by default.
Oops, something went wrong.
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
Large diffs are not rendered by default.
Oops, something went wrong.
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,122 @@ | ||
import cv2 | ||
import torch | ||
import albumentations as A | ||
import segmentation_models_pytorch as smp | ||
|
||
MODEL_WEIGHTS_PATH = r"dpt_large-ade20k-b12dca68.pt" | ||
HF_HUB_PATH = "qubvel-hf/dpt-large-ade20k" | ||
PUSH_TO_HUB = False | ||
|
||
|
||
def get_transform(): | ||
return A.Compose( | ||
[ | ||
A.LongestMaxSize(max_size=480, interpolation=cv2.INTER_CUBIC), | ||
A.Normalize( | ||
mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), max_pixel_value=255.0 | ||
), | ||
# This is not correct transform, ideally image should resized without padding to multiple of 32, | ||
# but we take there is no such transform in albumentations, here is closest one | ||
A.PadIfNeeded( | ||
min_height=None, | ||
min_width=None, | ||
pad_height_divisor=32, | ||
pad_width_divisor=32, | ||
border_mode=cv2.BORDER_CONSTANT, | ||
value=0, | ||
p=1, | ||
), | ||
] | ||
) | ||
|
||
|
||
if __name__ == "__main__": | ||
# fmt: off | ||
smp_model = smp.DPT(encoder_name="tu-vit_large_patch16_384", classes=150, dynamic_img_size=True) | ||
dpt_model_dict = torch.load(MODEL_WEIGHTS_PATH, weights_only=True) | ||
|
||
for layer_index in range(0, 4): | ||
for param in ["running_mean", "running_var", "num_batches_tracked", "weight", "bias"]: | ||
for block_index in [1, 2]: | ||
for bn_index in [1, 2]: | ||
# Assigning weights of 4th fusion layer of original model to 1st layer of SMP DPT model, | ||
# Assigning weights of 3rd fusion layer of original model to 2nd layer of SMP DPT model ... | ||
# and so on ... | ||
# This is because order of calling fusion layers is reversed in original DPT implementation | ||
dpt_model_dict[f"decoder.fusion_blocks.{layer_index}.residual_conv_block{block_index}.batch_norm_{bn_index}.{param}"] = \ | ||
dpt_model_dict.pop(f"scratch.refinenet{4 - layer_index}.resConfUnit{block_index}.bn{bn_index}.{param}") | ||
|
||
if param in ["weight", "bias"]: | ||
if param == "weight": | ||
for block_index in [1, 2]: | ||
for conv_index in [1, 2]: | ||
dpt_model_dict[f"decoder.fusion_blocks.{layer_index}.residual_conv_block{block_index}.conv_{conv_index}.{param}"] = \ | ||
dpt_model_dict.pop(f"scratch.refinenet{4 - layer_index}.resConfUnit{block_index}.conv{conv_index}.{param}") | ||
|
||
dpt_model_dict[f"decoder.reassemble_blocks.{layer_index}.project_to_feature_dim.{param}"] = \ | ||
dpt_model_dict.pop(f"scratch.layer{layer_index + 1}_rn.{param}") | ||
|
||
dpt_model_dict[f"decoder.fusion_blocks.{layer_index}.project.{param}"] = \ | ||
dpt_model_dict.pop(f"scratch.refinenet{4 - layer_index}.out_conv.{param}") | ||
|
||
dpt_model_dict[f"decoder.projection_blocks.{layer_index}.project.0.{param}"] = \ | ||
dpt_model_dict.pop(f"pretrained.act_postprocess{layer_index + 1}.0.project.0.{param}") | ||
|
||
dpt_model_dict[f"decoder.reassemble_blocks.{layer_index}.project_to_out_channel.{param}"] = \ | ||
dpt_model_dict.pop(f"pretrained.act_postprocess{layer_index + 1}.3.{param}") | ||
|
||
if layer_index != 2: | ||
dpt_model_dict[f"decoder.reassemble_blocks.{layer_index}.upsample.{param}"] = \ | ||
dpt_model_dict.pop(f"pretrained.act_postprocess{layer_index + 1}.4.{param}") | ||
|
||
# Changing state dict keys for segmentation head | ||
dpt_model_dict = { | ||
name.replace("scratch.output_conv", "segmentation_head.head"): parameter | ||
for name, parameter in dpt_model_dict.items() | ||
} | ||
|
||
# Changing state dict keys for encoder layers | ||
dpt_model_dict = { | ||
name.replace("pretrained.model", "encoder.model"): parameter | ||
for name, parameter in dpt_model_dict.items() | ||
} | ||
|
||
# Removing keys, value pairs associated with auxiliary head | ||
dpt_model_dict = { | ||
name: parameter | ||
for name, parameter in dpt_model_dict.items() | ||
if not name.startswith("auxlayer") | ||
} | ||
# fmt: on | ||
|
||
smp_model.load_state_dict(dpt_model_dict, strict=True) | ||
|
||
# ------- DO NOT touch this section ------- | ||
smp_model.eval() | ||
|
||
input_tensor = torch.ones((1, 3, 384, 384)) | ||
output = smp_model(input_tensor) | ||
|
||
print(output.shape) | ||
print(output[0, 0, :3, :3]) | ||
|
||
expected_slice = torch.tensor( | ||
[ | ||
[3.4243, 3.4553, 3.4863], | ||
[3.3332, 3.2876, 3.2419], | ||
[3.2422, 3.1199, 2.9975], | ||
] | ||
) | ||
|
||
torch.testing.assert_close( | ||
output[0, 0, :3, :3], expected_slice, atol=1e-4, rtol=1e-4 | ||
) | ||
|
||
# Saving | ||
transform = get_transform() | ||
|
||
transform.save_pretrained(HF_HUB_PATH) | ||
smp_model.save_pretrained(HF_HUB_PATH, push_to_hub=PUSH_TO_HUB) | ||
|
||
# Re-loading to make sure everything is saved correctly | ||
smp_model = smp.from_pretrained(HF_HUB_PATH) |
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,3 @@ | ||
from .model import DPT | ||
|
||
__all__ = ["DPT"] |
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.
Should we check only if we got an exception here?
Would it be better to make two independent checks?
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.
If you check the behaviour of functions
check_features_and_reduction
andvalid_vit_encoder_for_dpt
, their output is mutually exclusive. To be more detailed:check_features_and_reduction
returns true only when reduction scales of a model are equal to[2, 4, 8, 16, 32]
, whereas,valid_vit_encoder_for_dpt
returns false if the encoder has multiple reduction scales.In short, a model which satisfies the conditions specified by
check_features_and_reduction
will never satisfy the conditions set byvalid_vit_encoder_for_dpt
and vice versa.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.
Ok, I suppose this code should be updated as well, because as far as I remember [4, 8, 16, 32] and [1, 2, 4, 8, 16, 32] reductions are also supported
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.
Should I update this as well or will you do it from your end?