Source code for towhee.models.utils.get_relative_position_index

# Original pytorch implementation by:
# 'MaxViT: Multi-Axis Vision Transformer'
#       - https://arxiv.org/pdf/2204.01697.pdf
# Original code by / Copyright 2021, Christoph Reich.
# Modifications & additions by / Copyright 2022 Zilliz. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch


[docs]def get_relative_position_index( win_h: int, win_w: int ) -> torch.Tensor: """ Function to generate pair-wise relative position index for each token inside the window. Taken from Timms Swin V1 implementation. Args: win_h (int): Window/Grid height. win_w (int): Window/Grid width. Returns: relative_coords (torch.Tensor): Pair-wise relative position indexes [height * width, height * width]. """ coords = torch.stack(torch.meshgrid([torch.arange(win_h), torch.arange(win_w)])) coords_flatten = torch.flatten(coords, 1) relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] relative_coords = relative_coords.permute(1, 2, 0).contiguous() relative_coords[:, :, 0] += win_h - 1 relative_coords[:, :, 1] += win_w - 1 relative_coords[:, :, 0] *= 2 * win_w - 1 return relative_coords.sum(-1)