deformable_transformer.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. # Modified from Deformable-DETR (https://github.com/fundamentalvision/Deformable-DETR)
  16. # Copyright (c) 2020 SenseTime. All Rights Reserved.
  17. from __future__ import absolute_import
  18. from __future__ import division
  19. from __future__ import print_function
  20. import math
  21. import paddle
  22. import paddle.nn as nn
  23. import paddle.nn.functional as F
  24. from paddle import ParamAttr
  25. from ppdet.core.workspace import register
  26. from ..layers import MultiHeadAttention
  27. from .position_encoding import PositionEmbedding
  28. from .utils import _get_clones, get_valid_ratio
  29. from ..initializer import linear_init_, constant_, xavier_uniform_, normal_
  30. __all__ = ['DeformableTransformer']
  31. class MSDeformableAttention(nn.Layer):
  32. def __init__(self,
  33. embed_dim=256,
  34. num_heads=8,
  35. num_levels=4,
  36. num_points=4,
  37. lr_mult=0.1):
  38. """
  39. Multi-Scale Deformable Attention Module
  40. """
  41. super(MSDeformableAttention, self).__init__()
  42. self.embed_dim = embed_dim
  43. self.num_heads = num_heads
  44. self.num_levels = num_levels
  45. self.num_points = num_points
  46. self.total_points = num_heads * num_levels * num_points
  47. self.head_dim = embed_dim // num_heads
  48. assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads"
  49. self.sampling_offsets = nn.Linear(
  50. embed_dim,
  51. self.total_points * 2,
  52. weight_attr=ParamAttr(learning_rate=lr_mult),
  53. bias_attr=ParamAttr(learning_rate=lr_mult))
  54. self.attention_weights = nn.Linear(embed_dim, self.total_points)
  55. self.value_proj = nn.Linear(embed_dim, embed_dim)
  56. self.output_proj = nn.Linear(embed_dim, embed_dim)
  57. try:
  58. # use cuda op
  59. from deformable_detr_ops import ms_deformable_attn
  60. except:
  61. # use paddle func
  62. from .utils import deformable_attention_core_func as ms_deformable_attn
  63. self.ms_deformable_attn_core = ms_deformable_attn
  64. self._reset_parameters()
  65. def _reset_parameters(self):
  66. # sampling_offsets
  67. constant_(self.sampling_offsets.weight)
  68. thetas = paddle.arange(
  69. self.num_heads,
  70. dtype=paddle.float32) * (2.0 * math.pi / self.num_heads)
  71. grid_init = paddle.stack([thetas.cos(), thetas.sin()], -1)
  72. grid_init = grid_init / grid_init.abs().max(-1, keepdim=True)
  73. grid_init = grid_init.reshape([self.num_heads, 1, 1, 2]).tile(
  74. [1, self.num_levels, self.num_points, 1])
  75. scaling = paddle.arange(
  76. 1, self.num_points + 1,
  77. dtype=paddle.float32).reshape([1, 1, -1, 1])
  78. grid_init *= scaling
  79. self.sampling_offsets.bias.set_value(grid_init.flatten())
  80. # attention_weights
  81. constant_(self.attention_weights.weight)
  82. constant_(self.attention_weights.bias)
  83. # proj
  84. xavier_uniform_(self.value_proj.weight)
  85. constant_(self.value_proj.bias)
  86. xavier_uniform_(self.output_proj.weight)
  87. constant_(self.output_proj.bias)
  88. def forward(self,
  89. query,
  90. reference_points,
  91. value,
  92. value_spatial_shapes,
  93. value_level_start_index,
  94. value_mask=None):
  95. """
  96. Args:
  97. query (Tensor): [bs, query_length, C]
  98. reference_points (Tensor): [bs, query_length, n_levels, 2], range in [0, 1], top-left (0,0),
  99. bottom-right (1, 1), including padding area
  100. value (Tensor): [bs, value_length, C]
  101. value_spatial_shapes (Tensor): [n_levels, 2], [(H_0, W_0), (H_1, W_1), ..., (H_{L-1}, W_{L-1})]
  102. value_level_start_index (Tensor(int64)): [n_levels], [0, H_0*W_0, H_0*W_0+H_1*W_1, ...]
  103. value_mask (Tensor): [bs, value_length], True for non-padding elements, False for padding elements
  104. Returns:
  105. output (Tensor): [bs, Length_{query}, C]
  106. """
  107. bs, Len_q = query.shape[:2]
  108. Len_v = value.shape[1]
  109. assert int(value_spatial_shapes.prod(1).sum()) == Len_v
  110. value = self.value_proj(value)
  111. if value_mask is not None:
  112. value_mask = value_mask.astype(value.dtype).unsqueeze(-1)
  113. value *= value_mask
  114. value = value.reshape([bs, Len_v, self.num_heads, self.head_dim])
  115. sampling_offsets = self.sampling_offsets(query).reshape(
  116. [bs, Len_q, self.num_heads, self.num_levels, self.num_points, 2])
  117. attention_weights = self.attention_weights(query).reshape(
  118. [bs, Len_q, self.num_heads, self.num_levels * self.num_points])
  119. attention_weights = F.softmax(attention_weights).reshape(
  120. [bs, Len_q, self.num_heads, self.num_levels, self.num_points])
  121. if reference_points.shape[-1] == 2:
  122. offset_normalizer = value_spatial_shapes.flip([1]).reshape(
  123. [1, 1, 1, self.num_levels, 1, 2])
  124. sampling_locations = reference_points.reshape([
  125. bs, Len_q, 1, self.num_levels, 1, 2
  126. ]) + sampling_offsets / offset_normalizer
  127. elif reference_points.shape[-1] == 4:
  128. sampling_locations = (
  129. reference_points[:, :, None, :, None, :2] + sampling_offsets /
  130. self.num_points * reference_points[:, :, None, :, None, 2:] *
  131. 0.5)
  132. else:
  133. raise ValueError(
  134. "Last dim of reference_points must be 2 or 4, but get {} instead.".
  135. format(reference_points.shape[-1]))
  136. output = self.ms_deformable_attn_core(
  137. value, value_spatial_shapes, value_level_start_index,
  138. sampling_locations, attention_weights)
  139. output = self.output_proj(output)
  140. return output
  141. class DeformableTransformerEncoderLayer(nn.Layer):
  142. def __init__(self,
  143. d_model=256,
  144. n_head=8,
  145. dim_feedforward=1024,
  146. dropout=0.1,
  147. activation="relu",
  148. n_levels=4,
  149. n_points=4,
  150. weight_attr=None,
  151. bias_attr=None):
  152. super(DeformableTransformerEncoderLayer, self).__init__()
  153. # self attention
  154. self.self_attn = MSDeformableAttention(d_model, n_head, n_levels,
  155. n_points)
  156. self.dropout1 = nn.Dropout(dropout)
  157. self.norm1 = nn.LayerNorm(d_model)
  158. # ffn
  159. self.linear1 = nn.Linear(d_model, dim_feedforward, weight_attr,
  160. bias_attr)
  161. self.activation = getattr(F, activation)
  162. self.dropout2 = nn.Dropout(dropout)
  163. self.linear2 = nn.Linear(dim_feedforward, d_model, weight_attr,
  164. bias_attr)
  165. self.dropout3 = nn.Dropout(dropout)
  166. self.norm2 = nn.LayerNorm(d_model)
  167. self._reset_parameters()
  168. def _reset_parameters(self):
  169. linear_init_(self.linear1)
  170. linear_init_(self.linear2)
  171. xavier_uniform_(self.linear1.weight)
  172. xavier_uniform_(self.linear2.weight)
  173. def with_pos_embed(self, tensor, pos):
  174. return tensor if pos is None else tensor + pos
  175. def forward_ffn(self, src):
  176. src2 = self.linear2(self.dropout2(self.activation(self.linear1(src))))
  177. src = src + self.dropout3(src2)
  178. src = self.norm2(src)
  179. return src
  180. def forward(self,
  181. src,
  182. reference_points,
  183. spatial_shapes,
  184. level_start_index,
  185. src_mask=None,
  186. pos_embed=None):
  187. # self attention
  188. src2 = self.self_attn(
  189. self.with_pos_embed(src, pos_embed), reference_points, src,
  190. spatial_shapes, level_start_index, src_mask)
  191. src = src + self.dropout1(src2)
  192. src = self.norm1(src)
  193. # ffn
  194. src = self.forward_ffn(src)
  195. return src
  196. class DeformableTransformerEncoder(nn.Layer):
  197. def __init__(self, encoder_layer, num_layers):
  198. super(DeformableTransformerEncoder, self).__init__()
  199. self.layers = _get_clones(encoder_layer, num_layers)
  200. self.num_layers = num_layers
  201. @staticmethod
  202. def get_reference_points(spatial_shapes, valid_ratios, offset=0.5):
  203. valid_ratios = valid_ratios.unsqueeze(1)
  204. reference_points = []
  205. for i, (H, W) in enumerate(spatial_shapes):
  206. ref_y, ref_x = paddle.meshgrid(
  207. paddle.arange(end=H) + offset, paddle.arange(end=W) + offset)
  208. ref_y = ref_y.flatten().unsqueeze(0) / (valid_ratios[:, :, i, 1] *
  209. H)
  210. ref_x = ref_x.flatten().unsqueeze(0) / (valid_ratios[:, :, i, 0] *
  211. W)
  212. reference_points.append(paddle.stack((ref_x, ref_y), axis=-1))
  213. reference_points = paddle.concat(reference_points, 1).unsqueeze(2)
  214. reference_points = reference_points * valid_ratios
  215. return reference_points
  216. def forward(self,
  217. src,
  218. spatial_shapes,
  219. level_start_index,
  220. src_mask=None,
  221. pos_embed=None,
  222. valid_ratios=None):
  223. output = src
  224. if valid_ratios is None:
  225. valid_ratios = paddle.ones(
  226. [src.shape[0], spatial_shapes.shape[0], 2])
  227. reference_points = self.get_reference_points(spatial_shapes,
  228. valid_ratios)
  229. for layer in self.layers:
  230. output = layer(output, reference_points, spatial_shapes,
  231. level_start_index, src_mask, pos_embed)
  232. return output
  233. class DeformableTransformerDecoderLayer(nn.Layer):
  234. def __init__(self,
  235. d_model=256,
  236. n_head=8,
  237. dim_feedforward=1024,
  238. dropout=0.1,
  239. activation="relu",
  240. n_levels=4,
  241. n_points=4,
  242. weight_attr=None,
  243. bias_attr=None):
  244. super(DeformableTransformerDecoderLayer, self).__init__()
  245. # self attention
  246. self.self_attn = MultiHeadAttention(d_model, n_head, dropout=dropout)
  247. self.dropout1 = nn.Dropout(dropout)
  248. self.norm1 = nn.LayerNorm(d_model)
  249. # cross attention
  250. self.cross_attn = MSDeformableAttention(d_model, n_head, n_levels,
  251. n_points)
  252. self.dropout2 = nn.Dropout(dropout)
  253. self.norm2 = nn.LayerNorm(d_model)
  254. # ffn
  255. self.linear1 = nn.Linear(d_model, dim_feedforward, weight_attr,
  256. bias_attr)
  257. self.activation = getattr(F, activation)
  258. self.dropout3 = nn.Dropout(dropout)
  259. self.linear2 = nn.Linear(dim_feedforward, d_model, weight_attr,
  260. bias_attr)
  261. self.dropout4 = nn.Dropout(dropout)
  262. self.norm3 = nn.LayerNorm(d_model)
  263. self._reset_parameters()
  264. def _reset_parameters(self):
  265. linear_init_(self.linear1)
  266. linear_init_(self.linear2)
  267. xavier_uniform_(self.linear1.weight)
  268. xavier_uniform_(self.linear2.weight)
  269. def with_pos_embed(self, tensor, pos):
  270. return tensor if pos is None else tensor + pos
  271. def forward_ffn(self, tgt):
  272. tgt2 = self.linear2(self.dropout3(self.activation(self.linear1(tgt))))
  273. tgt = tgt + self.dropout4(tgt2)
  274. tgt = self.norm3(tgt)
  275. return tgt
  276. def forward(self,
  277. tgt,
  278. reference_points,
  279. memory,
  280. memory_spatial_shapes,
  281. memory_level_start_index,
  282. memory_mask=None,
  283. query_pos_embed=None):
  284. # self attention
  285. q = k = self.with_pos_embed(tgt, query_pos_embed)
  286. tgt2 = self.self_attn(q, k, value=tgt)
  287. tgt = tgt + self.dropout1(tgt2)
  288. tgt = self.norm1(tgt)
  289. # cross attention
  290. tgt2 = self.cross_attn(
  291. self.with_pos_embed(tgt, query_pos_embed), reference_points, memory,
  292. memory_spatial_shapes, memory_level_start_index, memory_mask)
  293. tgt = tgt + self.dropout2(tgt2)
  294. tgt = self.norm2(tgt)
  295. # ffn
  296. tgt = self.forward_ffn(tgt)
  297. return tgt
  298. class DeformableTransformerDecoder(nn.Layer):
  299. def __init__(self, decoder_layer, num_layers, return_intermediate=False):
  300. super(DeformableTransformerDecoder, self).__init__()
  301. self.layers = _get_clones(decoder_layer, num_layers)
  302. self.num_layers = num_layers
  303. self.return_intermediate = return_intermediate
  304. def forward(self,
  305. tgt,
  306. reference_points,
  307. memory,
  308. memory_spatial_shapes,
  309. memory_level_start_index,
  310. memory_mask=None,
  311. query_pos_embed=None):
  312. output = tgt
  313. intermediate = []
  314. for lid, layer in enumerate(self.layers):
  315. output = layer(output, reference_points, memory,
  316. memory_spatial_shapes, memory_level_start_index,
  317. memory_mask, query_pos_embed)
  318. if self.return_intermediate:
  319. intermediate.append(output)
  320. if self.return_intermediate:
  321. return paddle.stack(intermediate)
  322. return output.unsqueeze(0)
  323. @register
  324. class DeformableTransformer(nn.Layer):
  325. __shared__ = ['hidden_dim']
  326. def __init__(self,
  327. num_queries=300,
  328. position_embed_type='sine',
  329. return_intermediate_dec=True,
  330. backbone_num_channels=[512, 1024, 2048],
  331. num_feature_levels=4,
  332. num_encoder_points=4,
  333. num_decoder_points=4,
  334. hidden_dim=256,
  335. nhead=8,
  336. num_encoder_layers=6,
  337. num_decoder_layers=6,
  338. dim_feedforward=1024,
  339. dropout=0.1,
  340. activation="relu",
  341. lr_mult=0.1,
  342. weight_attr=None,
  343. bias_attr=None):
  344. super(DeformableTransformer, self).__init__()
  345. assert position_embed_type in ['sine', 'learned'], \
  346. f'ValueError: position_embed_type not supported {position_embed_type}!'
  347. assert len(backbone_num_channels) <= num_feature_levels
  348. self.hidden_dim = hidden_dim
  349. self.nhead = nhead
  350. self.num_feature_levels = num_feature_levels
  351. encoder_layer = DeformableTransformerEncoderLayer(
  352. hidden_dim, nhead, dim_feedforward, dropout, activation,
  353. num_feature_levels, num_encoder_points, weight_attr, bias_attr)
  354. self.encoder = DeformableTransformerEncoder(encoder_layer,
  355. num_encoder_layers)
  356. decoder_layer = DeformableTransformerDecoderLayer(
  357. hidden_dim, nhead, dim_feedforward, dropout, activation,
  358. num_feature_levels, num_decoder_points, weight_attr, bias_attr)
  359. self.decoder = DeformableTransformerDecoder(
  360. decoder_layer, num_decoder_layers, return_intermediate_dec)
  361. self.level_embed = nn.Embedding(num_feature_levels, hidden_dim)
  362. self.tgt_embed = nn.Embedding(num_queries, hidden_dim)
  363. self.query_pos_embed = nn.Embedding(num_queries, hidden_dim)
  364. self.reference_points = nn.Linear(
  365. hidden_dim,
  366. 2,
  367. weight_attr=ParamAttr(learning_rate=lr_mult),
  368. bias_attr=ParamAttr(learning_rate=lr_mult))
  369. self.input_proj = nn.LayerList()
  370. for in_channels in backbone_num_channels:
  371. self.input_proj.append(
  372. nn.Sequential(
  373. nn.Conv2D(
  374. in_channels,
  375. hidden_dim,
  376. kernel_size=1,
  377. weight_attr=weight_attr,
  378. bias_attr=bias_attr),
  379. nn.GroupNorm(32, hidden_dim)))
  380. in_channels = backbone_num_channels[-1]
  381. for _ in range(num_feature_levels - len(backbone_num_channels)):
  382. self.input_proj.append(
  383. nn.Sequential(
  384. nn.Conv2D(
  385. in_channels,
  386. hidden_dim,
  387. kernel_size=3,
  388. stride=2,
  389. padding=1,
  390. weight_attr=weight_attr,
  391. bias_attr=bias_attr),
  392. nn.GroupNorm(32, hidden_dim)))
  393. in_channels = hidden_dim
  394. self.position_embedding = PositionEmbedding(
  395. hidden_dim // 2,
  396. normalize=True if position_embed_type == 'sine' else False,
  397. embed_type=position_embed_type,
  398. offset=-0.5)
  399. self._reset_parameters()
  400. def _reset_parameters(self):
  401. normal_(self.level_embed.weight)
  402. normal_(self.tgt_embed.weight)
  403. normal_(self.query_pos_embed.weight)
  404. xavier_uniform_(self.reference_points.weight)
  405. constant_(self.reference_points.bias)
  406. for l in self.input_proj:
  407. xavier_uniform_(l[0].weight)
  408. constant_(l[0].bias)
  409. @classmethod
  410. def from_config(cls, cfg, input_shape):
  411. return {'backbone_num_channels': [i.channels for i in input_shape], }
  412. def forward(self, src_feats, src_mask=None, *args, **kwargs):
  413. srcs = []
  414. for i in range(len(src_feats)):
  415. srcs.append(self.input_proj[i](src_feats[i]))
  416. if self.num_feature_levels > len(srcs):
  417. len_srcs = len(srcs)
  418. for i in range(len_srcs, self.num_feature_levels):
  419. if i == len_srcs:
  420. srcs.append(self.input_proj[i](src_feats[-1]))
  421. else:
  422. srcs.append(self.input_proj[i](srcs[-1]))
  423. src_flatten = []
  424. mask_flatten = []
  425. lvl_pos_embed_flatten = []
  426. spatial_shapes = []
  427. valid_ratios = []
  428. for level, src in enumerate(srcs):
  429. bs, _, h, w = paddle.shape(src)
  430. spatial_shapes.append(paddle.concat([h, w]))
  431. src = src.flatten(2).transpose([0, 2, 1])
  432. src_flatten.append(src)
  433. if src_mask is not None:
  434. mask = F.interpolate(src_mask.unsqueeze(0), size=(h, w))[0]
  435. else:
  436. mask = paddle.ones([bs, h, w])
  437. valid_ratios.append(get_valid_ratio(mask))
  438. pos_embed = self.position_embedding(mask).flatten(1, 2)
  439. lvl_pos_embed = pos_embed + self.level_embed.weight[level]
  440. lvl_pos_embed_flatten.append(lvl_pos_embed)
  441. mask = mask.flatten(1)
  442. mask_flatten.append(mask)
  443. src_flatten = paddle.concat(src_flatten, 1)
  444. mask_flatten = None if src_mask is None else paddle.concat(mask_flatten,
  445. 1)
  446. lvl_pos_embed_flatten = paddle.concat(lvl_pos_embed_flatten, 1)
  447. # [l, 2]
  448. spatial_shapes = paddle.to_tensor(
  449. paddle.stack(spatial_shapes).astype('int64'))
  450. # [l], 每一个level的起始index
  451. level_start_index = paddle.concat([
  452. paddle.zeros(
  453. [1], dtype='int64'), spatial_shapes.prod(1).cumsum(0)[:-1]
  454. ])
  455. # [b, l, 2]
  456. valid_ratios = paddle.stack(valid_ratios, 1)
  457. # encoder
  458. memory = self.encoder(src_flatten, spatial_shapes, level_start_index,
  459. mask_flatten, lvl_pos_embed_flatten, valid_ratios)
  460. # prepare input for decoder
  461. bs, _, c = memory.shape
  462. query_embed = self.query_pos_embed.weight.unsqueeze(0).tile([bs, 1, 1])
  463. tgt = self.tgt_embed.weight.unsqueeze(0).tile([bs, 1, 1])
  464. reference_points = F.sigmoid(self.reference_points(query_embed))
  465. reference_points_input = reference_points.unsqueeze(
  466. 2) * valid_ratios.unsqueeze(1)
  467. # decoder
  468. hs = self.decoder(tgt, reference_points_input, memory, spatial_shapes,
  469. level_start_index, mask_flatten, query_embed)
  470. return (hs, memory, reference_points)