deformable_transformer.py 20.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
# Copyright (c) 2021 PaddlePaddle Authors. 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.
14 15 16
#
# Modified from Deformable-DETR (https://github.com/fundamentalvision/Deformable-DETR)
# Copyright (c) 2020 SenseTime. All Rights Reserved.
17 18 19 20 21 22 23 24 25 26 27 28 29 30

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import math
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddle import ParamAttr

from ppdet.core.workspace import register
from ..layers import MultiHeadAttention
from .position_encoding import PositionEmbedding
31
from .utils import _get_clones, get_valid_ratio
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
from ..initializer import linear_init_, constant_, xavier_uniform_, normal_

__all__ = ['DeformableTransformer']


class MSDeformableAttention(nn.Layer):
    def __init__(self,
                 embed_dim=256,
                 num_heads=8,
                 num_levels=4,
                 num_points=4,
                 lr_mult=0.1):
        """
        Multi-Scale Deformable Attention Module
        """
        super(MSDeformableAttention, self).__init__()
        self.embed_dim = embed_dim
        self.num_heads = num_heads
        self.num_levels = num_levels
        self.num_points = num_points
        self.total_points = num_heads * num_levels * num_points

        self.head_dim = embed_dim // num_heads
        assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads"

        self.sampling_offsets = nn.Linear(
            embed_dim,
            self.total_points * 2,
            weight_attr=ParamAttr(learning_rate=lr_mult),
            bias_attr=ParamAttr(learning_rate=lr_mult))

        self.attention_weights = nn.Linear(embed_dim, self.total_points)
        self.value_proj = nn.Linear(embed_dim, embed_dim)
        self.output_proj = nn.Linear(embed_dim, embed_dim)
66 67 68 69 70 71 72
        try:
            # use cuda op
            from deformable_detr_ops import ms_deformable_attn
        except:
            # use paddle func
            from .utils import deformable_attention_core_func as ms_deformable_attn
        self.ms_deformable_attn_core = ms_deformable_attn
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

        self._reset_parameters()

    def _reset_parameters(self):
        # sampling_offsets
        constant_(self.sampling_offsets.weight)
        thetas = paddle.arange(
            self.num_heads,
            dtype=paddle.float32) * (2.0 * math.pi / self.num_heads)
        grid_init = paddle.stack([thetas.cos(), thetas.sin()], -1)
        grid_init = grid_init / grid_init.abs().max(-1, keepdim=True)
        grid_init = grid_init.reshape([self.num_heads, 1, 1, 2]).tile(
            [1, self.num_levels, self.num_points, 1])
        scaling = paddle.arange(
            1, self.num_points + 1,
            dtype=paddle.float32).reshape([1, 1, -1, 1])
        grid_init *= scaling
        self.sampling_offsets.bias.set_value(grid_init.flatten())
        # attention_weights
        constant_(self.attention_weights.weight)
        constant_(self.attention_weights.bias)
        # proj
        xavier_uniform_(self.value_proj.weight)
        constant_(self.value_proj.bias)
        xavier_uniform_(self.output_proj.weight)
        constant_(self.output_proj.bias)

    def forward(self,
                query,
                reference_points,
                value,
                value_spatial_shapes,
105
                value_level_start_index,
106 107 108 109 110 111 112 113
                value_mask=None):
        """
        Args:
            query (Tensor): [bs, query_length, C]
            reference_points (Tensor): [bs, query_length, n_levels, 2], range in [0, 1], top-left (0,0),
                bottom-right (1, 1), including padding area
            value (Tensor): [bs, value_length, C]
            value_spatial_shapes (Tensor): [n_levels, 2], [(H_0, W_0), (H_1, W_1), ..., (H_{L-1}, W_{L-1})]
114
            value_level_start_index (Tensor(int64)): [n_levels], [0, H_0*W_0, H_0*W_0+H_1*W_1, ...]
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
            value_mask (Tensor): [bs, value_length], True for non-padding elements, False for padding elements

        Returns:
            output (Tensor): [bs, Length_{query}, C]
        """
        bs, Len_q = query.shape[:2]
        Len_v = value.shape[1]
        assert int(value_spatial_shapes.prod(1).sum()) == Len_v

        value = self.value_proj(value)
        if value_mask is not None:
            value_mask = value_mask.astype(value.dtype).unsqueeze(-1)
            value *= value_mask
        value = value.reshape([bs, Len_v, self.num_heads, self.head_dim])

        sampling_offsets = self.sampling_offsets(query).reshape(
            [bs, Len_q, self.num_heads, self.num_levels, self.num_points, 2])
        attention_weights = self.attention_weights(query).reshape(
            [bs, Len_q, self.num_heads, self.num_levels * self.num_points])
