swing transformer中相对位置编码理解

# define a parameter table of relative position bias
self.relative_position_bias_table = nn.Parameter(
	torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads))  # 2*Wh-1 * 2*Ww-1, nH

# https://blog.csdn.net/weixin_40723264/article/details/127632545 the position embedding are added to the attention score
# get pair-wise relative position index for each token inside the window
coords_h = torch.arange(self.window_size[0]) # 纵坐标
coords_w = torch.arange(self.window_size[1]) # 横坐标
coords = torch.stack(torch.meshgrid([coords_h, coords_w]))  # 2, Wh, Ww
coords_flatten = torch.flatten(coords, 1)  # 2, Wh*Ww
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]  # 2, Wh*Ww, Wh*Ww 横坐标之间的差值 以及 纵坐标之间的差值
relative_coords = relative_coords.permute(1, 2, 0).contiguous()  # Wh*Ww, Wh*Ww, 2
relative_coords[:, :, 0] += self.window_size[0] - 1  # shift to start from 0 纵坐标之间的差值最大是 windows_size[0] - 1 取值范围是 [-(m-1), (m-1)] -> [0, 2(m-1)]
relative_coords[:, :, 1] += self.window_size[1] - 1  # 横坐标坐标之间的差值最大是 windows_size[0] - 1
relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 # 让每一行 行列差值相加具有唯一性 由于两者的取值范围都是 [0, 2(m-1)], 所以相加会出现相等的现象
relative_position_index = relative_coords.sum(-1)  # Wh*Ww, Wh*Ww 最大值为 2(m-1)(2m-1)+2(m-1) 最小值为 0 因此一共有 2(m-1)(2m-1)+2(m-1)+1个元素 = (2m-1)(2m-1) = relative_position_bias_table.shape[0]
self.register_buffer("relative_position_index", relative_position_index)

来自https://blog.csdn.net/weixin_40723264/article/details/127632545

图片来源:https://blog.csdn.net/weixin_40723264/article/details/127632545

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值