MCPcopy Create free account
hub / github.com/OpenGVLab/HumanBench / calc_rel_pos_spatial

Function calc_rel_pos_spatial

PATH/core/models/backbones/vit.py:131–173  ·  view source on GitHub ↗

Spatial Relative Positional Embeddings. Source: https://github.com/facebookresearch/mvit/

(
        attn,
        q,
        q_shape,
        k_shape,
        rel_pos_h,
        rel_pos_w,
)

Source from the content-addressed store, hash-verified

129
130
131def calc_rel_pos_spatial(
132 attn,
133 q,
134 q_shape,
135 k_shape,
136 rel_pos_h,
137 rel_pos_w,
138):
139 """
140 Spatial Relative Positional Embeddings.
141
142 Source: https://github.com/facebookresearch/mvit/
143 """
144 sp_idx = 0
145 q_h, q_w = q_shape
146 k_h, k_w = k_shape
147
148 # Scale up rel pos if shapes for q and k are different.
149 q_h_ratio = max(k_h / q_h, 1.0)
150 k_h_ratio = max(q_h / k_h, 1.0)
151 dist_h = (torch.arange(q_h)[:, None] * q_h_ratio - torch.arange(k_h)[None, :] * k_h_ratio)
152 dist_h += (k_h - 1) * k_h_ratio
153 q_w_ratio = max(k_w / q_w, 1.0)
154 k_w_ratio = max(q_w / k_w, 1.0)
155 dist_w = (torch.arange(q_w)[:, None] * q_w_ratio - torch.arange(k_w)[None, :] * k_w_ratio)
156 dist_w += (k_w - 1) * k_w_ratio
157
158 Rh = rel_pos_h[dist_h.long()]
159 Rw = rel_pos_w[dist_w.long()]
160
161 B, n_head, q_N, dim = q.shape
162
163 r_q = q[:, :, sp_idx:].reshape(B, n_head, q_h, q_w, dim)
164 rel_h = torch.einsum("byhwc,hkc->byhwk", r_q, Rh)
165 rel_w = torch.einsum("byhwc,wkc->byhwk", r_q, Rw)
166
167 attn[:, :, sp_idx:, sp_idx:] = (
168 attn[:, :, sp_idx:, sp_idx:].view(B, -1, q_h, q_w, k_h, k_w)
169 + rel_h[:, :, :, :, :, None]
170 + rel_w[:, :, :, :, None, :]
171 ).view(B, -1, q_h * q_w, k_h * k_w)
172
173 return attn
174
175
176class WindowAttention(nn.Module):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected