Spaces:
Runtime error
Runtime error
File size: 13,965 Bytes
f549064 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 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 66 67 68 69 70 71 72 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 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 |
# Copyright (c) OpenMMLab. All rights reserved.
from typing import Union
import torch
from mmcv.cnn import build_norm_layer
from mmcv.cnn.bricks.transformer import FFN, MultiheadAttention
from mmengine import ConfigDict
from mmengine.model import BaseModule, ModuleList
from torch import Tensor
from mmdet.utils import ConfigType, OptConfigType
class DetrTransformerEncoder(BaseModule):
"""Encoder of DETR.
Args:
num_layers (int): Number of encoder layers.
layer_cfg (:obj:`ConfigDict` or dict): the config of each encoder
layer. All the layers will share the same config.
init_cfg (:obj:`ConfigDict` or dict, optional): the config to control
the initialization. Defaults to None.
"""
def __init__(self,
num_layers: int,
layer_cfg: ConfigType,
init_cfg: OptConfigType = None) -> None:
super().__init__(init_cfg=init_cfg)
self.num_layers = num_layers
self.layer_cfg = layer_cfg
self._init_layers()
def _init_layers(self) -> None:
"""Initialize encoder layers."""
self.layers = ModuleList([
DetrTransformerEncoderLayer(**self.layer_cfg)
for _ in range(self.num_layers)
])
self.embed_dims = self.layers[0].embed_dims
def forward(self, query: Tensor, query_pos: Tensor,
key_padding_mask: Tensor, **kwargs) -> Tensor:
"""Forward function of encoder.
Args:
query (Tensor): Input queries of encoder, has shape
(bs, num_queries, dim).
query_pos (Tensor): The positional embeddings of the queries, has
shape (bs, num_queries, dim).
key_padding_mask (Tensor): The `key_padding_mask` of `self_attn`
input. ByteTensor, has shape (bs, num_queries).
Returns:
Tensor: Has shape (bs, num_queries, dim) if `batch_first` is
`True`, otherwise (num_queries, bs, dim).
"""
for layer in self.layers:
query = layer(query, query_pos, key_padding_mask, **kwargs)
return query
class DetrTransformerDecoder(BaseModule):
"""Decoder of DETR.
Args:
num_layers (int): Number of decoder layers.
layer_cfg (:obj:`ConfigDict` or dict): the config of each encoder
layer. All the layers will share the same config.
post_norm_cfg (:obj:`ConfigDict` or dict, optional): Config of the
post normalization layer. Defaults to `LN`.
return_intermediate (bool, optional): Whether to return outputs of
intermediate layers. Defaults to `True`,
init_cfg (:obj:`ConfigDict` or dict, optional): the config to control
the initialization. Defaults to None.
"""
def __init__(self,
num_layers: int,
layer_cfg: ConfigType,
post_norm_cfg: OptConfigType = dict(type='LN'),
return_intermediate: bool = True,
init_cfg: Union[dict, ConfigDict] = None) -> None:
super().__init__(init_cfg=init_cfg)
self.layer_cfg = layer_cfg
self.num_layers = num_layers
self.post_norm_cfg = post_norm_cfg
self.return_intermediate = return_intermediate
self._init_layers()
def _init_layers(self) -> None:
"""Initialize decoder layers."""
self.layers = ModuleList([
DetrTransformerDecoderLayer(**self.layer_cfg)
for _ in range(self.num_layers)
])
self.embed_dims = self.layers[0].embed_dims
self.post_norm = build_norm_layer(self.post_norm_cfg,
self.embed_dims)[1]
def forward(self, query: Tensor, key: Tensor, value: Tensor,
query_pos: Tensor, key_pos: Tensor, key_padding_mask: Tensor,
**kwargs) -> Tensor:
"""Forward function of decoder
Args:
query (Tensor): The input query, has shape (bs, num_queries, dim).
key (Tensor): The input key, has shape (bs, num_keys, dim).
value (Tensor): The input value with the same shape as `key`.
query_pos (Tensor): The positional encoding for `query`, with the
same shape as `query`.
key_pos (Tensor): The positional encoding for `key`, with the
same shape as `key`.
key_padding_mask (Tensor): The `key_padding_mask` of `cross_attn`
input. ByteTensor, has shape (bs, num_value).
Returns:
Tensor: The forwarded results will have shape
(num_decoder_layers, bs, num_queries, dim) if
`return_intermediate` is `True` else (1, bs, num_queries, dim).
"""
intermediate = []
for layer in self.layers:
query = layer(
query,
key=key,
value=value,
query_pos=query_pos,
key_pos=key_pos,
key_padding_mask=key_padding_mask,
**kwargs)
if self.return_intermediate:
intermediate.append(self.post_norm(query))
query = self.post_norm(query)
if self.return_intermediate:
return torch.stack(intermediate)
return query.unsqueeze(0)
class DetrTransformerEncoderLayer(BaseModule):
"""Implements encoder layer in DETR transformer.
Args:
self_attn_cfg (:obj:`ConfigDict` or dict, optional): Config for self
attention.
ffn_cfg (:obj:`ConfigDict` or dict, optional): Config for FFN.
norm_cfg (:obj:`ConfigDict` or dict, optional): Config for
normalization layers. All the layers will share the same
config. Defaults to `LN`.
init_cfg (:obj:`ConfigDict` or dict, optional): Config to control
the initialization. Defaults to None.
"""
def __init__(self,
self_attn_cfg: OptConfigType = dict(
embed_dims=256, num_heads=8, dropout=0.0),
ffn_cfg: OptConfigType = dict(
embed_dims=256,
feedforward_channels=1024,
num_fcs=2,
ffn_drop=0.,
act_cfg=dict(type='ReLU', inplace=True)),
norm_cfg: OptConfigType = dict(type='LN'),
init_cfg: OptConfigType = None) -> None:
super().__init__(init_cfg=init_cfg)
self.self_attn_cfg = self_attn_cfg
if 'batch_first' not in self.self_attn_cfg:
self.self_attn_cfg['batch_first'] = True
else:
assert self.self_attn_cfg['batch_first'] is True, 'First \
dimension of all DETRs in mmdet is `batch`, \
please set `batch_first` flag.'
self.ffn_cfg = ffn_cfg
self.norm_cfg = norm_cfg
self._init_layers()
def _init_layers(self) -> None:
"""Initialize self-attention, FFN, and normalization."""
self.self_attn = MultiheadAttention(**self.self_attn_cfg)
self.embed_dims = self.self_attn.embed_dims
self.ffn = FFN(**self.ffn_cfg)
norms_list = [
build_norm_layer(self.norm_cfg, self.embed_dims)[1]
for _ in range(2)
]
self.norms = ModuleList(norms_list)
def forward(self, query: Tensor, query_pos: Tensor,
key_padding_mask: Tensor, **kwargs) -> Tensor:
"""Forward function of an encoder layer.
Args:
query (Tensor): The input query, has shape (bs, num_queries, dim).
query_pos (Tensor): The positional encoding for query, with
the same shape as `query`.
key_padding_mask (Tensor): The `key_padding_mask` of `self_attn`
input. ByteTensor. has shape (bs, num_queries).
Returns:
Tensor: forwarded results, has shape (bs, num_queries, dim).
"""
query = self.self_attn(
query=query,
key=query,
value=query,
query_pos=query_pos,
key_pos=query_pos,
key_padding_mask=key_padding_mask,
**kwargs)
query = self.norms[0](query)
query = self.ffn(query)
query = self.norms[1](query)
return query
class DetrTransformerDecoderLayer(BaseModule):
"""Implements decoder layer in DETR transformer.
Args:
self_attn_cfg (:obj:`ConfigDict` or dict, optional): Config for self
attention.
cross_attn_cfg (:obj:`ConfigDict` or dict, optional): Config for cross
attention.
ffn_cfg (:obj:`ConfigDict` or dict, optional): Config for FFN.
norm_cfg (:obj:`ConfigDict` or dict, optional): Config for
normalization layers. All the layers will share the same
config. Defaults to `LN`.
init_cfg (:obj:`ConfigDict` or dict, optional): Config to control
the initialization. Defaults to None.
"""
def __init__(self,
self_attn_cfg: OptConfigType = dict(
embed_dims=256,
num_heads=8,
dropout=0.0,
batch_first=True),
cross_attn_cfg: OptConfigType = dict(
embed_dims=256,
num_heads=8,
dropout=0.0,
batch_first=True),
ffn_cfg: OptConfigType = dict(
embed_dims=256,
feedforward_channels=1024,
num_fcs=2,
ffn_drop=0.,
act_cfg=dict(type='ReLU', inplace=True),
),
norm_cfg: OptConfigType = dict(type='LN'),
init_cfg: OptConfigType = None) -> None:
super().__init__(init_cfg=init_cfg)
self.self_attn_cfg = self_attn_cfg
self.cross_attn_cfg = cross_attn_cfg
if 'batch_first' not in self.self_attn_cfg:
self.self_attn_cfg['batch_first'] = True
else:
assert self.self_attn_cfg['batch_first'] is True, 'First \
dimension of all DETRs in mmdet is `batch`, \
please set `batch_first` flag.'
if 'batch_first' not in self.cross_attn_cfg:
self.cross_attn_cfg['batch_first'] = True
else:
assert self.cross_attn_cfg['batch_first'] is True, 'First \
dimension of all DETRs in mmdet is `batch`, \
please set `batch_first` flag.'
self.ffn_cfg = ffn_cfg
self.norm_cfg = norm_cfg
self._init_layers()
def _init_layers(self) -> None:
"""Initialize self-attention, FFN, and normalization."""
self.self_attn = MultiheadAttention(**self.self_attn_cfg)
self.cross_attn = MultiheadAttention(**self.cross_attn_cfg)
self.embed_dims = self.self_attn.embed_dims
self.ffn = FFN(**self.ffn_cfg)
norms_list = [
build_norm_layer(self.norm_cfg, self.embed_dims)[1]
for _ in range(3)
]
self.norms = ModuleList(norms_list)
def forward(self,
query: Tensor,
key: Tensor = None,
value: Tensor = None,
query_pos: Tensor = None,
key_pos: Tensor = None,
self_attn_mask: Tensor = None,
cross_attn_mask: Tensor = None,
key_padding_mask: Tensor = None,
**kwargs) -> Tensor:
"""
Args:
query (Tensor): The input query, has shape (bs, num_queries, dim).
key (Tensor, optional): The input key, has shape (bs, num_keys,
dim). If `None`, the `query` will be used. Defaults to `None`.
value (Tensor, optional): The input value, has the same shape as
`key`, as in `nn.MultiheadAttention.forward`. If `None`, the
`key` will be used. Defaults to `None`.
query_pos (Tensor, optional): The positional encoding for `query`,
has the same shape as `query`. If not `None`, it will be added
to `query` before forward function. Defaults to `None`.
key_pos (Tensor, optional): The positional encoding for `key`, has
the same shape as `key`. If not `None`, it will be added to
`key` before forward function. If None, and `query_pos` has the
same shape as `key`, then `query_pos` will be used for
`key_pos`. Defaults to None.
self_attn_mask (Tensor, optional): ByteTensor mask, has shape
(num_queries, num_keys), as in `nn.MultiheadAttention.forward`.
Defaults to None.
cross_attn_mask (Tensor, optional): ByteTensor mask, has shape
(num_queries, num_keys), as in `nn.MultiheadAttention.forward`.
Defaults to None.
key_padding_mask (Tensor, optional): The `key_padding_mask` of
`self_attn` input. ByteTensor, has shape (bs, num_value).
Defaults to None.
Returns:
Tensor: forwarded results, has shape (bs, num_queries, dim).
"""
query = self.self_attn(
query=query,
key=query,
value=query,
query_pos=query_pos,
key_pos=query_pos,
attn_mask=self_attn_mask,
**kwargs)
query = self.norms[0](query)
query = self.cross_attn(
query=query,
key=key,
value=value,
query_pos=query_pos,
key_pos=key_pos,
attn_mask=cross_attn_mask,
key_padding_mask=key_padding_mask,
**kwargs)
query = self.norms[1](query)
query = self.ffn(query)
query = self.norms[2](query)
return query
|