Skip to content

Commit 9caf32b

Browse files
committed
Move levit style pos bias resize with other rel pos bias utils
1 parent 63417b4 commit 9caf32b

File tree

4 files changed

+45
-46
lines changed

4 files changed

+45
-46
lines changed

timm/layers/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,9 @@
3636
from .patch_dropout import PatchDropout
3737
from .patch_embed import PatchEmbed, PatchEmbedWithSize, resample_patch_embed
3838
from .pool2d_same import AvgPool2dSame, create_pool2d
39-
from .pos_embed import resample_abs_pos_embed, resample_abs_pos_embed_nhwc, resample_relative_position_bias_table
39+
from .pos_embed import resample_abs_pos_embed, resample_abs_pos_embed_nhwc
4040
from .pos_embed_rel import RelPosMlp, RelPosBias, RelPosBiasTf, gen_relative_position_index, gen_relative_log_coords, \
41-
resize_rel_pos_bias_table, resize_rel_pos_bias_table_simple
41+
resize_rel_pos_bias_table, resize_rel_pos_bias_table_simple, resize_rel_pos_bias_table_levit
4242
from .pos_embed_sincos import pixel_freq_bands, freq_bands, build_sincos2d_pos_embed, build_fourier_pos_embed, \
4343
build_rotary_pos_embed, apply_rot_embed, apply_rot_embed_cat, apply_rot_embed_list, apply_keep_indices_nlc, \
4444
FourierEmbed, RotaryEmbedding, RotaryEmbeddingCat

timm/layers/pos_embed.py

Lines changed: 0 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -78,38 +78,3 @@ def resample_abs_pos_embed_nhwc(
7878
_logger.info(f'Resized position embedding: {posemb.shape[-3:-1]} to {new_size}.')
7979

8080
return posemb
81-
82-
83-
def resample_relative_position_bias_table(
84-
position_bias_table,
85-
new_size,
86-
interpolation: str = 'bicubic',
87-
antialias: bool = True,
88-
verbose: bool = False
89-
):
90-
"""
91-
Resample relative position bias table suggested in LeVit
92-
Adapted from: https://github.com/microsoft/Cream/blob/main/TinyViT/utils.py
93-
"""
94-
L1, nH1 = position_bias_table.size()
95-
L2, nH2 = new_size
96-
assert nH1 == nH2
97-
if L1 != L2:
98-
orig_dtype = position_bias_table.dtype
99-
position_bias_table = position_bias_table.float()
100-
# bicubic interpolate relative_position_bias_table if not match
101-
S1 = int(L1 ** 0.5)
102-
S2 = int(L2 ** 0.5)
103-
relative_position_bias_table_resized = F.interpolate(
104-
position_bias_table.permute(1, 0).view(1, nH1, S1, S1),
105-
size=(S2, S2),
106-
mode=interpolation,
107-
antialias=antialias)
108-
relative_position_bias_table_resized = \
109-
relative_position_bias_table_resized.view(nH2, L2).permute(1, 0)
110-
relative_position_bias_table_resized.to(orig_dtype)
111-
if not torch.jit.is_scripting() and verbose:
112-
_logger.info(f'Resized position bias: {L1, nH1} to {L2, nH2}.')
113-
return relative_position_bias_table_resized
114-
else:
115-
return position_bias_table

timm/layers/pos_embed_rel.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,38 @@ def resize_rel_pos_bias_table_simple(
121121
return rel_pos_bias
122122

123123

124+
def resize_rel_pos_bias_table_levit(
125+
position_bias_table,
126+
new_size,
127+
interpolation: str = 'bicubic',
128+
antialias: bool = True,
129+
):
130+
"""
131+
Resample relative position bias table suggested in LeVit
132+
Adapted from: https://github.com/microsoft/Cream/blob/main/TinyViT/utils.py
133+
"""
134+
L1, nH1 = position_bias_table.size()
135+
L2, nH2 = new_size
136+
assert nH1 == nH2
137+
if L1 != L2:
138+
orig_dtype = position_bias_table.dtype
139+
position_bias_table = position_bias_table.float()
140+
# bicubic interpolate relative_position_bias_table if not match
141+
S1 = int(L1 ** 0.5)
142+
S2 = int(L2 ** 0.5)
143+
relative_position_bias_table_resized = F.interpolate(
144+
position_bias_table.permute(1, 0).view(1, nH1, S1, S1),
145+
size=(S2, S2),
146+
mode=interpolation,
147+
antialias=antialias)
148+
relative_position_bias_table_resized = \
149+
relative_position_bias_table_resized.view(nH2, L2).permute(1, 0)
150+
relative_position_bias_table_resized.to(orig_dtype)
151+
return relative_position_bias_table_resized
152+
else:
153+
return position_bias_table
154+
155+
124156
def resize_rel_pos_bias_table(
125157
rel_pos_bias,
126158
new_window_size: Tuple[int, int],

timm/models/tiny_vit.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919

2020
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
2121
from timm.layers import LayerNorm2d, NormMlpClassifierHead, DropPath,\
22-
to_2tuple, trunc_normal_, resample_relative_position_bias_table, use_fused_attn
22+
trunc_normal_, resize_rel_pos_bias_table_levit, use_fused_attn
2323
from ._builder import build_model_with_cfg
2424
from ._manipulate import checkpoint_seq
2525
from ._registry import register_model, generate_default_cfgs
@@ -182,6 +182,7 @@ def __init__(
182182
self.d = int(attn_ratio * key_dim)
183183
self.dh = int(attn_ratio * key_dim) * num_heads
184184
self.attn_ratio = attn_ratio
185+
self.resolution = resolution
185186
self.fused_attn = use_fused_attn()
186187

187188
h = self.dh + nh_kd * 2
@@ -551,17 +552,18 @@ def checkpoint_filter_fn(state_dict, model):
551552
# TODO: temporary use for testing, need change after weight convert
552553
if 'model' in state_dict.keys():
553554
state_dict = state_dict['model']
554-
targe_sd = model.state_dict()
555-
target_keys = list(targe_sd.keys())
555+
target_sd = model.state_dict()
556+
target_keys = list(target_sd.keys())
556557
out_dict = {}
557558
i = 0
558559
for k, v in state_dict.items():
559-
if not k.endswith('attention_bias_idxs'):
560-
if 'attention_biases' in k:
561-
# dynamic window size by resampling relative_position_bias_table
562-
# TODO: whether move this func into model for dynamic input resolution? (high risk)
563-
v = resample_relative_position_bias_table(v.T, targe_sd[target_keys[i]].shape[::-1]).T
564-
out_dict[target_keys[i]] = v
560+
if k.endswith('attention_bias_idxs'):
561+
continue
562+
tk = target_keys[i]
563+
if 'attention_biases' in k:
564+
# TODO: whether move this func into model for dynamic input resolution? (high risk)
565+
v = resize_rel_pos_bias_table_levit(v.T, target_sd[tk].shape[::-1]).T
566+
out_dict[tk] = v
565567
i += 1
566568
return out_dict
567569

0 commit comments

Comments
 (0)