S
shangliang Xu 已提交
134
        attention_weights = F.softmax(attention_weights).reshape(
135 136
            [bs, Len_q, self.num_heads, self.num_levels, self.num_points])

S
shangliang Xu 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
        if reference_points.shape[-1] == 2:
            offset_normalizer = value_spatial_shapes.flip([1]).reshape(
                [1, 1, 1, self.num_levels, 1, 2])
            sampling_locations = reference_points.reshape([
                bs, Len_q, 1, self.num_levels, 1, 2
            ]) + sampling_offsets / offset_normalizer
        elif reference_points.shape[-1] == 4:
            sampling_locations = (
                reference_points[:, :, None, :, None, :2] + sampling_offsets /
                self.num_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]))
152

153 154 155
        output = self.ms_deformable_attn_core(
            value, value_spatial_shapes, value_level_start_index,
            sampling_locations, attention_weights)
156 157 158 159 160 161 162 163 164 165 166 167 168 169
        output = self.output_proj(output)

        return output


class DeformableTransformerEncoderLayer(nn.Layer):
    def __init__(self,
                 d_model=256,
                 n_head=8,
                 dim_feedforward=1024,
                 dropout=0.1,
                 activation="relu",
                 n_levels=4,
                 n_points=4,
170
                 lr_mult=0.1,
171 172 173 174 175
                 weight_attr=None,
                 bias_attr=None):
        super(DeformableTransformerEncoderLayer, self).__init__()
        # self attention
        self.self_attn = MSDeformableAttention(d_model, n_head, n_levels,
176
                                               n_points, lr_mult)
177
        self.dropout1 = nn.Dropout(dropout)
178 179
        self.norm1 = nn.LayerNorm(
            d_model, weight_attr=weight_attr, bias_attr=bias_attr)
180
        # ffn
181
        self.linear1 = nn.Linear(d_model, dim_feedforward)
182 183
        self.activation = getattr(F, activation)
        self.dropout2 = nn.Dropout(dropout)
184
        self.linear2 = nn.Linear(dim_feedforward, d_model)
185
        self.dropout3 = nn.Dropout(dropout)
186 187
        self.norm2 = nn.LayerNorm(
            d_model, weight_attr=weight_attr, bias_attr=bias_attr)
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
        self._reset_parameters()

    def _reset_parameters(self):
        linear_init_(self.linear1)
        linear_init_(self.linear2)
        xavier_uniform_(self.linear1.weight)
        xavier_uniform_(self.linear2.weight)

    def with_pos_embed(self, 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,
                reference_points,
                spatial_shapes,
209
                level_start_index,
210
                src_mask=None,
211
                query_pos_embed=None):
212 213
        # self attention
        src2 = self.self_attn(
214
            self.with_pos_embed(src, query_pos_embed), reference_points, src,
215
            spatial_shapes, level_start_index, src_mask)
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
        src = src + self.dropout1(src2)
        src = self.norm1(src)
        # ffn
        src = self.forward_ffn(src)

        return src


class DeformableTransformerEncoder(nn.Layer):
    def __init__(self, encoder_layer, num_layers):
        super(DeformableTransformerEncoder, self).__init__()
        self.layers = _get_clones(encoder_layer, num_layers)
        self.num_layers = num_layers

    @staticmethod
231
    def get_reference_points(spatial_shapes, valid_ratios, offset=0.5):
232 233
        valid_ratios = valid_ratios.unsqueeze(1)
        reference_points = []
