Cuiunbo commited on
Commit
c8011f9
1 Parent(s): 9909305

Upload resampler.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. resampler.py +171 -0
resampler.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import partial
2
+ import numpy as np
3
+
4
+ import torch
5
+ from torch import nn
6
+ # from torch.nn.init import trunc_normal_
7
+
8
+ def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
9
+ # Convert tensor to float32
10
+ tensor = tensor.float()
11
+ with torch.no_grad():
12
+ tensor.normal_(mean, std)
13
+ valid = (tensor > a) & (tensor < b)
14
+ ind = valid.max()
15
+ tensor = tensor[ind].uniform_(a, b)
16
+ return tensor.half()
17
+
18
+ def get_2d_sincos_pos_embed(embed_dim, image_size):
19
+ """
20
+ image_size: image_size or (image_height, image_width)
21
+ return:
22
+ pos_embed: [image_height, image_width, embed_dim]
23
+ """
24
+ if isinstance(image_size, int):
25
+ grid_h_size, grid_w_size = image_size, image_size
26
+ else:
27
+ grid_h_size, grid_w_size = image_size[0], image_size[1]
28
+
29
+ grid_h = np.arange(grid_h_size, dtype=np.float32)
30
+ grid_w = np.arange(grid_w_size, dtype=np.float32)
31
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
32
+ grid = np.stack(grid, axis=0)
33
+
34
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
35
+ return pos_embed
36
+
37
+
38
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
39
+ assert embed_dim % 2 == 0
40
+
41
+ # use half of dimensions to encode grid_h
42
+ emb_h = get_1d_sincos_pos_embed_from_grid_new(embed_dim // 2, grid[0]) # (H, W, D/2)
43
+ emb_w = get_1d_sincos_pos_embed_from_grid_new(embed_dim // 2, grid[1]) # (H, W, D/2)
44
+
45
+ emb = np.concatenate([emb_h, emb_w], axis=-1) # (H, W, D)
46
+ return emb
47
+
48
+ def get_1d_sincos_pos_embed_from_grid_new(embed_dim, pos):
49
+ """
50
+ embed_dim: output dimension for each position
51
+ pos: a list of positions to be encoded: size (H, W)
52
+ out: (H, W, D)
53
+ """
54
+ assert embed_dim % 2 == 0
55
+ omega = np.arange(embed_dim // 2, dtype=np.float32)
56
+ omega /= embed_dim / 2.
57
+ omega = 1. / 10000 ** omega # (D/2,)
58
+
59
+ out = np.einsum('hw,d->hwd', pos, omega) # (H, W, D/2), outer product
60
+
61
+ emb_sin = np.sin(out) # (H, W, D/2)
62
+ emb_cos = np.cos(out) # (H, W, D/2)
63
+
64
+ emb = np.concatenate([emb_sin, emb_cos], axis=-1) # (H, W, D)
65
+ return emb
66
+
67
+ class Resampler(nn.Module):
68
+ """
69
+ A 2D perceiver-resampler network with one cross attention layers by
70
+ given learnable queries and 2d sincos pos_emb
71
+ Outputs:
72
+ A tensor with the shape of (batch_size, num_queries, embed_dim)
73
+ """
74
+
75
+ def __init__(
76
+ self,
77
+ num_queries,
78
+ embed_dim,
79
+ num_heads,
80
+ kv_dim=None,
81
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
82
+ adaptive=False,
83
+ max_size=(70, 70),
84
+ ):
85
+ super().__init__()
86
+ self.num_queries = num_queries
87
+ self.embed_dim = embed_dim
88
+ self.num_heads = num_heads
89
+ self.adaptive = adaptive
90
+ self.max_size = max_size
91
+
92
+ self.query = nn.Parameter(torch.zeros(self.num_queries, embed_dim))
93
+ trunc_normal_(self.query, std=.02)
94
+
95
+ if kv_dim is not None and kv_dim != embed_dim:
96
+ self.kv_proj = nn.Linear(kv_dim, embed_dim, bias=False)
97
+ else:
98
+ self.kv_proj = nn.Identity()
99
+
100
+ self.attn = nn.MultiheadAttention(embed_dim, num_heads)
101
+ self.ln_q = norm_layer(embed_dim)
102
+ self.ln_kv = norm_layer(embed_dim)
103
+
104
+ self.ln_post = norm_layer(embed_dim)
105
+ self.proj = nn.Parameter((embed_dim ** -0.5) * torch.randn(embed_dim, embed_dim))
106
+
107
+ self._set_2d_pos_cache(self.max_size)
108
+ self.apply(self._init_weights)
109
+
110
+ def _set_2d_pos_cache(self, max_size, device='cpu'):
111
+ pos_embed = torch.from_numpy(get_2d_sincos_pos_embed(self.embed_dim, max_size)).float().to(device)
112
+ self.register_buffer("pos_embed", pos_embed, persistent=False)
113
+
114
+ def _adjust_pos_cache(self, tgt_sizes, device):
115
+ max_h = torch.max(tgt_sizes[:, 0])
116
+ max_w = torch.max(tgt_sizes[:, 1])
117
+ if max_h > self.max_size[0] or max_w > self.max_size[1]:
118
+ self.max_size = [max(max_h, self.max_size[0]), max(max_w, self.max_size[1])]
119
+ self._set_2d_pos_cache(self.max_size, device)
120
+
121
+ def _init_weights(self, m):
122
+ if isinstance(m, nn.Linear):
123
+ trunc_normal_(m.weight, std=.02)
124
+ if isinstance(m, nn.Linear) and m.bias is not None:
125
+ nn.init.constant_(m.bias, 0)
126
+ elif isinstance(m, nn.LayerNorm):
127
+ nn.init.constant_(m.bias, 0)
128
+ nn.init.constant_(m.weight, 1.0)
129
+
130
+ def forward(self, x, tgt_sizes=None):
131
+ assert x.shape[0] == tgt_sizes.shape[0]
132
+ bs = x.shape[0]
133
+
134
+ device = x.device
135
+ dtype = x.dtype
136
+
137
+ patch_len = tgt_sizes[:, 0] * tgt_sizes[:, 1]
138
+
139
+ self._adjust_pos_cache(tgt_sizes, device=device)
140
+
141
+ max_patch_len = torch.max(patch_len)
142
+ key_padding_mask = torch.zeros((bs, max_patch_len), dtype=torch.bool, device=device)
143
+
144
+ pos_embed = []
145
+ for i in range(bs):
146
+ tgt_h, tgt_w = tgt_sizes[i]
147
+ pos_embed.append(self.pos_embed[:tgt_h, :tgt_w, :].reshape((tgt_h * tgt_w, -1)).to(dtype)) # patches * D
148
+ key_padding_mask[i, patch_len[i]:] = True
149
+
150
+ pos_embed = torch.nn.utils.rnn.pad_sequence(
151
+ pos_embed, batch_first=True, padding_value=0.0).permute(1, 0, 2) # BLD => L * B * D
152
+
153
+ x = self.kv_proj(x) # B * L * D
154
+ x = self.ln_kv(x).permute(1, 0, 2) # L * B * D
155
+
156
+ q = self.ln_q(self.query) # Q * D
157
+
158
+ out = self.attn(
159
+ self._repeat(q, bs), # Q * B * D
160
+ x + pos_embed, # L * B * D + L * B * D
161
+ x,
162
+ key_padding_mask=key_padding_mask)[0]
163
+ # out: Q * B * D
164
+ x = out.permute(1, 0, 2) # B * Q * D
165
+
166
+ x = self.ln_post(x)
167
+ x = x @ self.proj
168
+ return x
169
+
170
+ def _repeat(self, query, N: int):
171
+ return query.unsqueeze(1).repeat(1, N, 1)