-
Notifications
You must be signed in to change notification settings - Fork 647
Visual Encoders (ViT, DeiT) Support Rollout #1546
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
Changes from all commits
Commits
Show all changes
77 commits
Select commit
Hold shift + click to select a range
4903efb
Add ViTArchitectureAdapter to supported architectures
david-wei-01001 2172e71
Add ViTArchitectureAdapter to architecture factory
david-wei-01001 5f893f5
Add ViT and DeiT models to model registry
david-wei-01001 d3513ae
Add new model descriptions for Vision Transformers and Wav2Vec2
david-wei-01001 75c9d2c
Add ViTArchitectureAdapter for vision models
david-wei-01001 a9956fd
Create vision_embedings.py
david-wei-01001 33601d9
Add VisionClassifierHeadBridge for CLS token classification
david-wei-01001 7bbeeaf
Add visual model configuration to transformer bridge
david-wei-01001 cc5713b
Clarify pixel_values usage for multimodal and vision models
david-wei-01001 7cd2393
Update bridge.py
david-wei-01001 7974c6f
Update bridge.py
david-wei-01001 03b9af6
Rename vision_embedings.py to vision_embeddings.py
david-wei-01001 11ed7c3
Define vision model and classification architectures
david-wei-01001 3b245fb
Add support for vision architectures in transformers
david-wei-01001 6d2ade6
Refactor VisionClassifierHeadBridge to use pooled output
david-wei-01001 db6a4ad
Update vit.py
david-wei-01001 bdf0333
Add unit tests for ViTArchitectureAdapter
david-wei-01001 078ff22
Create test_vit_adapter.py
david-wei-01001 62cc5b4
Update transformers.py
david-wei-01001 0c6ba10
Update vit.py
david-wei-01001 33cf0e4
Update vit.py
david-wei-01001 07971b7
Update vit.py
david-wei-01001 0f80c9e
Fix type hint for get_remote_component method
david-wei-01001 9c63445
Fix type hint for get_remote_component method
david-wei-01001 c58f962
Change import of torch to torch.nn in vit.py
david-wei-01001 4de1446
Update vit.py
david-wei-01001 fc86e45
Re-add dummy 'mlp' attribute injection for ViTLayer
david-wei-01001 161eebb
Refactor ViTLayer handling by removing patch_layers
david-wei-01001 d3d14c9
Add dummy 'mlp' attribute to ViTLayer blocks
david-wei-01001 792cc22
Update vit.py
david-wei-01001 ef7305d
Remove TestViTConfigNCtx and related test case
david-wei-01001 a91f2ab
Enhance ViTLayer with MLP wrapper and fix forward method
david-wei-01001 8dd96fc
Refactor ViT layer forward pass handling
david-wei-01001 071784d
Refactor ViTLayer forward pass handling
david-wei-01001 430d29b
Fix tuple handling in ViTLayer forward method
david-wei-01001 5e0cbbc
Reorder model prefix checks for better clarity
david-wei-01001 80a11af
Update vit.py
david-wei-01001 ad660b7
Detect model class name in prepare_model method
david-wei-01001 1d2f60d
Simplify prefix determination for ViT models
david-wei-01001 9ee506e
Implement fixture for distilled DeiT model testing
david-wei-01001 d3e4b59
Update DeiT bridge tests for bare model handling
david-wei-01001 c9b6c95
Set architecture in Hugging Face model configuration
david-wei-01001 331cb5b
Support DeiTLayer in patch_layers function
david-wei-01001 f8c6bb9
sort
david-wei-01001 1e9ac7d
Replace direct attribute assignment with setattr
david-wei-01001 32e6c9f
black fix
david-wei-01001 52b5213
fix formatting after merge
david-wei-01001 473253e
Update vit.py
david-wei-01001 ca71899
Update ViT adapter test paths for consistency
david-wei-01001 4088646
Remove redundant test for n_ctx in prepare_loading
david-wei-01001 5b970a5
black sorted
david-wei-01001 a30ee28
解冲突: 合并 upstream/dev 到 vit 分支
david-wei-01001 ddc2bad
Merge branch 'dev' into vit
jlarson4 26ebfb4
black reorder
david-wei-01001 92f8eba
Merge branch 'dev' into vit
david-wei-01001 df2c598
Refactor vit_bridge and vit_bare_bridge fixtures
david-wei-01001 e188901
temp support up to transformers 5.8.0
david-wei-01001 5d02a74
support transformers 5.13.0
david-wei-01001 7f48011
format fixed. Unit test all passed. Intergration test all passed. sho…
david-wei-01001 01ad336
Update vit.py
david-wei-01001 84fb3da
Clarify tokenizer support in ViTArchitectureAdapter
david-wei-01001 655f6e1
Remove head_dim assignment from hf_config
david-wei-01001 0c5fe6c
Update vit.py
david-wei-01001 8414789
Update bridge.py
david-wei-01001 9197869
Add VisionEmbeddingsBridge and VisionClassifierHeadBridge
david-wei-01001 57ce0db
Update test_vit_adapter.py
david-wei-01001 fef6967
Update test_vit_adapter.py
david-wei-01001 b6dd32b
Update test_vit_adapter.py
david-wei-01001 357eea6
Update test_vit_adapter.py
david-wei-01001 b0bdead
Improve compatibility mode error and output handling
david-wei-01001 6d1f36d
Refactor test to check output type and shape
david-wei-01001 e2156bf
Update bridge.py
david-wei-01001 bd025d5
Update test_vit_adapter.py
david-wei-01001 815e8f1
Remove obsolete tests from TestViTPrepareLoading
david-wei-01001 eee85af
Update test_vit_adapter.py
david-wei-01001 e5b1795
Update test_vit_adapter.py
david-wei-01001 f18a333
formatted
david-wei-01001 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
Large diffs are not rendered by default.
Oops, something went wrong.
359 changes: 359 additions & 0 deletions
359
tests/unit/model_bridge/supported_architectures/test_vit_adapter.py
Large diffs are not rendered by default.
Oops, something went wrong.
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
37 changes: 37 additions & 0 deletions
37
transformer_lens/model_bridge/generalized_components/vision_classifier_head.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,37 @@ | ||
| """CLS-token classifier head bridge component. | ||
|
|
||
| HF's ViTForImageClassification.forward() / DeiTForImageClassification.forward() | ||
| already pool the CLS token before calling self.classifier: | ||
|
|
||
| sequence_output = outputs.last_hidden_state | ||
| pooled_output = sequence_output[:, 0, :] | ||
| logits = self.classifier(pooled_output) | ||
|
|
||
| So this component only ever receives an already-pooled (batch, hidden) tensor. | ||
| No slicing needed here — this is a thin, hook-named pass-through. | ||
|
|
||
| Deliberately NOT covering DeiTForImageClassificationWithTeacher (dual | ||
| cls_classifier + distillation_classifier head) — see vit.py's docstring. | ||
| """ | ||
|
|
||
| from typing import Any | ||
|
|
||
| from torch import Tensor | ||
|
|
||
| from transformer_lens.model_bridge.generalized_components.base import ( | ||
| GeneralizedComponent, | ||
| ) | ||
|
|
||
|
|
||
| class VisionClassifierHeadBridge(GeneralizedComponent): | ||
| """Wraps the classifier nn.Linear that HF calls with an already-pooled CLS token.""" | ||
|
|
||
| def forward(self, pooled_output: Tensor, **kwargs: Any) -> Tensor: | ||
| original_component = self.original_component | ||
| if original_component is None: | ||
| raise RuntimeError( | ||
| f"Original component not set for {self.name}. Call set_original_component() first." | ||
| ) | ||
| pooled_output = self.hook_in(pooled_output) | ||
| logits = original_component(pooled_output) | ||
| return self.hook_out(logits) |
64 changes: 64 additions & 0 deletions
64
transformer_lens/model_bridge/generalized_components/vision_embeddings.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,64 @@ | ||
| """Vision (ViT-style) embeddings bridge component. | ||
|
|
||
| Wraps a HF `ViTEmbeddings` / `DeiTEmbeddings` module directly and forwards through | ||
| it unmodified. The patch-conv projection, CLS-token (and, for DeiT, distillation- | ||
| token) concatenation, and position-embedding addition are HF's math — we don't | ||
| reimplement any of it, we just point at the real module and hook its input/output. | ||
|
|
||
| Why one class covers both ViT and DeiT: `ViTEmbeddings.forward` and | ||
| `DeiTEmbeddings.forward` have an *identical* signature | ||
| (pixel_values, bool_masked_pos=None, interpolate_pos_encoding=False) | ||
| The only structural difference between them (DeiT prepends a distillation token | ||
| in addition to CLS, and sizes `position_embeddings` for +2 slots instead of +1) | ||
| lives entirely inside whichever module `set_original_component` resolves to — it's | ||
| invisible to this wrapper, so no DeiT-specific branching is needed here. | ||
|
|
||
| Verified against the real generalized_components/base.py (not extrapolated): | ||
| `GeneralizedComponent.forward(*args, **kwargs)` already does exactly what we need | ||
| — it hooks the input via `self.hook_in`, casts it to match the wrapped module's | ||
| own parameter dtype (equivalent to HF's own `pixel_values.to(expected_dtype)` | ||
| "kept for BC" cast in ViTModel.forward — both land on the same dtype in the | ||
| overwhelming common case of a non-mixed-precision checkpoint), calls | ||
| `self.original_component(*args, **kwargs)`, and hooks the output via | ||
| `self.hook_out`. So this subclass only needs to guarantee `pixel_values` reaches | ||
| `super().forward()` *positionally* — the base class's own kwarg-name sniffing | ||
| list (`input`, `hidden_states`, `input_ids`, `query_input`, `x`, `inputs_embeds`) | ||
| doesn't include `pixel_values`, so if this component were ever called | ||
| all-keyword (`self.embeddings(pixel_values=x, ...)`, unlike the two HF call | ||
| sites we've confirmed) the base class's hook_in would silently never fire. | ||
| Re-emitting positionally here closes that gap regardless of how *we* were | ||
| called. | ||
| """ | ||
|
|
||
| from typing import Any, Optional | ||
|
|
||
| import torch | ||
| from torch import Tensor | ||
|
|
||
| from transformer_lens.model_bridge.generalized_components.base import ( | ||
| GeneralizedComponent, | ||
| ) | ||
|
|
||
|
|
||
| class VisionEmbeddingsBridge(GeneralizedComponent): | ||
| """Bridge for ViTEmbeddings / DeiTEmbeddings. | ||
|
|
||
| Point `name=` at the embeddings module directly, e.g.: | ||
| VisionEmbeddingsBridge(name="embeddings") # bare ViTModel/DeiTModel | ||
| VisionEmbeddingsBridge(name="vit.embeddings") # ViTForImageClassification | ||
| VisionEmbeddingsBridge(name="deit.embeddings") # DeiTForImageClassification | ||
| """ | ||
|
|
||
| def forward( | ||
| self, | ||
| pixel_values: Tensor, | ||
| bool_masked_pos: Optional[torch.BoolTensor] = None, | ||
| interpolate_pos_encoding: Optional[bool] = None, | ||
| **kwargs: Any, | ||
| ) -> Tensor: | ||
| return super().forward( | ||
| pixel_values, | ||
| bool_masked_pos=bool_masked_pos, | ||
| interpolate_pos_encoding=interpolate_pos_encoding, | ||
| **kwargs, | ||
| ) |
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
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.
Uh oh!
There was an error while loading. Please reload this page.