234
        for i, (H, W) in enumerate(spatial_shapes):
235
            ref_y, ref_x = paddle.meshgrid(
236
                paddle.arange(end=H) + offset, paddle.arange(end=W) + offset)
237 238 239 240 241 242 243 244 245 246
            ref_y = ref_y.flatten().unsqueeze(0) / (valid_ratios[:, :, i, 1] *
                                                    H)
            ref_x = ref_x.flatten().unsqueeze(0) / (valid_ratios[:, :, i, 0] *
                                                    W)
            reference_points.append(paddle.stack((ref_x, ref_y), axis=-1))
        reference_points = paddle.concat(reference_points, 1).unsqueeze(2)
        reference_points = reference_points * valid_ratios
        return reference_points

    def forward(self,
247
                feat,
248
                spatial_shapes,
249
                level_start_index,
250 251
                feat_mask=None,
                query_pos_embed=None,
252 253 254
                valid_ratios=None):
        if valid_ratios is None:
            valid_ratios = paddle.ones(
255
                [feat.shape[0], spatial_shapes.shape[0], 2])
256 257 258
        reference_points = self.get_reference_points(spatial_shapes,
                                                     valid_ratios)
        for layer in self.layers:
259 260
            feat = layer(feat, reference_points, spatial_shapes,
                         level_start_index, feat_mask, query_pos_embed)
261

262
        return feat
263 264 265 266 267 268 269 270 271 272 273


class DeformableTransformerDecoderLayer(nn.Layer):
    def __init__(self,
                 d_model=256,
                 n_head=8,
                 dim_feedforward=1024,
                 dropout=0.1,
                 activation="relu",
                 n_levels=4,
                 n_points=4,
274
                 lr_mult=0.1,
275 276 277 278 279 280 281
                 weight_attr=None,
                 bias_attr=None):
        super(DeformableTransformerDecoderLayer, self).__init__()

        # self attention
        self.self_attn = MultiHeadAttention(d_model, n_head, dropout=dropout)
        self.dropout1 = nn.Dropout(dropout)
282 283
        self.norm1 = nn.LayerNorm(
            d_model, weight_attr=weight_attr, bias_attr=bias_attr)
284 285 286

        # cross attention
        self.cross_attn = MSDeformableAttention(d_model, n_head, n_levels,
287
                                                n_points, lr_mult)
288
        self.dropout2 = nn.Dropout(dropout)
289 290
        self.norm2 = nn.LayerNorm(
            d_model, weight_attr=weight_attr, bias_attr=bias_attr)
291 292

        # ffn
293
        self.linear1 = nn.Linear(d_model, dim_feedforward)
294 295
        self.activation = getattr(F, activation)
        self.dropout3 = nn.Dropout(dropout)
296
        self.linear2 = nn.Linear(dim_feedforward, d_model)
297
        self.dropout4 = nn.Dropout(dropout)
298 299
        self.norm3 = nn.LayerNorm(
            d_model, weight_attr=weight_attr, bias_attr=bias_attr)
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
        self._reset_parameters()

    def _reset_parameters(self):
        linear_init_(self.linear1)
        linear_init_(self.linear2)
        xavier_uniform_(self.linear1.weight)
        xavier_uniform_(self.linear2.weight)

    def with_pos_embed(self, 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,
                reference_points,
                memory,
                memory_spatial_shapes,
322
                memory_level_start_index,
323 324 325 326 327 328 329 330 331 332 333
                memory_mask=None,
                query_pos_embed=None):
        # self attention
        q = k = self.with_pos_embed(tgt, query_pos_embed)
        tgt2 = self.self_attn(q, k, value=tgt)
        tgt = tgt + self.dropout1(tgt2)
        tgt = self.norm1(tgt)

        # cross attention
        tgt2 = self.cross_attn(
            self.with_pos_embed(tgt, query_pos_embed), reference_points, memory,
334
            memory_spatial_shapes, memory_level_start_index, memory_mask)
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
        tgt = tgt + self.dropout2(tgt2)
        tgt = self.norm2(tgt)

        # ffn
        tgt = self.forward_ffn(tgt)

        return tgt


