-
Notifications
You must be signed in to change notification settings - Fork 355
fix: MaskedCausalVisionTransformer build on all supported timm versions #2043
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
gabrielfruet
merged 2 commits into
lightly-ai:master
from
lorinczszabolcs:fix-masked-causal-vit-attention-kwargs
Aug 21, 2026
Merged
Changes from all commits
Commits
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
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
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
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
98 changes: 98 additions & 0 deletions
98
tests/models/modules/test_masked_causal_vision_transformer.py
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,98 @@ | ||
| import pytest | ||
| import torch | ||
|
|
||
| from lightly.utils import dependency | ||
|
|
||
| if not dependency.timm_vit_available(): | ||
| # We do not use pytest.importorskip on module level because it makes mypy unhappy. | ||
| pytest.skip("TIMM vision transformer is not available", allow_module_level=True) | ||
|
|
||
| from lightly.models.modules.masked_causal_vision_transformer import ( | ||
| MaskedCausalAttention, | ||
| MaskedCausalBlock, | ||
| MaskedCausalVisionTransformer, | ||
| ) | ||
|
|
||
| # MaskedCausalAttention supports only fused attention, which needs | ||
| # torch.nn.functional.scaled_dot_product_attention (PyTorch >=2.0). | ||
| skip_without_fused_attention = pytest.mark.skipif( | ||
| not hasattr(torch.nn.functional, "scaled_dot_product_attention"), | ||
| reason="MaskedCausalAttention supports only fused attention (PyTorch >=2.0).", | ||
| ) | ||
|
|
||
|
|
||
| class TestMaskedCausalBlock: | ||
| def test_init__forwards_only_attention_kwargs(self) -> None: | ||
| # Block-level kwargs such as mlp_ratio must not reach the attention layer. | ||
| block = MaskedCausalBlock(dim=24, num_heads=3, mlp_ratio=4.0, qkv_bias=True) | ||
| assert isinstance(block.attn, MaskedCausalAttention) | ||
| # The mlp_ratio is still applied to the block's mlp, not dropped. | ||
| fc1 = block.mlp.fc1 | ||
| assert isinstance(fc1, torch.nn.Linear) | ||
| assert fc1.out_features == 24 * 4 | ||
|
|
||
|
|
||
| class TestMaskedCausalVisionTransformer: | ||
| def test_init(self) -> None: | ||
| model = MaskedCausalVisionTransformer( | ||
| img_size=32, | ||
| patch_size=16, | ||
| embed_dim=24, | ||
| depth=2, | ||
| num_heads=3, | ||
| mlp_ratio=4.0, | ||
| ) | ||
| assert all( | ||
| isinstance(block.attn, MaskedCausalAttention) for block in model.blocks | ||
| ) | ||
|
|
||
| @skip_without_fused_attention | ||
| def test_init__aim_config(self) -> None: | ||
| # The AIM examples build the backbone without a class token and with | ||
| # average pooling. timm asserts global_pool != "token" when class_token is | ||
| # False, so both settings are required for the backbone to build. | ||
| model = MaskedCausalVisionTransformer( | ||
| img_size=32, | ||
| patch_size=16, | ||
| embed_dim=24, | ||
| depth=2, | ||
| num_heads=3, | ||
| class_token=False, | ||
| no_embed_class=True, | ||
| global_pool="avg", | ||
| ) | ||
| assert all( | ||
| isinstance(block.attn, MaskedCausalAttention) for block in model.blocks | ||
| ) | ||
| images = torch.rand(2, 3, 32, 32) | ||
| sequence_length = (32 // 16) ** 2 + model.num_prefix_tokens | ||
| mask = torch.zeros(2, sequence_length, dtype=torch.bool) | ||
| mask[:, model.num_prefix_tokens :] = True | ||
| features = model.forward_features(images, mask=mask) | ||
| assert features.shape == (2, sequence_length, 24) | ||
|
|
||
| @skip_without_fused_attention | ||
| def test_forward(self) -> None: | ||
| model = MaskedCausalVisionTransformer( | ||
| img_size=32, patch_size=16, embed_dim=24, depth=2, num_heads=3 | ||
| ) | ||
| images = torch.rand(2, 3, 32, 32) | ||
| features = model.forward_features(images) | ||
| sequence_length = (32 // 16) ** 2 + model.num_prefix_tokens | ||
| assert features.shape == (2, sequence_length, 24) | ||
|
|
||
| @skip_without_fused_attention | ||
| def test_forward__with_mask(self) -> None: | ||
| model = MaskedCausalVisionTransformer( | ||
| img_size=32, patch_size=16, embed_dim=24, depth=2, num_heads=3 | ||
| ) | ||
| images = torch.rand(2, 3, 32, 32) | ||
| sequence_length = (32 // 16) ** 2 + model.num_prefix_tokens | ||
| mask = torch.zeros(2, sequence_length, dtype=torch.bool) | ||
| mask[:, model.num_prefix_tokens :] = True | ||
|
|
||
| features = model.forward_features(images, mask=mask) | ||
| features_no_mask = model.forward_features(images) | ||
| assert features.shape == (2, sequence_length, 24) | ||
| # The mask switches the patch tokens to causal attention and changes the output. | ||
| assert not torch.allclose(features, features_no_mask) |
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.
Uh oh!
There was an error while loading. Please reload this page.