赞
踩
理解中。。。
接下来深入最难的DeformableTransformer_Det,这个py文件包含了多个class
DeformableTransformer_Det
DeformableTransformerEncoderLayer
DeformableTransformerEncoder
CirConv 环形卷积
DeformableTransformerDecoderLayer_Det
DeformableTransformerDecoder_Det
# adet/layers/deformable_transformer.py
# ------------------------------------------------------------------------
# Deformable DETR
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------
# Modified from DETR (https://github.com/facebookresearch/detr)
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# ------------------------------------------------------------------------PositionalEncoding2D
import copy
import math
import torch
import torch.nn.functional as F
from torch import nn
from torch.nn.init import normal_
from adet.utils.misc import inverse_sigmoid
from adet.modeling.dptext_detr.utils import MLP, gen_point_pos_embed
from .ms_deform_attn import MSDeformAttn # MultiScaleDeformableAttention
from timm.models.layers import DropPath # 这里居然用了timm
class DeformableTransformer_Det(nn.Module):
def __init__(
self,
d_model=256,
nhead=8,
num_encoder_layers=6,
num_decoder_layers=6,
dim_feedforward=1024,
dropout=0.1,
activation="relu",
return_intermediate_dec=False, # 实例化时为True
num_feature_levels=4,
dec_n_points=4,
enc_n_points=4,
num_proposals=100,
num_ctrl_points=16,
epqm=False, # 实例化时为True
efsa=False # 实例化时为True
):
super().__init__()
self.d_model = d_model
self.nhead = nhead
self.num_proposals = num_proposals
# 单层编码器
encoder_layer = DeformableTransformerEncoderLayer(
d_model,
dim_feedforward,
dropout,
activation,
num_feature_levels,
nhead,
enc_n_points
)
# 重复N层编码器
self.encoder = DeformableTransformerEncoder(encoder_layer, num_encoder_layers)
# 单层解码器
decoder_layer = DeformableTransformerDecoderLayer_Det(
d_model,
dim_feedforward,
dropout,
activation,
num_feature_levels,
nhead,
dec_n_points,
efsa
)
# 重复N层解码器
self.decoder = DeformableTransformerDecoder_Det(
decoder_layer,
num_decoder_layers,
return_intermediate_dec,
d_model,
epqm
)
# 4,256。lvl的编码,对2d的PE的补充,用于多尺度场景
self.level_embed = nn.Parameter(torch.Tensor(num_feature_levels, d_model))
self.bbox_class_embed = None # 在models.py中赋予具体方法
self.bbox_embed = None # 在models.py中赋予具体方法
self.enc_output = nn.Linear(d_model, d_model)
self.enc_output_norm = nn.LayerNorm(d_model)
if not epqm:
self.pos_trans = nn.Linear(d_model, d_model)
self.pos_trans_norm = nn.LayerNorm(d_model)
self.num_ctrl_points = num_ctrl_points
self.epqm = epqm
self._reset_parameters()
def _reset_parameters(self):
for p in self.parameters():
if p.dim() > 1:
nn.init.xavier_uniform_(p)
for m in self.modules():
if isinstance(m, MSDeformAttn):
m._reset_parameters()
normal_(self.level_embed)
def get_proposal_pos_embed(self, proposals):
"""
正弦位置编码,一般是正余弦交替的sin(pos/(1000**(2*i/d_model)))、cos(pos/(1000**(2*i/d_model))),其中i为0~d_model/2-1
这里d_model为64
"""
num_pos_feats = 64
temperature = 10000
scale = 2 * math.pi
# 0、1、2、...63
dim_t = torch.arange(num_pos_feats, dtype=torch.float32, device=proposals.device)
# torch.div(dim_t, 2, rounding_mode='trunc') 为0、0、1、1、...31、31
# 1000**(2*(i=0、0、1、1...、31、31)/(d_model=64))
dim_t = temperature ** (2 * torch.div(dim_t, 2, rounding_mode='trunc') / num_pos_feats)
# N, L, 4
proposals = proposals.sigmoid() * scale
# N, L, 4, 64
pos = proposals[:, :, :, None] / dim_t
# N, L, 256
pos = torch.stack((pos[:, :, :, 0::2].sin(), pos[:, :, :, 1::2].cos()), dim=4).flatten(2)
return pos
def gen_encoder_output_proposals(self, memory, memory_padding_mask, spatial_shapes):
"""
对encoder的输出进行nn.Linear(d_model, d_model)及norm处理;用计算而不是模型的方法计算各个lvl的output_proposals,作为基准,这里相当于anchor?,forward再用模型计算偏移
"""
N_, S_, C_ = memory.shape
base_scale = 4.0
proposals = []
_cur = 0
for lvl, (H_, W_) in enumerate(spatial_shapes):
mask_flatten_ = memory_padding_mask[:, _cur:(_cur + H_ * W_)].view(N_, H_, W_, 1)
valid_H = torch.sum(~mask_flatten_[:, :, 0, 0], 1) # 未pad处
valid_W = torch.sum(~mask_flatten_[:, 0, :, 0], 1)
grid_y, grid_x = torch.meshgrid(torch.linspace(0, H_ - 1, H_, dtype=torch.float32, device=memory.device),
torch.linspace(0, W_ - 1, W_, dtype=torch.float32, device=memory.device))
grid = torch.cat([grid_x.unsqueeze(-1), grid_y.unsqueeze(-1)], -1)
scale = torch.cat([valid_W.unsqueeze(-1), valid_H.unsqueeze(-1)], 1).view(N_, 1, 1, 2)
grid = (grid.unsqueeze(0).expand(N_, -1, -1, -1) + 0.5) / scale
# lvl越大,wh越大
wh = torch.ones_like(grid) * 0.05 * (2.0 ** lvl)
proposal = torch.cat((grid, wh), -1).view(N_, -1, 4)
proposals.append(proposal)
_cur += (H_ * W_)
output_proposals = torch.cat(proposals, 1) # cat xywh?
output_proposals_valid = ((output_proposals > 0.01) & (output_proposals < 0.99)).all(-1, keepdim=True)
# sigmoid的反操作
output_proposals = torch.log(output_proposals / (1 - output_proposals))
output_proposals = output_proposals.masked_fill(memory_padding_mask.unsqueeze(-1), float('inf'))
output_proposals = output_proposals.masked_fill(~output_proposals_valid, float('inf'))
output_memory = memory
output_memory = output_memory.masked_fill(memory_padding_mask.unsqueeze(-1), float(0))
output_memory = output_memory.masked_fill(~output_proposals_valid, float(0))
"""
self.enc_output = nn.Linear(d_model, d_model)
self.enc_output_norm = nn.LayerNorm(d_model)
"""
output_memory = self.enc_output_norm(self.enc_output(output_memory))
return output_memory, output_proposals
def get_valid_ratio(self, mask):# 计算wh方向非pad的占比
_, H, W = mask.shape
valid_H = torch.sum(~mask[:, :, 0], 1)
valid_W = torch.sum(~mask[:, 0, :], 1)
valid_ratio_h = valid_H.float() / H
valid_ratio_w = valid_W.float() / W
valid_ratio = torch.stack([valid_ratio_w, valid_ratio_h], -1)
return valid_ratio
def init_control_points_from_anchor(self, reference_points_anchor):
"""
通过box获得16个点,即显示点生成
例子
入参:xywh的torch.tensor([[[0.1,0.1,0.2,0.2]]])
出参:torch.tensor([[[[0.0,0.0]
[0.0286,0.0]
...
[0.2,0.0]
[0.2,0.2]
...
[0.0,0.2]]]])
"""
# reference_points_anchor: bs, nq, 4
# return size:
# - reference_points: (bs, nq, n_pts, 2)
assert reference_points_anchor.shape[-1] == 4
# 这里进行了repeat操作,reference_points 维度为 (bs, nq, n_pts, 4),最后的:2操作将其处理为(bs, nq, n_pts, 2)
reference_points = reference_points_anchor[:, :, None, :].repeat(1, 1, self.num_ctrl_points, 1)
pts_per_side = self.num_ctrl_points // 2 # 一边8个点
# x坐标计算,先算0点的起始坐标,后在1-7位放间距,再通过torch.cumsum计算累积和还原上边界各点坐标,下边界通过上边界取对应值
reference_points[:, :, 0, 0].sub_(reference_points[:, :, 0, 2] / 2)
reference_points[:, :, 1:pts_per_side, 0] = reference_points[:, :, 1:pts_per_side, 2] / (pts_per_side - 1)
reference_points[:, :, :pts_per_side, 0] = torch.cumsum(reference_points[:, :, :pts_per_side, 0], dim=-1)
reference_points[:, :, pts_per_side:, 0] = reference_points[:, :, :pts_per_side, 0].flip(dims=[-1])
# y坐标计算,中心点y值加减半个h
reference_points[:, :, :pts_per_side, 1].sub_(reference_points[:, :, :pts_per_side, 3] / 2)
reference_points[:, :, pts_per_side:, 1].add_(reference_points[:, :, pts_per_side:, 3] / 2)
# :2只保留xy,去掉wh
reference_points = torch.clamp(reference_points[:, :, :, :2], 0, 1)
return reference_points
def forward(self, srcs, masks, pos_embeds, query_embed):
# prepare input for encoder
src_flatten = []
mask_flatten = []
lvl_pos_embed_flatten = []
spatial_shapes = []
# lvl为0、1、2、3,对应4个特征图,做flatten
for lvl, (src, mask, pos_embed) in enumerate(zip(srcs, masks, pos_embeds)):
bs, c, h, w = src.shape
spatial_shape = (h, w)
spatial_shapes.append(spatial_shape) #(4,h, w)
src = src.flatten(2).transpose(1, 2) # (bs, h*w , c)
mask = mask.flatten(1) # (bs, h*w)
pos_embed = pos_embed.flatten(2).transpose(1, 2) # (bs, h*w , c)
# 2d PE+ level PE = 3d PE,注意这里是相加而不是多一维
lvl_pos_embed = pos_embed + self.level_embed[lvl].view(1, 1, -1) # (bs, h*w , c)
lvl_pos_embed_flatten.append(lvl_pos_embed)
src_flatten.append(src) #4个( bs, h*w , c)的list
mask_flatten.append(mask)
# torch.cat(a, 1) 表示将列表a(a的每个元素是tensor)在1维上cat,实现1维是h1*w1+h2*w2+h3*w3+h4*w4
src_flatten = torch.cat(src_flatten, 1)
mask_flatten = torch.cat(mask_flatten, 1)
lvl_pos_embed_flatten = torch.cat(lvl_pos_embed_flatten, 1)
spatial_shapes = torch.as_tensor(spatial_shapes, dtype=torch.long, device=src_flatten.device)
"""
spatial_shapes = torch.tensor([[76,95],[38,48],[19,24],[10,12])
spatial_shapes.new_zeros((1,))=torch.tensor([0]) # 生成单个0
spatial_shapes.prod(1)=torch.tensor([7220,1824,456,120]) # 1方向乘
spatial_shapes.prod(1).cumsum(0)=torch.tensor([7220,9044,9550,9620]) # 0方向加
注意这里 h1*w1+h2*w2+h3*w3+h4*w4= 9620
spatial_shapes.prod(1).cumsum(0)[:-1]=torch.tensor([7220,9044,9550]) # 去掉最后一个
torch.cat((spatial_shapes.new_zeros((1,)), spatial_shapes.prod(1).cumsum(0)[:-1]))=torch.tensor([0,7220,9044,9550]) # 拼接
"""
level_start_index = torch.cat((spatial_shapes.new_zeros((1,)), spatial_shapes.prod(1).cumsum(0)[:-1]))
valid_ratios = torch.stack([self.get_valid_ratio(m) for m in masks], 1)
# 编码器encoder
memory = self.encoder(
src_flatten, # ( bs, h1*w1+h2*w2+h3*w3+h4*w4=9620, c=256)
spatial_shapes, # (4,2) 2是hw的值
level_start_index, # (4)
valid_ratios, # (bs, 4,2)
lvl_pos_embed_flatten, # 3D (bs,h1*w1+h2*w2+h3*w3+h4*w4=9620,c=256)
mask_flatten # (bs,h1*w1+h2*w2+h3*w3+h4*w4)
)
# 编码器输出过线性层及norm,获得预设的proposals(相当于每个位置的anchor),prepare input for decoder
bs, _, c = memory.shape
output_memory, output_proposals = self.gen_encoder_output_proposals(memory, mask_flatten, spatial_shapes)
"""
models.py中
self.bbox_coord = MLP(self.d_model, self.d_model, 4, 3)
self.bbox_class = nn.Linear(self.d_model, self.num_classes)
self.transformer.bbox_class_embed = self.bbox_class
self.transformer.bbox_embed = self.bbox_coord
"""
# 根据编码器输出得到class及box的偏移量,+后得到修正的box
enc_outputs_class = self.bbox_class_embed(output_memory)
enc_outputs_coord_unact = self.bbox_embed(output_memory) + output_proposals
# 根据class得分得到top_self.num_proposals 个参考点
topk = self.num_proposals
topk_proposals = torch.topk(enc_outputs_class[..., 0], topk, dim=1)[1]
topk_coords_unact = torch.gather(enc_outputs_coord_unact, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, 4))
topk_coords_unact = topk_coords_unact.detach()
reference_points = topk_coords_unact.sigmoid() # (bs, nq, 4)
if self.epqm: # 由xywh的box转化为显式的16点坐标
reference_points = self.init_control_points_from_anchor(reference_points) # Prior Points Sampling
else: # 对topk的box进行正弦位置编码,再过线性层、norm
# positional queries
query_pos = self.pos_trans_norm(self.pos_trans(self.get_proposal_pos_embed(topk_coords_unact)))
query_pos = query_pos[:, :, None, :].repeat(1, 1, query_embed.shape[2], 1)
init_reference_out = reference_points # return的初始参考点是编码器输出的topk个box
# learnable control point content queries
query_embed = query_embed.unsqueeze(0).expand(bs, -1, -1, -1)
hs, inter_references = self.decoder(
query_embed, # (bs,n_proposals=100,n_ctrl_points=16,d_model=256) 最后2维是nn.Embedding,其他2维是expand和repeat出来的,即在bs、n_proposals维度上不断重复
reference_points, # epqm时是(bs,nq=100,n_pts=16,2),否则是(bs,nq=100,4)
memory, # bs,h1*w1+h2*w2+h3*w3+h4*w4,c
spatial_shapes, # (4,2) 2是hw的值
level_start_index, # (4)
valid_ratios, # (bs, 4, 2)
query_pos=query_pos if not self.epqm else None, #query_pos为(_,_,256,_)
src_padding_mask=mask_flatten # (bs,h1*w1+h2*w2+h3*w3+h4*w4)
)
inter_references_out = inter_references # return的中间参考点是解码器输出的
return hs, init_reference_out, inter_references_out, enc_outputs_class, enc_outputs_coord_unact
class DeformableTransformerEncoderLayer(nn.Module):
def __init__(
self,
d_model=256,
d_ffn=1024,
dropout=0.1,
activation="relu",
n_levels=4,
n_heads=8,
n_points=4
):
super().__init__()
# self attention
self.self_attn = MSDeformAttn(d_model, n_levels, n_heads, n_points)
self.dropout1 = nn.Dropout(dropout)
self.norm1 = nn.LayerNorm(d_model)
# ffn
self.linear1 = nn.Linear(d_model, d_ffn)
self.activation = _get_activation_fn(activation)
self.dropout2 = nn.Dropout(dropout)
self.linear2 = nn.Linear(d_ffn, d_model)
self.dropout3 = nn.Dropout(dropout)
self.norm2 = nn.LayerNorm(d_model)
@staticmethod
def with_pos_embed(tensor, pos):
return tensor if pos is None else tensor + pos
def forward_ffn(self, src):
src2 = self.linear2(self.dropout2(self.activation(self.linear1(src))))
src = src + self.dropout3(src2)
src = self.norm2(src)
return src
def forward(self, src, pos, reference_points, spatial_shapes, level_start_index, padding_mask=None):
"""
output ( bs, h1*w1+h2*w2+h3*w3+h4*w4=9620, c=256)
pos (bs,h1*w1+h2*w2+h3*w3+h4*w4=9620,c=256)
reference_points [bs,h1*w1+h2*w2+h3*w3+h4*w4,4,2]
spatial_shapes (4,2)
level_start_index (4)
padding_mask (bs,h1*w1+h2*w2+h3*w3+h4*w4)
"""
# self attention
src2 = self.self_attn(
self.with_pos_embed(src, pos), # (bs,h1*w1+h2*w2+h3*w3+h4*w4=9620,c=256) reference_points, #(bs,h1*w1+h2*w2+h3*w3+h4*w4,4,2)
src, # ( bs, h1*w1+h2*w2+h3*w3+h4*w4=9620, c=256)
spatial_shapes, # (4,2)
level_start_index, #(4)
padding_mask # (bs,h1*w1+h2*w2+h3*w3+h4*w4)
)
src = src + self.dropout1(src2)
src = self.norm1(src)
# ffn
src = self.forward_ffn(src)
return src
class DeformableTransformerEncoder(nn.Module):
def __init__(self, encoder_layer, num_layers):
super().__init__()
self.layers = _get_clones(encoder_layer, num_layers)
self.num_layers = num_layers
@staticmethod
def get_reference_points(spatial_shapes, valid_ratios, device):
"""
获得编码器的参考点,
输入维度
spatial_shapes [n_l_level=4,2]
valid_ratios [bs, 4,2]
输出维度[bs,h1*w1+h2*w2+h3*w3+h4*w4,4,2],这里valid_ratios先除后乘,这里我之前有个疑问,都已经h1*w1+h2*w2+h3*w3+h4*w4搞到4个尺度了,为什么还要倒数第二维是4,这里和valid_ratios在不同尺度上不同有关,大是在不同尺度上取偏移点时要得到对应参考点的位置
当H_ =10
torch.linspace(0.5, H_ - 0.5, H_, dtype=torch.float32, device=device)
=torch.tensor(0.5,1.5,2.5,...,9.5)
"""
reference_points_list = []
for lvl, (H_, W_) in enumerate(spatial_shapes): # 0.5是取中间位置?
ref_y, ref_x = torch.meshgrid(torch.linspace(0.5, H_ - 0.5, H_, dtype=torch.float32, device=device),
torch.linspace(0.5, W_ - 0.5, W_, dtype=torch.float32, device=device))
ref_y = ref_y.reshape(-1)[None] / (valid_ratios[:, None, lvl, 1] * H_)
ref_x = ref_x.reshape(-1)[None] / (valid_ratios[:, None, lvl, 0] * W_)
ref = torch.stack((ref_x, ref_y), -1)
reference_points_list.append(ref)
reference_points = torch.cat(reference_points_list, 1) # [bs,h1*w1+h2*w2+h3*w3+h4*w4,2]
reference_points = reference_points[:, :, None] * valid_ratios[:, None] # [bs,h1*w1+h2*w2+h3*w3+h4*w4,4,2]
return reference_points
def forward(self, src, spatial_shapes, level_start_index, valid_ratios, pos=None, padding_mask=None):
"""
入参维度参考,都是展平后的
memory = self.encoder(
src_flatten, # ( bs, h1*w1+h2*w2+h3*w3+h4*w4=9620, c=256)
spatial_shapes, # (4,2)
level_start_index, # (4)
valid_ratios, # (bs, 4,2)
lvl_pos_embed_flatten, # 3D (bs,h1*w1+h2*w2+h3*w3+h4*w4=9620,c=256)
mask_flatten # (bs,h1*w1+h2*w2+h3*w3+h4*w4)
)
"""
# 6层编码器,注意编码器的reference_points是固定不变的
output = src
reference_points = self.get_reference_points(spatial_shapes, valid_ratios, device=src.device)
for _, layer in enumerate(self.layers):
output = layer(output, pos, reference_points, spatial_shapes, level_start_index, padding_mask)
"""
output ( bs, h1*w1+h2*w2+h3*w3+h4*w4=9620, c=256)
pos (bs,h1*w1+h2*w2+h3*w3+h4*w4=9620,c=256)
reference_points [bs,h1*w1+h2*w2+h3*w3+h4*w4,4,2]
spatial_shapes (4,2)
level_start_index (4)
padding_mask (bs,h1*w1+h2*w2+h3*w3+h4*w4)
"""
return output
class CirConv(nn.Module): # 环形卷积
def __init__(self, d_model, n_adj=4):
super(CirConv, self).__init__()
self.n_adj = n_adj
self.conv = nn.Conv1d(d_model, d_model, kernel_size=self.n_adj*2+1)
self.relu = nn.ReLU(inplace=True)
self.norm = nn.BatchNorm1d(d_model)
for m in self.modules():
if isinstance(m, nn.Conv1d):
m.weight.data.normal_(0.0, 0.01)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
if isinstance(m, nn.BatchNorm1d):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
def forward(self, tgt):
shape = tgt.shape
tgt = (tgt.flatten(0, 1)).permute(0,2,1).contiguous() # (bs*nq, dim, n_pts)
tgt = torch.cat([tgt[..., -self.n_adj:], tgt, tgt[..., :self.n_adj]], dim=2)
"""
这里n_adj为4,假设tgt 为[0,1,2,3,4,5,6,7,8,9]则
[tgt[..., -self.n_adj:], tgt, tgt[..., :self.n_adj]]为[6,7,8,9][0,1,2,3,4,5,6,7,8,9][0,1,2,3]。cat到一起后总长为len(tgt)+2*n_adj
在self.conv中kernel_size=self.n_adj*2+1,则Conv1d后长度为len(tgt)+2*n_adj-(self.n_adj*2+1)+1 = len(tgt)
这里利用包围文字的控制点,相邻的n_adj个点应该有联系,用环形卷积实现这种近邻点的卷积,且头尾也考虑到了
"""
tgt = self.relu(self.norm(self.conv(tgt)))
tgt = tgt.permute(0,2,1).contiguous().reshape(shape)
return tgt
class DeformableTransformerDecoderLayer_Det(nn.Module):
def __init__(
self,
d_model=256,
d_ffn=1024,
dropout=0.1,
activation="relu",
n_levels=4,
n_heads=8,
n_points=4,
efsa=False
):
super().__init__()
self.efsa = efsa
# cross attention
self.attn_cross = MSDeformAttn(d_model, n_levels, n_heads, n_points)
self.dropout_cross = nn.Dropout(dropout)
self.norm_cross = nn.LayerNorm(d_model)
# intra-group self-attention
if self.efsa:
self.attn_intra = nn.MultiheadAttention(d_model, n_heads, dropout=0.)
self.circonv = CirConv(d_model)
self.norm_fuse = nn.LayerNorm(d_model)
self.mlp_fuse = nn.Linear(d_model, d_model)
self.drop_path = DropPath(0.1)
else:
self.attn_intra = nn.MultiheadAttention(d_model, n_heads, dropout=dropout)
self.dropout_intra = nn.Dropout(dropout)
self.norm_intra = nn.LayerNorm(d_model)
# inter-group self-attention
self.attn_inter = nn.MultiheadAttention(d_model, n_heads, dropout=dropout)
self.dropout_inter = nn.Dropout(dropout)
self.norm_inter = nn.LayerNorm(d_model)
# ffn
self.linear1 = nn.Linear(d_model, d_ffn)
self.activation = _get_activation_fn(activation)
self.dropout3 = nn.Dropout(dropout)
self.linear2 = nn.Linear(d_ffn, d_model)
self.dropout4 = nn.Dropout(dropout)
self.norm3 = nn.LayerNorm(d_model)
@staticmethod
def with_pos_embed(tensor, pos):
return tensor if pos is None else tensor + pos
def forward_ffn(self, tgt):
tgt2 = self.linear2(self.dropout3(self.activation(self.linear1(tgt))))
tgt = tgt + self.dropout4(tgt2)
tgt = self.norm3(tgt)
return tgt
def forward(
self,
tgt,
query_pos,
reference_points,
src,
src_spatial_shapes,
level_start_index,
src_padding_mask=None
):
"""
output, # (bs, n_q=100,n_pts=16,c=256)
query_pos, # (bs, n_q=100,n_pts=16,c=256)
reference_points_input, #(bs, n_q, n_pts,4,2)
src, # bs,h1*w1+h2*w2+h3*w3+h4*w4,c
src_spatial_shapes, # (4,2)
src_level_start_index, # (4)
src_padding_mask # (bs,h1*w1+h2*w2+h3*w3+h4*w4)
"""
# input size
# - tgt: (bs, n_q, n_pts, dim)
# - query_pos: (bs, n_q, n_pts, dim)
# intra-group self-attention 组内自注意力
if self.efsa:
shortcut = tgt
q = k = self.with_pos_embed(tgt, query_pos)
tgt = self.attn_intra( # nn.MultiheadAttention(d_model, n_heads, dropout=0.)
q.flatten(0, 1).transpose(0, 1),
k.flatten(0, 1).transpose(0, 1),
tgt.flatten(0, 1).transpose(0, 1),
)[0].transpose(0, 1).reshape(q.shape)
tgt_circonv = self.drop_path(self.circonv(shortcut+query_pos))
tgt = shortcut + self.norm_intra(self.drop_path(tgt) + tgt_circonv)
tgt = tgt + self.drop_path(self.norm_fuse(self.mlp_fuse(tgt)))
else:
q = k = self.with_pos_embed(tgt, query_pos)
tgt2 = self.attn_intra(
q.flatten(0, 1).transpose(0, 1),
k.flatten(0, 1).transpose(0, 1),
tgt.flatten(0, 1).transpose(0, 1),
)[0].transpose(0, 1).reshape(q.shape)
tgt = tgt + self.dropout_intra(tgt2)
tgt = self.norm_intra(tgt)
# inter-group self-attention 组间自注意力
q_inter = k_inter = tgt_inter = torch.swapdims(tgt, 1, 2) # (bs, n_pts, n_q, dim)
# self.attn_inter = nn.MultiheadAttention(d_model, n_heads, dropout=dropout)
tgt2_inter = self.attn_inter(
q_inter.flatten(0, 1).transpose(0, 1),
k_inter.flatten(0, 1).transpose(0, 1),
tgt_inter.flatten(0, 1).transpose(0, 1)
)[0].transpose(0, 1).reshape(q_inter.shape)
tgt_inter = tgt_inter + self.dropout_inter(tgt2_inter)
tgt_inter = torch.swapdims(self.norm_inter(tgt_inter), 1, 2)
# cross attention
if len(reference_points.shape) == 4:
reference_points_loc = reference_points[:, :, None, :, :].repeat(1, 1, tgt_inter.shape[2], 1, 1)
else:
assert reference_points.shape[2] == tgt_inter.shape[2]
reference_points_loc = reference_points
# self.attn_cross = MSDeformAttn(d_model, n_levels, n_heads, n_points)
tgt2 = self.attn_cross(
self.with_pos_embed(tgt_inter, query_pos).flatten(1, 2), # epqm时query_pos为None,(bs,n_q=100*n_pts=16=1600,c=256)
reference_points_loc.flatten(1, 2), #(bs,n_q*n_pts=1600,4,2或4)
src, # bs,h1*w1+h2*w2+h3*w3+h4*w4,c
src_spatial_shapes, # (4,2)
level_start_index, # (4)
src_padding_mask # (bs,h1*w1+h2*w2+h3*w3+h4*w4)
).reshape(tgt_inter.shape)
tgt_inter = tgt_inter + self.dropout_cross(tgt2)
tgt = self.norm_cross(tgt_inter)
# ffn
tgt = self.forward_ffn(tgt)
return tgt
class DeformableTransformerDecoder_Det(nn.Module):
def __init__(
self,
decoder_layer,
num_layers,
return_intermediate=False,
d_model=256,
epqm=False
):
super().__init__()
self.layers = _get_clones(decoder_layer, num_layers)
self.num_layers = num_layers
self.return_intermediate = return_intermediate
# hack implementation for iterative bounding box refinement and two-stage Deformable DETR
self.bbox_embed = None
self.class_embed = None
self.ctrl_point_coord = None
self.epqm = epqm
if epqm:
self.ref_point_head = MLP(d_model, d_model, d_model, 2)
def forward(
self,
tgt,
reference_points,
src,
src_spatial_shapes,
src_level_start_index,
src_valid_ratios,
query_pos=None,
src_padding_mask=None
):
"""
入参维度参考:
query_embed, # (bs,n_proposals=100,n_ctrl_points=16,d_model=256) 最后2维是nn.Embedding,其他2维是expand和repeat出来的,即在bs、n_proposals维度上不断重复
reference_points, # epqm时是(bs,nq=100,n_pts=16,2),否则是(bs,nq=100,4)
memory, # bs,h1*w1+h2*w2+h3*w3+h4*w4,c
spatial_shapes, # (4,2) 2是hw的值
level_start_index, # (4)
valid_ratios, # (bs, 4, 2)
query_pos=query_pos if not self.epqm else None, #query_pos为(_,_,256,_)
src_padding_mask=mask_flatten # (bs,h1*w1+h2*w2+h3*w3+h4*w4)
其中
query_embed nn.Embedding生成+拓展维度
reference_points 编码器head输出,epqm就转成16点,否则是4点
memory 是编码器输出的feature
query_pos 非epqm时对top box 进行正弦位置编码,epqm时为None
"""
output = tgt # bs, n_q, n_pts, 256 可以看出n_proposals就是n_q
if self.epqm:
assert query_pos is None
assert reference_points.shape[-1] == 2
intermediate = []
intermediate_reference_points = []
for lid, layer in enumerate(self.layers):
if reference_points.shape[-1] == 4: #xywh
reference_points_input = reference_points[:, :, None] \
* torch.cat([src_valid_ratios, src_valid_ratios], -1)[:, None]
else: #之前很困惑,作者原意可能是想区别一阶段和两阶段,但是上面的代码是两阶段的,也就是其实走不到下面的else。但要注意reference_points在各层解码器中会传递
# enter here
assert reference_points.shape[-1] == 2
if self.epqm:
# reference_points: (bs, nq, n_pts, 2)
# reference_points_input: (bs, nq, n_pts, 4, 2)
reference_points_input = reference_points[:, :, :, None] * src_valid_ratios[:, None, None]
else:
reference_points_input = reference_points[:, :, None] * src_valid_ratios[:, None]
if self.epqm:
# embed the explicit point coordinates 正弦位置编码
query_pos = gen_point_pos_embed(reference_points_input[:, :, :, 0, :])
# get the positional queries 2层mlp
query_pos = self.ref_point_head(query_pos) # projection
"""
query_pos 非epqm时对top box 进行正弦位置编码,epqm时为对参考点进行正弦位置编码
"""
output = layer(
output, # (bs, n_q=100,n_pts=16,c=256)
query_pos, # (bs, n_q=100,n_pts=16,c=256)
reference_points_input, #(bs, n_q, n_pts,4,2)
src, # bs,h1*w1+h2*w2+h3*w3+h4*w4,c
src_spatial_shapes, # (4,2)
src_level_start_index, # (4)
src_padding_mask # (bs,h1*w1+h2*w2+h3*w3+h4*w4)
)
# update the reference points
if self.ctrl_point_coord is not None: # models.py中epqm时为3层mlp,MLP(256,256,2,3),各层解码器共享,更新参考点
tmp = self.ctrl_point_coord[lid](output)
tmp += inverse_sigmoid(reference_points)
tmp = tmp.sigmoid()
reference_points = tmp.detach()
if self.return_intermediate:
intermediate.append(output)
intermediate_reference_points.append(reference_points)
if self.return_intermediate:
# 注意这里,可以把不同层的output和参考点输出
return torch.stack(intermediate), torch.stack(intermediate_reference_points)
return output, reference_points # 这里只返回最后一层的,和上面的return维度不同
def _get_clones(module, N):
return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
def _get_activation_fn(activation):
"""Return an activation function given a string"""
if activation == "relu":
return F.relu
if activation == "gelu":
return F.gelu
if activation == "glu":
return F.glu
raise RuntimeError(F"activation should be relu/gelu, not {activation}.")
多尺度可变形注意力
# adet/layers/ms_deform_attn.py
# ------------------------------------------------------------------------------------------------
# Deformable DETR
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
# ------------------------------------------------------------------------------------------------
# Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
# ------------------------------------------------------------------------------------------------
import warnings
import math
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn.init import xavier_uniform_, constant_
from torch.autograd.function import once_differentiable
from adet import _C
class _MSDeformAttnFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, value, value_spatial_shapes, value_level_start_index, sampling_locations, attention_weights, im2col_step):
"""
ctx #( bs, h1*w1+h2*w2+h3*w3+h4*w4=9620, c=256)拆多头后过Linear得到的value
value_spatial_shapes # 每个level的hw值(4,2)
value_level_start_index# input_level_start_index (4)
sampling_locations # 采样点 (N, Len_q, self.n_heads, self.n_levels, self.n_points, 2)
attention_weights # head中每个采样点的权重 (N, Len_q, self.n_heads, self.n_levels, self.n_points)
self.im2col_step #=64
"""
ctx.im2col_step = im2col_step
output = _C.ms_deform_attn_forward(
value, value_spatial_shapes, value_level_start_index, sampling_locations, attention_weights, ctx.im2col_step)
ctx.save_for_backward(value, value_spatial_shapes, value_level_start_index, sampling_locations, attention_weights)
return output
@staticmethod
@once_differentiable
def backward(ctx, grad_output):
value, value_spatial_shapes, value_level_start_index, sampling_locations, attention_weights = ctx.saved_tensors
grad_value, grad_sampling_loc, grad_attn_weight = \
_C.ms_deform_attn_backward(
value, value_spatial_shapes, value_level_start_index, sampling_locations, attention_weights, grad_output, ctx.im2col_step)
return grad_value, None, None, grad_sampling_loc, grad_attn_weight, None
def ms_deform_attn_core_pytorch(value, value_spatial_shapes, sampling_locations, attention_weights):
# 可变形卷积最最核心的地方是C++实现的,这里还提供了Python的版本供参考,主要流程为,sampling_locations处理到[-1,1],基于grid_sample方法在value中采样,乘以attention_weights
# for debug and test only,
# need to use cuda version instead
N_, S_, M_, D_ = value.shape
_, Lq_, M_, L_, P_, _ = sampling_locations.shape
value_list = value.split([H_ * W_ for H_, W_ in value_spatial_shapes], dim=1)
sampling_grids = 2 * sampling_locations - 1 # 值处理到[-1,1]范围作为grid_sample入参
sampling_value_list = []
for lid_, (H_, W_) in enumerate(value_spatial_shapes):
# N_, H_*W_, M_, D_ -> N_, H_*W_, M_*D_ -> N_, M_*D_, H_*W_ -> N_*M_, D_, H_, W_
value_l_ = value_list[lid_].flatten(2).transpose(1, 2).reshape(N_*M_, D_, H_, W_)
# N_, Lq_, M_, P_, 2 -> N_, M_, Lq_, P_, 2 -> N_*M_, Lq_, P_, 2
sampling_grid_l_ = sampling_grids[:, :, :, lid_].transpose(1, 2).flatten(0, 1)
# N_*M_, D_, Lq_, P_
sampling_value_l_ = F.grid_sample(value_l_, sampling_grid_l_,
mode='bilinear', padding_mode='zeros', align_corners=False)
sampling_value_list.append(sampling_value_l_)
# (N_, Lq_, M_, L_, P_) -> (N_, M_, Lq_, L_, P_) -> (N_, M_, 1, Lq_, L_*P_)
attention_weights = attention_weights.transpose(1, 2).reshape(N_*M_, 1, Lq_, L_*P_)
output = (torch.stack(sampling_value_list, dim=-2).flatten(-2) * attention_weights).sum(-1).view(N_, M_*D_, Lq_)
return output.transpose(1, 2).contiguous()
def _is_power_of_2(n):
if (not isinstance(n, int)) or (n < 0):
raise ValueError("invalid input for _is_power_of_2: {} (type: {})".format(n, type(n)))
return (n & (n-1) == 0) and n != 0
class MSDeformAttn(nn.Module):
def __init__(self, d_model=256, n_levels=4, n_heads=8, n_points=4):
"""
Multi-Scale Deformable Attention Module
:param d_model hidden dimension
:param n_levels number of feature levels
:param n_heads number of attention heads
:param n_points number of sampling points per attention head per feature level
这里 默认有4 levels,8head,每head每level有4个采样点,则每个head有4*4=16个采样点
"""
super().__init__()
if d_model % n_heads != 0:
raise ValueError('d_model must be divisible by n_heads, but got {} and {}'.format(d_model, n_heads))
_d_per_head = d_model // n_heads # 多头中每头的维度,如256/8
# you'd better set _d_per_head to a power of 2 which is more efficient in our CUDA implementation
if not _is_power_of_2(_d_per_head):
warnings.warn("You'd better set d_model in MSDeformAttn to make the dimension of each attention head a power of 2 "
"which is more efficient in our CUDA implementation.")
self.im2col_step = 64
self.d_model = d_model
self.n_levels = n_levels
self.n_heads = n_heads
self.n_points = n_points
self.sampling_offsets = nn.Linear(d_model, n_heads * n_levels * n_points * 2)
self.attention_weights = nn.Linear(d_model, n_heads * n_levels * n_points)
self.value_proj = nn.Linear(d_model, d_model)
self.output_proj = nn.Linear(d_model, d_model)
self._reset_parameters()
def _reset_parameters(self):
constant_(self.sampling_offsets.weight.data, 0.)
# head=8,就是8个方向采样;n_points=4,就是4个偏移程度
thetas = torch.arange(self.n_heads, dtype=torch.float32) * (2.0 * math.pi / self.n_heads)
grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
grid_init = (grid_init / grid_init.abs().max(-1, keepdim=True)[0]).view(self.n_heads, 1, 1, 2).repeat(1, self.n_levels, self.n_points, 1)
for i in range(self.n_points):
grid_init[:, :, i, :] *= i + 1 # (n_heads, self.n_levels, self.n_points,2)
with torch.no_grad():
self.sampling_offsets.bias = nn.Parameter(grid_init.view(-1))
constant_(self.attention_weights.weight.data, 0.)
constant_(self.attention_weights.bias.data, 0.)
xavier_uniform_(self.value_proj.weight.data)
constant_(self.value_proj.bias.data, 0.)
xavier_uniform_(self.output_proj.weight.data)
constant_(self.output_proj.bias.data, 0.)
def forward(self, query, reference_points, input_flatten, input_spatial_shapes, input_level_start_index, input_padding_mask=None):
"""
:param query (N, Length_{query}, C)
:param reference_points (N, Length_{query}, n_levels, 2), range in [0, 1], top-left (0,0), bottom-right (1, 1), including padding area
or (N, Length_{query}, n_levels, 4), add additional (w, h) to form reference boxes
:param input_flatten (N, \sum_{l=0}^{L-1} H_l \cdot W_l, C)
:param input_spatial_shapes (n_levels, 2), [(H_0, W_0), (H_1, W_1), ..., (H_{L-1}, W_{L-1})]
:param input_level_start_index (n_levels, ), [0, H_0*W_0, H_0*W_0+H_1*W_1, H_0*W_0+H_1*W_1+H_2*W_2, ..., H_0*W_0+H_1*W_1+...+H_{L-1}*W_{L-1}]
:param input_padding_mask (N, \sum_{l=0}^{L-1} H_l \cdot W_l), True for padding elements, False for non-padding elements
:return output (N, Length_{query}, C)
"""
N, Len_q, _ = query.shape
N, Len_in, _ = input_flatten.shape
assert (input_spatial_shapes[:, 0] * input_spatial_shapes[:, 1]).sum() == Len_in
value = self.value_proj(input_flatten) # 基于Linear(256,256)得到Value
if input_padding_mask is not None:
value = value.masked_fill(input_padding_mask[..., None], float(0))
# 拆多头,并通过2个线性层得到偏移量和权重Weight
value = value.view(N, Len_in, self.n_heads, self.d_model // self.n_heads)
sampling_offsets = self.sampling_offsets(query).view(N, Len_q, self.n_heads, self.n_levels, self.n_points, 2)
attention_weights = self.attention_weights(query).view(N, Len_q, self.n_heads, self.n_levels * self.n_points)
# 这里可以看出softmax 是在self.n_levels * self.n_points=4*4=16中进行的,head间无关
attention_weights = F.softmax(attention_weights, -1).view(N, Len_q, self.n_heads, self.n_levels, self.n_points)
# N, Len_q, n_heads, n_levels, n_points, 2
# 参考点基础上进行偏移得到采样点
if reference_points.shape[-1] == 2:
offset_normalizer = torch.stack([input_spatial_shapes[..., 1], input_spatial_shapes[..., 0]], -1)
sampling_locations = reference_points[:, :, None, :, None, :] \
+ sampling_offsets / offset_normalizer[None, None, None, :, None, :]
elif reference_points.shape[-1] == 4:
sampling_locations = reference_points[:, :, None, :, None, :2] \
+ sampling_offsets / self.n_points * reference_points[:, :, None, :, None, 2:] * 0.5
else:
raise ValueError(
'Last dim of reference_points must be 2 or 4, but get {} instead.'.format(reference_points.shape[-1]))
output = _MSDeformAttnFunction.apply(
value, input_spatial_shapes, input_level_start_index, sampling_locations, attention_weights, self.im2col_step)
# 输出还要过个Linear
output = self.output_proj(output)
return output
先说结论:随batch增大,显存占用变高,但单张平均推理时间几乎没变。阅读时可跳过这部分实验记录。
(1)单张图片predict的速度及显存约为0.2s/张,2.5G
(2)推理时调用的方法,最底层的脚本在DefaultPredictor,用注册机制获取模型,然后进行推理。
现在想要实验一下,解决以下问题:
Q:多张图推理的速度如何,是0.2*N还是更小一点?多张图推理的显存如何,16G的卡最多能接受batch为多大?
先改DefaultPredictor的def __call__,试试多张相同的图。修改self.model的入参为4张图时速度
self.model的入参list数量 | 显存 | N张推理速度 | 单张平均耗时 |
1 | 2.5G | 0.2s | 0.2s |
4 | 5.6G | 0.5s | 0.125S |
8 | 10G | 1s | 0.125S |
10 | 12g | 1.2S | 0.12S |
为快速评估方案,采用的是以下基于同一个inputs的方案,少了不同图片的约需要0.063的self.aug.get_transform的处理最大最小长宽时间。
|
inputs = {"image": image, "height": height, "width": width}
predictions = self.model([inputs])[0]
#改成
predictions = self.model([inputs,inputs,inputs,inputs,......])[0]
令人伤心的是,增大batch_size虽然增大了显存,但是并不能有效并行提速,其他人也遇到了类似的问题。batchsize大小对训练速度的影响_batchsize越大训练越快吗_Golden-sun的博客-CSDN博客
yolov5多batch模型推理相比单batch没有缩短 · Issue #I6MHX2 · Ascend/modelzoo - Gitee.com
一个可能的原因是数据处理占用了大部分耗时,在DefaultPredictor的def __call__、class TransformerPureDetector的forward 都打印耗时,10张图片(在self.model中输入多个)总耗时1.02s,较大的耗时分布如下:
总耗时 | 1.02 | |
self.aug.get_transform 1张图 | 0.063 | 将输入图片处理到长宽在1000-1800之间,测试图尺寸为2350x3037 |
TransformerPureDetector 中preprocess_image 10张图 | 0.051 | |
TransformerPureDetector 中self.dptext_detr 10张图 | 0.82 | |
TransformerPureDetector 中self.inference10张图 | 0.017 |
分析下来,只有dptext_detr 可能存在一点加速空间,内部耗时如下:
self.backbone 10张图 | 0.25 | cnn |
self.input_proj等 10张图 | 0.15 | 处理为通道为256的4个特征图 |
self.transformer 10张图 | 0.58 | 编解码器 |
Q:float32能换成float16吗,对速度和精度的有何影响?
Q:编解码器都用到了可变形注意力机制,入参有什么区别,尤其是query的区别
先看一下MSDeformAttn方法的forward描述
class MSDeformAttn(d_model, n_levels, n_heads, n_points):
......
def forward(self, query, reference_points, input_flatten, input_spatial_shapes, input_level_start_index, input_padding_mask=None):
"""
:param query (N, Length_{query}, C)
:param reference_points (N, Length_{query}, n_levels, 2), range in [0, 1], top-left (0,0), bottom-right (1, 1), including padding area
or (N, Length_{query}, n_levels, 4), add additional (w, h) to form reference boxes
:param input_flatten (N, \sum_{l=0}^{L-1} H_l \cdot W_l, C)
:param input_spatial_shapes (n_levels, 2), [(H_0, W_0), (H_1, W_1), ..., (H_{L-1}, W_{L-1})]
:param input_level_start_index (n_levels, ), [0, H_0*W_0, H_0*W_0+H_1*W_1, H_0*W_0+H_1*W_1+H_2*W_2, ..., H_0*W_0+H_1*W_1+...+H_{L-1}*W_{L-1}]
:param input_padding_mask (N, \sum_{l=0}^{L-1} H_l \cdot W_l), True for padding elements, False for non-padding elements
:return output (N, Length_{query}, C)
然后看一下编解码器的入参维度,可以看到src维度是一样的,区别在于:
1.query在编码器中是每个层的每个点,数量为h1*w1+h2*w2+h3*w3+h4*w4=9620,在解码器中是设置的最大文本数*每个文本的控制点数,数量为n_q=100*n_pts=16=1600
2.编码器的参考点是xy,解码器的参考点可能是xywh
# 编码器----------------
self.with_pos_embed(src, pos), # (bs,h1*w1+h2*w2+h3*w3+h4*w4=9620,c=256)
reference_points, #(bs,h1*w1+h2*w2+h3*w3+h4*w4,4,2)
src, # ( bs, h1*w1+h2*w2+h3*w3+h4*w4=9620, c=256)
spatial_shapes, # (4,2)
level_start_index, #(4)
padding_mask # (bs,h1*w1+h2*w2+h3*w3+h4*w4)
# 解码器----------------
self.with_pos_embed(tgt_inter, query_pos).flatten(1, 2), # epqm时query_pos为None,(bs,n_q=100*n_pts=16=1600,c=256)
reference_points_loc.flatten(1, 2), #(bs,n_q*n_pts=1600,4,2或4)
src, # bs,h1*w1+h2*w2+h3*w3+h4*w4,c
src_spatial_shapes, # (4,2)
level_start_index, # (4)
src_padding_mask # (bs,h1*w1+h2*w2+h3*w3+h4*w4)
Q:DETR中的FFN
图中彩色方框其实是每个点的高维特征表达,FFN是2个线性层
Q:Object queries 的QK为什么还要相加,为什么还要加到交叉attention中
相加是query+position,大概是自注意力后位置信息弱了,要加强一下?
Q:Q特征哪来的
看上面对MSDeformAttn的解释,编码器是每层特征图的每个网格点,解码器是编码器给的proposal或embedding出来的
Q:训练好的模型,Object queries还能改来改去,这是任意伸缩的?nn.Embedding实现可以瞎改吗
其实改的是编码器proposal的数量,而不是embedding
Q:EFSA(Enhanced Factorized Self-Attention 增强的因子化自我注意):进行环形引导。通过循环卷积(环形卷积)引入局部关注
就是拿个一维卷积,每n个交换下信息得到一个输出,然后滑窗。环形是补充了一下头尾的信息
Q:为何检测头部的回归分支预测的是偏移量而非绝对坐标值?
Deformable DETR: 基于稀疏空间采样的注意力机制,让DCN与Transformer一起玩! - 知乎
“采样点的位置是基于参考点和对应的坐标偏移量计算出来的,也就是说采样特征是分布在参考点附近的,既然这里需要由采样特征回归出bbox的位置,那么预测相对于参考点的偏移量就会比直接预测绝对坐标更易优化,更有利于模型学习。”
总之就是由于参考点的设置,这样优化更容易
Q:各通道之间怎么组合呢
每个query在各个通道间取参考点及其采样点,及query是在各个层间
Q: 源码中有没有对推理时的尺寸大小做限制,避免输入太大时显存溢出OOM
有的,参数见配置文件yaml的MIN_SIZE_TEST、MAX_SIZE_TEST,具体实现在detectron中
Q:3中颜色有啥说法,为什么从彩色变成了统一
画图好看?
————————————————————
Q:模型3的2个解码器的输入输出
Q:模型3的2个解码器交换了什么信息,即图中的红绿线
Q:detectron2的CfgNode
Q:# 4>4 应该没执行这个if下的操作
Q:为啥分解自注意力可以降低计算量
不得不看!降低Transformer复杂度的方法-CSDN博客
看代码也还没理解
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。