xdecoder/Instruct-X-Decoder
163
1# Copyright (c) Facebook, Inc. and its affiliates.2## Modified by Bowen Cheng from: https://github.com/facebookresearch/detr/blob/master/models/position_encoding.py3"""4Various positional encodings for the transformer.5"""6import math7 8import torch9from torch import nn10 11 12class PositionEmbeddingSine(nn.Module):13 """14 This is a more standard version of the position embedding, very similar to the one15 used by the Attention is all you need paper, generalized to work on images.16 """17 18 def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None):19 super().__init__()20 self.num_pos_feats = num_pos_feats21 self.temperature = temperature22 self.normalize = normalize23 if scale is not None and normalize is False:24 raise ValueError("normalize should be True if scale is passed")25 if scale is None:26 scale = 2 * math.pi27 self.scale = scale28 29 def forward(self, x, mask=None):30 if mask is None:31 mask = torch.zeros((x.size(0), x.size(2), x.size(3)), device=x.device, dtype=torch.bool)32 not_mask = ~mask33 y_embed = not_mask.cumsum(1, dtype=x.dtype)34 x_embed = not_mask.cumsum(2, dtype=x.dtype)35 if self.normalize:36 eps = 1e-637 y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale38 x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale39 40 dim_t = torch.arange(self.num_pos_feats, dtype=x.dtype, device=x.device)41 dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)42 43 pos_x = x_embed[:, :, :, None] / dim_t44 pos_y = y_embed[:, :, :, None] / dim_t45 pos_x = torch.stack(46 (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=447 ).flatten(3)48 pos_y = torch.stack(49 (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=450 ).flatten(3)51 pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)52 return pos53 54 def __repr__(self, _repr_indent=4):55 head = "Positional encoding " + self.__class__.__name__56 body = [57 "num_pos_feats: {}".format(self.num_pos_feats),58 "temperature: {}".format(self.temperature),59 "normalize: {}".format(self.normalize),60 "scale: {}".format(self.scale),61 ]62 # _repr_indent = 463 lines = [head] + [" " * _repr_indent + line for line in body]64 return "\n".join(lines)65 