class DeformableTransformerDecoder(nn.Layer):
    def __init__(self, decoder_layer, num_layers, return_intermediate=False):
        super(DeformableTransformerDecoder, self).__init__()
        self.layers = _get_clones(decoder_layer, num_layers)
        self.num_layers = num_layers
        self.return_intermediate = return_intermediate

    def forward(self,
                tgt,
                reference_points,
                memory,
                memory_spatial_shapes,
356
                memory_level_start_index,
357 358 359 360 361 362
                memory_mask=None,
                query_pos_embed=None):
        output = tgt
        intermediate = []
        for lid, layer in enumerate(self.layers):
            output = layer(output, reference_points, memory,
363 364
                           memory_spatial_shapes, memory_level_start_index,
                           memory_mask, query_pos_embed)
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382

            if self.return_intermediate:
                intermediate.append(output)

        if self.return_intermediate:
            return paddle.stack(intermediate)

        return output.unsqueeze(0)


@register
class DeformableTransformer(nn.Layer):
    __shared__ = ['hidden_dim']

    def __init__(self,
                 num_queries=300,
                 position_embed_type='sine',
                 return_intermediate_dec=True,
383
                 in_feats_channel=[512, 1024, 2048],
384 385 386 387 388 389 390 391 392 393 394
                 num_feature_levels=4,
                 num_encoder_points=4,
                 num_decoder_points=4,
                 hidden_dim=256,
                 nhead=8,
                 num_encoder_layers=6,
                 num_decoder_layers=6,
                 dim_feedforward=1024,
                 dropout=0.1,
                 activation="relu",
                 lr_mult=0.1,
395 396
                 pe_temperature=10000,
                 pe_offset=-0.5):
397 398 399
        super(DeformableTransformer, self).__init__()
        assert position_embed_type in ['sine', 'learned'], \
            f'ValueError: position_embed_type not supported {position_embed_type}!'
400
        assert len(in_feats_channel) <= num_feature_levels
401 402 403 404 405 406 407

        self.hidden_dim = hidden_dim
        self.nhead = nhead
        self.num_feature_levels = num_feature_levels

        encoder_layer = DeformableTransformerEncoderLayer(
            hidden_dim, nhead, dim_feedforward, dropout, activation,
408
            num_feature_levels, num_encoder_points, lr_mult)
409 410 411 412 413
        self.encoder = DeformableTransformerEncoder(encoder_layer,
                                                    num_encoder_layers)

        decoder_layer = DeformableTransformerDecoderLayer(
            hidden_dim, nhead, dim_feedforward, dropout, activation,
414
            num_feature_levels, num_decoder_points)
415 416 417 418 419 420 421 422 423 424 425 426 427 428
        self.decoder = DeformableTransformerDecoder(
            decoder_layer, num_decoder_layers, return_intermediate_dec)

        self.level_embed = nn.Embedding(num_feature_levels, hidden_dim)
        self.tgt_embed = nn.Embedding(num_queries, hidden_dim)
        self.query_pos_embed = nn.Embedding(num_queries, hidden_dim)

        self.reference_points = nn.Linear(
            hidden_dim,
            2,
            weight_attr=ParamAttr(learning_rate=lr_mult),
            bias_attr=ParamAttr(learning_rate=lr_mult))

        self.input_proj = nn.LayerList()
429
        for in_channels in in_feats_channel:
430 431 432
            self.input_proj.append(
                nn.Sequential(
                    nn.Conv2D(
433
                        in_channels, hidden_dim, kernel_size=1),
434
                    nn.GroupNorm(32, hidden_dim)))
435 436
        in_channels = in_feats_channel[-1]
        for _ in range(num_feature_levels - len(in_feats_channel)):
