Skip to content

Fix positional embedding resampling for non-square inputs in ViT #2317

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 3 commits into from
Nov 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion timm/models/deit.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,11 @@ def set_distilled_training(self, enable=True):
def _pos_embed(self, x):
if self.dynamic_img_size:
B, H, W, C = x.shape
prev_grid_size = self.patch_embed.grid_size
pos_embed = resample_abs_pos_embed(
self.pos_embed,
(H, W),
new_size=(H, W),
old_size=prev_grid_size,
num_prefix_tokens=0 if self.no_embed_class else self.num_prefix_tokens,
)
x = x.view(B, -1, C)
Expand Down
4 changes: 3 additions & 1 deletion timm/models/eva.py
Original file line number Diff line number Diff line change
Expand Up @@ -560,9 +560,11 @@ def _pos_embed(self, x) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
if self.dynamic_img_size:
B, H, W, C = x.shape
if self.pos_embed is not None:
prev_grid_size = self.patch_embed.grid_size
pos_embed = resample_abs_pos_embed(
self.pos_embed,
(H, W),
new_size=(H, W),
old_size=prev_grid_size,
num_prefix_tokens=self.num_prefix_tokens,
)
else:
Expand Down
4 changes: 3 additions & 1 deletion timm/models/vision_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -669,9 +669,11 @@ def _pos_embed(self, x: torch.Tensor) -> torch.Tensor:

if self.dynamic_img_size:
B, H, W, C = x.shape
prev_grid_size = self.patch_embed.grid_size
pos_embed = resample_abs_pos_embed(
self.pos_embed,
(H, W),
new_size=(H, W),
old_size=prev_grid_size,
num_prefix_tokens=0 if self.no_embed_class else self.num_prefix_tokens,
)
x = x.view(B, -1, C)
Expand Down
Loading