437 438 439 440 441 442 443
            self.input_proj.append(
                nn.Sequential(
                    nn.Conv2D(
                        in_channels,
                        hidden_dim,
                        kernel_size=3,
                        stride=2,
444
                        padding=1),
445 446 447 448 449
                    nn.GroupNorm(32, hidden_dim)))
            in_channels = hidden_dim

        self.position_embedding = PositionEmbedding(
            hidden_dim // 2,
450
            temperature=pe_temperature,
451 452
            normalize=True if position_embed_type == 'sine' else False,
            embed_type=position_embed_type,
L
LokeZhou 已提交
453 454
            offset=pe_offset,
            eps=1e-4)
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469

        self._reset_parameters()

    def _reset_parameters(self):
        normal_(self.level_embed.weight)
        normal_(self.tgt_embed.weight)
        normal_(self.query_pos_embed.weight)
        xavier_uniform_(self.reference_points.weight)
        constant_(self.reference_points.bias)
        for l in self.input_proj:
            xavier_uniform_(l[0].weight)
            constant_(l[0].bias)

    @classmethod
    def from_config(cls, cfg, input_shape):
470
        return {'in_feats_channel': [i.channels for i in input_shape], }
471

472
    def forward(self, src_feats, src_mask=None, *args, **kwargs):
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
        srcs = []
        for i in range(len(src_feats)):
            srcs.append(self.input_proj[i](src_feats[i]))
        if self.num_feature_levels > len(srcs):
            len_srcs = len(srcs)
            for i in range(len_srcs, self.num_feature_levels):
                if i == len_srcs:
                    srcs.append(self.input_proj[i](src_feats[-1]))
                else:
                    srcs.append(self.input_proj[i](srcs[-1]))
        src_flatten = []
        mask_flatten = []
        lvl_pos_embed_flatten = []
        spatial_shapes = []
        valid_ratios = []
        for level, src in enumerate(srcs):
489 490 491 492
            src_shape = paddle.shape(src)
            bs = src_shape[0:1]
            h = src_shape[2:3]
            w = src_shape[3:4]
493
            spatial_shapes.append(paddle.concat([h, w]))
494 495 496
            src = src.flatten(2).transpose([0, 2, 1])
            src_flatten.append(src)
            if src_mask is not None:
497
                mask = F.interpolate(src_mask.unsqueeze(0), size=(h, w))[0]
498
            else:
499
                mask = paddle.ones([bs, h, w])
500 501 502
            valid_ratios.append(get_valid_ratio(mask))
            pos_embed = self.position_embedding(mask).flatten(1, 2)
            lvl_pos_embed = pos_embed + self.level_embed.weight[level]
503
            lvl_pos_embed_flatten.append(lvl_pos_embed)
504
            mask = mask.flatten(1)
505 506
            mask_flatten.append(mask)
        src_flatten = paddle.concat(src_flatten, 1)
507 508
        mask_flatten = None if src_mask is None else paddle.concat(mask_flatten,
                                                                   1)
509 510
        lvl_pos_embed_flatten = paddle.concat(lvl_pos_embed_flatten, 1)
        # [l, 2]
511 512 513 514 515 516 517
        spatial_shapes = paddle.to_tensor(
            paddle.stack(spatial_shapes).astype('int64'))
        # [l], 每一个level的起始index
        level_start_index = paddle.concat([
            paddle.zeros(
                [1], dtype='int64'), spatial_shapes.prod(1).cumsum(0)[:-1]
        ])
518 519 520 521
        # [b, l, 2]
        valid_ratios = paddle.stack(valid_ratios, 1)

        # encoder
522 523
        memory = self.encoder(src_flatten, spatial_shapes, level_start_index,
                              mask_flatten, lvl_pos_embed_flatten, valid_ratios)
524 525 526 527 528 529 530 531 532 533 534

        # prepare input for decoder
        bs, _, c = memory.shape
        query_embed = self.query_pos_embed.weight.unsqueeze(0).tile([bs, 1, 1])
        tgt = self.tgt_embed.weight.unsqueeze(0).tile([bs, 1, 1])
        reference_points = F.sigmoid(self.reference_points(query_embed))
        reference_points_input = reference_points.unsqueeze(
            2) * valid_ratios.unsqueeze(1)

        # decoder
        hs = self.decoder(tgt, reference_points_input, memory, spatial_shapes,
535
                          level_start_index, mask_flatten, query_embed)
536 537

        return (hs, memory, reference_points)