modeling_detr.py 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693
  1. # coding=utf-8
  2. # Copyright 2021 Facebook AI Research The HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """PyTorch DETR model."""
  16. import math
  17. from dataclasses import dataclass
  18. from typing import Optional, Union
  19. import torch
  20. from torch import Tensor, nn
  21. from ...activations import ACT2FN
  22. from ...modeling_attn_mask_utils import _prepare_4d_attention_mask
  23. from ...modeling_layers import GradientCheckpointingLayer
  24. from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithCrossAttentions, Seq2SeqModelOutput
  25. from ...modeling_utils import PreTrainedModel
  26. from ...utils import (
  27. ModelOutput,
  28. auto_docstring,
  29. is_timm_available,
  30. logging,
  31. requires_backends,
  32. )
  33. from ...utils.backbone_utils import load_backbone
  34. from .configuration_detr import DetrConfig
  35. if is_timm_available():
  36. from timm import create_model
  37. logger = logging.get_logger(__name__)
  38. @dataclass
  39. @auto_docstring(
  40. custom_intro="""
  41. Base class for outputs of the DETR decoder. This class adds one attribute to BaseModelOutputWithCrossAttentions,
  42. namely an optional stack of intermediate decoder activations, i.e. the output of each decoder layer, each of them
  43. gone through a layernorm. This is useful when training the model with auxiliary decoding losses.
  44. """
  45. )
  46. class DetrDecoderOutput(BaseModelOutputWithCrossAttentions):
  47. r"""
  48. cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`):
  49. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  50. sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax,
  51. used to compute the weighted average in the cross-attention heads.
  52. intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, num_queries, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):
  53. Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
  54. layernorm.
  55. """
  56. intermediate_hidden_states: Optional[torch.FloatTensor] = None
  57. @dataclass
  58. @auto_docstring(
  59. custom_intro="""
  60. Base class for outputs of the DETR encoder-decoder model. This class adds one attribute to Seq2SeqModelOutput,
  61. namely an optional stack of intermediate decoder activations, i.e. the output of each decoder layer, each of them
  62. gone through a layernorm. This is useful when training the model with auxiliary decoding losses.
  63. """
  64. )
  65. class DetrModelOutput(Seq2SeqModelOutput):
  66. r"""
  67. last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
  68. Sequence of hidden-states at the output of the last layer of the decoder of the model.
  69. intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers, batch_size, sequence_length, hidden_size)`, *optional*, returned when `config.auxiliary_loss=True`):
  70. Intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a
  71. layernorm.
  72. """
  73. intermediate_hidden_states: Optional[torch.FloatTensor] = None
  74. @dataclass
  75. @auto_docstring(
  76. custom_intro="""
  77. Output type of [`DetrForObjectDetection`].
  78. """
  79. )
  80. class DetrObjectDetectionOutput(ModelOutput):
  81. r"""
  82. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
  83. Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
  84. bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
  85. scale-invariant IoU loss.
  86. loss_dict (`Dict`, *optional*):
  87. A dictionary containing the individual losses. Useful for logging.
  88. logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`):
  89. Classification logits (including no-object) for all queries.
  90. pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
  91. Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
  92. values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
  93. possible padding). You can use [`~DetrImageProcessor.post_process_object_detection`] to retrieve the
  94. unnormalized bounding boxes.
  95. auxiliary_outputs (`list[Dict]`, *optional*):
  96. Optional, only returned when auxiliary losses are activated (i.e. `config.auxiliary_loss` is set to `True`)
  97. and labels are provided. It is a list of dictionaries containing the two above keys (`logits` and
  98. `pred_boxes`) for each decoder layer.
  99. last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  100. Sequence of hidden-states at the output of the last layer of the decoder of the model.
  101. """
  102. loss: Optional[torch.FloatTensor] = None
  103. loss_dict: Optional[dict] = None
  104. logits: Optional[torch.FloatTensor] = None
  105. pred_boxes: Optional[torch.FloatTensor] = None
  106. auxiliary_outputs: Optional[list[dict]] = None
  107. last_hidden_state: Optional[torch.FloatTensor] = None
  108. decoder_hidden_states: Optional[tuple[torch.FloatTensor]] = None
  109. decoder_attentions: Optional[tuple[torch.FloatTensor]] = None
  110. cross_attentions: Optional[tuple[torch.FloatTensor]] = None
  111. encoder_last_hidden_state: Optional[torch.FloatTensor] = None
  112. encoder_hidden_states: Optional[tuple[torch.FloatTensor]] = None
  113. encoder_attentions: Optional[tuple[torch.FloatTensor]] = None
  114. @dataclass
  115. @auto_docstring(
  116. custom_intro="""
  117. Output type of [`DetrForSegmentation`].
  118. """
  119. )
  120. class DetrSegmentationOutput(ModelOutput):
  121. r"""
  122. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
  123. Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
  124. bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
  125. scale-invariant IoU loss.
  126. loss_dict (`Dict`, *optional*):
  127. A dictionary containing the individual losses. Useful for logging.
  128. logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`):
  129. Classification logits (including no-object) for all queries.
  130. pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
  131. Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
  132. values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
  133. possible padding). You can use [`~DetrImageProcessor.post_process_object_detection`] to retrieve the
  134. unnormalized bounding boxes.
  135. pred_masks (`torch.FloatTensor` of shape `(batch_size, num_queries, height/4, width/4)`):
  136. Segmentation masks logits for all queries. See also
  137. [`~DetrImageProcessor.post_process_semantic_segmentation`] or
  138. [`~DetrImageProcessor.post_process_instance_segmentation`]
  139. [`~DetrImageProcessor.post_process_panoptic_segmentation`] to evaluate semantic, instance and panoptic
  140. segmentation masks respectively.
  141. auxiliary_outputs (`list[Dict]`, *optional*):
  142. Optional, only returned when auxiliary losses are activated (i.e. `config.auxiliary_loss` is set to `True`)
  143. and labels are provided. It is a list of dictionaries containing the two above keys (`logits` and
  144. `pred_boxes`) for each decoder layer.
  145. last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  146. Sequence of hidden-states at the output of the last layer of the decoder of the model.
  147. """
  148. loss: Optional[torch.FloatTensor] = None
  149. loss_dict: Optional[dict] = None
  150. logits: Optional[torch.FloatTensor] = None
  151. pred_boxes: Optional[torch.FloatTensor] = None
  152. pred_masks: Optional[torch.FloatTensor] = None
  153. auxiliary_outputs: Optional[list[dict]] = None
  154. last_hidden_state: Optional[torch.FloatTensor] = None
  155. decoder_hidden_states: Optional[tuple[torch.FloatTensor]] = None
  156. decoder_attentions: Optional[tuple[torch.FloatTensor]] = None
  157. cross_attentions: Optional[tuple[torch.FloatTensor]] = None
  158. encoder_last_hidden_state: Optional[torch.FloatTensor] = None
  159. encoder_hidden_states: Optional[tuple[torch.FloatTensor]] = None
  160. encoder_attentions: Optional[tuple[torch.FloatTensor]] = None
  161. # BELOW: utilities copied from
  162. # https://github.com/facebookresearch/detr/blob/master/backbone.py
  163. class DetrFrozenBatchNorm2d(nn.Module):
  164. """
  165. BatchNorm2d where the batch statistics and the affine parameters are fixed.
  166. Copy-paste from torchvision.misc.ops with added eps before rqsrt, without which any other models than
  167. torchvision.models.resnet[18,34,50,101] produce nans.
  168. """
  169. def __init__(self, n):
  170. super().__init__()
  171. self.register_buffer("weight", torch.ones(n))
  172. self.register_buffer("bias", torch.zeros(n))
  173. self.register_buffer("running_mean", torch.zeros(n))
  174. self.register_buffer("running_var", torch.ones(n))
  175. def _load_from_state_dict(
  176. self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
  177. ):
  178. num_batches_tracked_key = prefix + "num_batches_tracked"
  179. if num_batches_tracked_key in state_dict:
  180. del state_dict[num_batches_tracked_key]
  181. super()._load_from_state_dict(
  182. state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
  183. )
  184. def forward(self, x):
  185. # move reshapes to the beginning
  186. # to make it user-friendly
  187. weight = self.weight.reshape(1, -1, 1, 1)
  188. bias = self.bias.reshape(1, -1, 1, 1)
  189. running_var = self.running_var.reshape(1, -1, 1, 1)
  190. running_mean = self.running_mean.reshape(1, -1, 1, 1)
  191. epsilon = 1e-5
  192. scale = weight * (running_var + epsilon).rsqrt()
  193. bias = bias - running_mean * scale
  194. return x * scale + bias
  195. def replace_batch_norm(model):
  196. r"""
  197. Recursively replace all `torch.nn.BatchNorm2d` with `DetrFrozenBatchNorm2d`.
  198. Args:
  199. model (torch.nn.Module):
  200. input model
  201. """
  202. for name, module in model.named_children():
  203. if isinstance(module, nn.BatchNorm2d):
  204. new_module = DetrFrozenBatchNorm2d(module.num_features)
  205. if module.weight.device != torch.device("meta"):
  206. new_module.weight.data.copy_(module.weight)
  207. new_module.bias.data.copy_(module.bias)
  208. new_module.running_mean.data.copy_(module.running_mean)
  209. new_module.running_var.data.copy_(module.running_var)
  210. model._modules[name] = new_module
  211. if len(list(module.children())) > 0:
  212. replace_batch_norm(module)
  213. class DetrConvEncoder(nn.Module):
  214. """
  215. Convolutional backbone, using either the AutoBackbone API or one from the timm library.
  216. nn.BatchNorm2d layers are replaced by DetrFrozenBatchNorm2d as defined above.
  217. """
  218. def __init__(self, config):
  219. super().__init__()
  220. self.config = config
  221. # For backwards compatibility we have to use the timm library directly instead of the AutoBackbone API
  222. if config.use_timm_backbone:
  223. # We default to values which were previously hard-coded. This enables configurability from the config
  224. # using backbone arguments, while keeping the default behavior the same.
  225. requires_backends(self, ["timm"])
  226. kwargs = getattr(config, "backbone_kwargs", {})
  227. kwargs = {} if kwargs is None else kwargs.copy()
  228. out_indices = kwargs.pop("out_indices", (1, 2, 3, 4))
  229. num_channels = kwargs.pop("in_chans", config.num_channels)
  230. if config.dilation:
  231. kwargs["output_stride"] = kwargs.get("output_stride", 16)
  232. backbone = create_model(
  233. config.backbone,
  234. pretrained=config.use_pretrained_backbone,
  235. features_only=True,
  236. out_indices=out_indices,
  237. in_chans=num_channels,
  238. **kwargs,
  239. )
  240. else:
  241. backbone = load_backbone(config)
  242. # replace batch norm by frozen batch norm
  243. with torch.no_grad():
  244. replace_batch_norm(backbone)
  245. self.model = backbone
  246. self.intermediate_channel_sizes = (
  247. self.model.feature_info.channels() if config.use_timm_backbone else self.model.channels
  248. )
  249. backbone_model_type = None
  250. if config.backbone is not None:
  251. backbone_model_type = config.backbone
  252. elif config.backbone_config is not None:
  253. backbone_model_type = config.backbone_config.model_type
  254. else:
  255. raise ValueError("Either `backbone` or `backbone_config` should be provided in the config")
  256. if "resnet" in backbone_model_type:
  257. for name, parameter in self.model.named_parameters():
  258. if config.use_timm_backbone:
  259. if "layer2" not in name and "layer3" not in name and "layer4" not in name:
  260. parameter.requires_grad_(False)
  261. else:
  262. if "stage.1" not in name and "stage.2" not in name and "stage.3" not in name:
  263. parameter.requires_grad_(False)
  264. def forward(self, pixel_values: torch.Tensor, pixel_mask: torch.Tensor):
  265. # send pixel_values through the model to get list of feature maps
  266. features = self.model(pixel_values) if self.config.use_timm_backbone else self.model(pixel_values).feature_maps
  267. out = []
  268. for feature_map in features:
  269. # downsample pixel_mask to match shape of corresponding feature_map
  270. mask = nn.functional.interpolate(pixel_mask[None].float(), size=feature_map.shape[-2:]).to(torch.bool)[0]
  271. out.append((feature_map, mask))
  272. return out
  273. class DetrConvModel(nn.Module):
  274. """
  275. This module adds 2D position embeddings to all intermediate feature maps of the convolutional encoder.
  276. """
  277. def __init__(self, conv_encoder, position_embedding):
  278. super().__init__()
  279. self.conv_encoder = conv_encoder
  280. self.position_embedding = position_embedding
  281. def forward(self, pixel_values, pixel_mask):
  282. # send pixel_values and pixel_mask through backbone to get list of (feature_map, pixel_mask) tuples
  283. out = self.conv_encoder(pixel_values, pixel_mask)
  284. pos = []
  285. for feature_map, mask in out:
  286. # position encoding
  287. pos.append(self.position_embedding(feature_map, mask).to(feature_map.dtype))
  288. return out, pos
  289. class DetrSinePositionEmbedding(nn.Module):
  290. """
  291. This is a more standard version of the position embedding, very similar to the one used by the Attention is all you
  292. need paper, generalized to work on images.
  293. """
  294. def __init__(self, embedding_dim=64, temperature=10000, normalize=False, scale=None):
  295. super().__init__()
  296. self.embedding_dim = embedding_dim
  297. self.temperature = temperature
  298. self.normalize = normalize
  299. if scale is not None and normalize is False:
  300. raise ValueError("normalize should be True if scale is passed")
  301. if scale is None:
  302. scale = 2 * math.pi
  303. self.scale = scale
  304. def forward(self, pixel_values, pixel_mask):
  305. if pixel_mask is None:
  306. raise ValueError("No pixel mask provided")
  307. y_embed = pixel_mask.cumsum(1, dtype=torch.float32)
  308. x_embed = pixel_mask.cumsum(2, dtype=torch.float32)
  309. if self.normalize:
  310. y_embed = y_embed / (y_embed[:, -1:, :] + 1e-6) * self.scale
  311. x_embed = x_embed / (x_embed[:, :, -1:] + 1e-6) * self.scale
  312. dim_t = torch.arange(self.embedding_dim, dtype=torch.int64, device=pixel_values.device).float()
  313. dim_t = self.temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / self.embedding_dim)
  314. pos_x = x_embed[:, :, :, None] / dim_t
  315. pos_y = y_embed[:, :, :, None] / dim_t
  316. pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
  317. pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
  318. pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
  319. return pos
  320. class DetrLearnedPositionEmbedding(nn.Module):
  321. """
  322. This module learns positional embeddings up to a fixed maximum size.
  323. """
  324. def __init__(self, embedding_dim=256):
  325. super().__init__()
  326. self.row_embeddings = nn.Embedding(50, embedding_dim)
  327. self.column_embeddings = nn.Embedding(50, embedding_dim)
  328. def forward(self, pixel_values, pixel_mask=None):
  329. height, width = pixel_values.shape[-2:]
  330. width_values = torch.arange(width, device=pixel_values.device)
  331. height_values = torch.arange(height, device=pixel_values.device)
  332. x_emb = self.column_embeddings(width_values)
  333. y_emb = self.row_embeddings(height_values)
  334. pos = torch.cat([x_emb.unsqueeze(0).repeat(height, 1, 1), y_emb.unsqueeze(1).repeat(1, width, 1)], dim=-1)
  335. pos = pos.permute(2, 0, 1)
  336. pos = pos.unsqueeze(0)
  337. pos = pos.repeat(pixel_values.shape[0], 1, 1, 1)
  338. return pos
  339. def build_position_encoding(config):
  340. n_steps = config.d_model // 2
  341. if config.position_embedding_type == "sine":
  342. # TODO find a better way of exposing other arguments
  343. position_embedding = DetrSinePositionEmbedding(n_steps, normalize=True)
  344. elif config.position_embedding_type == "learned":
  345. position_embedding = DetrLearnedPositionEmbedding(n_steps)
  346. else:
  347. raise ValueError(f"Not supported {config.position_embedding_type}")
  348. return position_embedding
  349. class DetrAttention(nn.Module):
  350. """
  351. Multi-headed attention from 'Attention Is All You Need' paper.
  352. Here, we add position embeddings to the queries and keys (as explained in the DETR paper).
  353. """
  354. def __init__(
  355. self,
  356. embed_dim: int,
  357. num_heads: int,
  358. dropout: float = 0.0,
  359. bias: bool = True,
  360. ):
  361. super().__init__()
  362. self.embed_dim = embed_dim
  363. self.num_heads = num_heads
  364. self.dropout = dropout
  365. self.head_dim = embed_dim // num_heads
  366. if self.head_dim * num_heads != self.embed_dim:
  367. raise ValueError(
  368. f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
  369. f" {num_heads})."
  370. )
  371. self.scaling = self.head_dim**-0.5
  372. self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
  373. self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
  374. self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
  375. self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
  376. def _shape(self, tensor: torch.Tensor, seq_len: int, batch_size: int):
  377. return tensor.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
  378. def with_pos_embed(self, tensor: torch.Tensor, object_queries: Optional[Tensor]):
  379. return tensor if object_queries is None else tensor + object_queries
  380. def forward(
  381. self,
  382. hidden_states: torch.Tensor,
  383. attention_mask: Optional[torch.Tensor] = None,
  384. object_queries: Optional[torch.Tensor] = None,
  385. key_value_states: Optional[torch.Tensor] = None,
  386. spatial_position_embeddings: Optional[torch.Tensor] = None,
  387. output_attentions: bool = False,
  388. ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
  389. """Input shape: Batch x Time x Channel"""
  390. # if key_value_states are provided this layer is used as a cross-attention layer
  391. # for the decoder
  392. is_cross_attention = key_value_states is not None
  393. batch_size, target_len, embed_dim = hidden_states.size()
  394. # add position embeddings to the hidden states before projecting to queries and keys
  395. if object_queries is not None:
  396. hidden_states_original = hidden_states
  397. hidden_states = self.with_pos_embed(hidden_states, object_queries)
  398. # add key-value position embeddings to the key value states
  399. if spatial_position_embeddings is not None:
  400. key_value_states_original = key_value_states
  401. key_value_states = self.with_pos_embed(key_value_states, spatial_position_embeddings)
  402. # get query proj
  403. query_states = self.q_proj(hidden_states) * self.scaling
  404. # get key, value proj
  405. if is_cross_attention:
  406. # cross_attentions
  407. key_states = self._shape(self.k_proj(key_value_states), -1, batch_size)
  408. value_states = self._shape(self.v_proj(key_value_states_original), -1, batch_size)
  409. else:
  410. # self_attention
  411. key_states = self._shape(self.k_proj(hidden_states), -1, batch_size)
  412. value_states = self._shape(self.v_proj(hidden_states_original), -1, batch_size)
  413. proj_shape = (batch_size * self.num_heads, -1, self.head_dim)
  414. query_states = self._shape(query_states, target_len, batch_size).view(*proj_shape)
  415. key_states = key_states.view(*proj_shape)
  416. value_states = value_states.view(*proj_shape)
  417. source_len = key_states.size(1)
  418. attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
  419. if attn_weights.size() != (batch_size * self.num_heads, target_len, source_len):
  420. raise ValueError(
  421. f"Attention weights should be of size {(batch_size * self.num_heads, target_len, source_len)}, but is"
  422. f" {attn_weights.size()}"
  423. )
  424. if attention_mask is not None:
  425. if attention_mask.size() != (batch_size, 1, target_len, source_len):
  426. raise ValueError(
  427. f"Attention mask should be of size {(batch_size, 1, target_len, source_len)}, but is"
  428. f" {attention_mask.size()}"
  429. )
  430. if attention_mask.dtype == torch.bool:
  431. attention_mask = torch.zeros_like(attention_mask, dtype=attn_weights.dtype).masked_fill_(
  432. attention_mask, -torch.inf
  433. )
  434. attn_weights = attn_weights.view(batch_size, self.num_heads, target_len, source_len) + attention_mask
  435. attn_weights = attn_weights.view(batch_size * self.num_heads, target_len, source_len)
  436. attn_weights = nn.functional.softmax(attn_weights, dim=-1)
  437. if output_attentions:
  438. # this operation is a bit awkward, but it's required to
  439. # make sure that attn_weights keeps its gradient.
  440. # In order to do so, attn_weights have to reshaped
  441. # twice and have to be reused in the following
  442. attn_weights_reshaped = attn_weights.view(batch_size, self.num_heads, target_len, source_len)
  443. attn_weights = attn_weights_reshaped.view(batch_size * self.num_heads, target_len, source_len)
  444. else:
  445. attn_weights_reshaped = None
  446. attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
  447. attn_output = torch.bmm(attn_probs, value_states)
  448. if attn_output.size() != (batch_size * self.num_heads, target_len, self.head_dim):
  449. raise ValueError(
  450. f"`attn_output` should be of size {(batch_size, self.num_heads, target_len, self.head_dim)}, but is"
  451. f" {attn_output.size()}"
  452. )
  453. attn_output = attn_output.view(batch_size, self.num_heads, target_len, self.head_dim)
  454. attn_output = attn_output.transpose(1, 2)
  455. attn_output = attn_output.reshape(batch_size, target_len, embed_dim)
  456. attn_output = self.out_proj(attn_output)
  457. return attn_output, attn_weights_reshaped
  458. class DetrEncoderLayer(nn.Module):
  459. def __init__(self, config: DetrConfig):
  460. super().__init__()
  461. self.embed_dim = config.d_model
  462. self.self_attn = DetrAttention(
  463. embed_dim=self.embed_dim,
  464. num_heads=config.encoder_attention_heads,
  465. dropout=config.attention_dropout,
  466. )
  467. self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
  468. self.dropout = config.dropout
  469. self.activation_fn = ACT2FN[config.activation_function]
  470. self.activation_dropout = config.activation_dropout
  471. self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
  472. self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
  473. self.final_layer_norm = nn.LayerNorm(self.embed_dim)
  474. def forward(
  475. self,
  476. hidden_states: torch.Tensor,
  477. attention_mask: torch.Tensor,
  478. object_queries: Optional[torch.Tensor] = None,
  479. output_attentions: bool = False,
  480. ):
  481. """
  482. Args:
  483. hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
  484. attention_mask (`torch.FloatTensor`): attention mask of size
  485. `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
  486. values.
  487. object_queries (`torch.FloatTensor`, *optional*):
  488. Object queries (also called content embeddings), to be added to the hidden states.
  489. output_attentions (`bool`, *optional*):
  490. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  491. returned tensors for more detail.
  492. """
  493. residual = hidden_states
  494. hidden_states, attn_weights = self.self_attn(
  495. hidden_states=hidden_states,
  496. attention_mask=attention_mask,
  497. object_queries=object_queries,
  498. output_attentions=output_attentions,
  499. )
  500. hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
  501. hidden_states = residual + hidden_states
  502. hidden_states = self.self_attn_layer_norm(hidden_states)
  503. residual = hidden_states
  504. hidden_states = self.activation_fn(self.fc1(hidden_states))
  505. hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
  506. hidden_states = self.fc2(hidden_states)
  507. hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
  508. hidden_states = residual + hidden_states
  509. hidden_states = self.final_layer_norm(hidden_states)
  510. if self.training:
  511. if torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any():
  512. clamp_value = torch.finfo(hidden_states.dtype).max - 1000
  513. hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
  514. outputs = (hidden_states,)
  515. if output_attentions:
  516. outputs += (attn_weights,)
  517. return outputs
  518. class DetrDecoderLayer(GradientCheckpointingLayer):
  519. def __init__(self, config: DetrConfig):
  520. super().__init__()
  521. self.embed_dim = config.d_model
  522. self.self_attn = DetrAttention(
  523. embed_dim=self.embed_dim,
  524. num_heads=config.decoder_attention_heads,
  525. dropout=config.attention_dropout,
  526. )
  527. self.dropout = config.dropout
  528. self.activation_fn = ACT2FN[config.activation_function]
  529. self.activation_dropout = config.activation_dropout
  530. self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
  531. self.encoder_attn = DetrAttention(
  532. self.embed_dim,
  533. config.decoder_attention_heads,
  534. dropout=config.attention_dropout,
  535. )
  536. self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
  537. self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
  538. self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
  539. self.final_layer_norm = nn.LayerNorm(self.embed_dim)
  540. def forward(
  541. self,
  542. hidden_states: torch.Tensor,
  543. attention_mask: Optional[torch.Tensor] = None,
  544. object_queries: Optional[torch.Tensor] = None,
  545. query_position_embeddings: Optional[torch.Tensor] = None,
  546. encoder_hidden_states: Optional[torch.Tensor] = None,
  547. encoder_attention_mask: Optional[torch.Tensor] = None,
  548. output_attentions: Optional[bool] = False,
  549. ):
  550. """
  551. Args:
  552. hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
  553. attention_mask (`torch.FloatTensor`): attention mask of size
  554. `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
  555. values.
  556. object_queries (`torch.FloatTensor`, *optional*):
  557. object_queries that are added to the hidden states
  558. in the cross-attention layer.
  559. query_position_embeddings (`torch.FloatTensor`, *optional*):
  560. position embeddings that are added to the queries and keys
  561. in the self-attention layer.
  562. encoder_hidden_states (`torch.FloatTensor`):
  563. cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
  564. encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
  565. `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
  566. values.
  567. output_attentions (`bool`, *optional*):
  568. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  569. returned tensors for more detail.
  570. """
  571. residual = hidden_states
  572. # Self Attention
  573. hidden_states, self_attn_weights = self.self_attn(
  574. hidden_states=hidden_states,
  575. object_queries=query_position_embeddings,
  576. attention_mask=attention_mask,
  577. output_attentions=output_attentions,
  578. )
  579. hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
  580. hidden_states = residual + hidden_states
  581. hidden_states = self.self_attn_layer_norm(hidden_states)
  582. # Cross-Attention Block
  583. cross_attn_weights = None
  584. if encoder_hidden_states is not None:
  585. residual = hidden_states
  586. hidden_states, cross_attn_weights = self.encoder_attn(
  587. hidden_states=hidden_states,
  588. object_queries=query_position_embeddings,
  589. key_value_states=encoder_hidden_states,
  590. attention_mask=encoder_attention_mask,
  591. spatial_position_embeddings=object_queries,
  592. output_attentions=output_attentions,
  593. )
  594. hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
  595. hidden_states = residual + hidden_states
  596. hidden_states = self.encoder_attn_layer_norm(hidden_states)
  597. # Fully Connected
  598. residual = hidden_states
  599. hidden_states = self.activation_fn(self.fc1(hidden_states))
  600. hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
  601. hidden_states = self.fc2(hidden_states)
  602. hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
  603. hidden_states = residual + hidden_states
  604. hidden_states = self.final_layer_norm(hidden_states)
  605. outputs = (hidden_states,)
  606. if output_attentions:
  607. outputs += (self_attn_weights, cross_attn_weights)
  608. return outputs
  609. @auto_docstring
  610. class DetrPreTrainedModel(PreTrainedModel):
  611. config: DetrConfig
  612. base_model_prefix = "model"
  613. main_input_name = "pixel_values"
  614. _no_split_modules = [r"DetrConvEncoder", r"DetrEncoderLayer", r"DetrDecoderLayer"]
  615. def _init_weights(self, module):
  616. std = self.config.init_std
  617. xavier_std = self.config.init_xavier_std
  618. if isinstance(module, DetrMHAttentionMap):
  619. nn.init.zeros_(module.k_linear.bias)
  620. nn.init.zeros_(module.q_linear.bias)
  621. nn.init.xavier_uniform_(module.k_linear.weight, gain=xavier_std)
  622. nn.init.xavier_uniform_(module.q_linear.weight, gain=xavier_std)
  623. elif isinstance(module, DetrLearnedPositionEmbedding):
  624. nn.init.uniform_(module.row_embeddings.weight)
  625. nn.init.uniform_(module.column_embeddings.weight)
  626. if isinstance(module, (nn.Linear, nn.Conv2d, nn.BatchNorm2d)):
  627. # Slightly different from the TF version which uses truncated_normal for initialization
  628. # cf https://github.com/pytorch/pytorch/pull/5617
  629. module.weight.data.normal_(mean=0.0, std=std)
  630. if module.bias is not None:
  631. module.bias.data.zero_()
  632. elif isinstance(module, nn.Embedding):
  633. module.weight.data.normal_(mean=0.0, std=std)
  634. if module.padding_idx is not None:
  635. module.weight.data[module.padding_idx].zero_()
  636. class DetrEncoder(DetrPreTrainedModel):
  637. """
  638. Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
  639. [`DetrEncoderLayer`].
  640. The encoder updates the flattened feature map through multiple self-attention layers.
  641. Small tweak for DETR:
  642. - object_queries are added to the forward pass.
  643. Args:
  644. config: DetrConfig
  645. """
  646. def __init__(self, config: DetrConfig):
  647. super().__init__(config)
  648. self.dropout = config.dropout
  649. self.layerdrop = config.encoder_layerdrop
  650. self.layers = nn.ModuleList([DetrEncoderLayer(config) for _ in range(config.encoder_layers)])
  651. # in the original DETR, no layernorm is used at the end of the encoder, as "normalize_before" is set to False by default
  652. # Initialize weights and apply final processing
  653. self.post_init()
  654. def forward(
  655. self,
  656. inputs_embeds=None,
  657. attention_mask=None,
  658. object_queries=None,
  659. output_attentions=None,
  660. output_hidden_states=None,
  661. return_dict=None,
  662. ):
  663. r"""
  664. Args:
  665. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
  666. Flattened feature map (output of the backbone + projection layer) that is passed to the encoder.
  667. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
  668. Mask to avoid performing attention on padding pixel features. Mask values selected in `[0, 1]`:
  669. - 1 for pixel features that are real (i.e. **not masked**),
  670. - 0 for pixel features that are padding (i.e. **masked**).
  671. [What are attention masks?](../glossary#attention-mask)
  672. object_queries (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
  673. Object queries that are added to the queries in each self-attention layer.
  674. output_attentions (`bool`, *optional*):
  675. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  676. returned tensors for more detail.
  677. output_hidden_states (`bool`, *optional*):
  678. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
  679. for more detail.
  680. return_dict (`bool`, *optional*):
  681. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  682. """
  683. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  684. output_hidden_states = (
  685. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  686. )
  687. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  688. hidden_states = inputs_embeds
  689. hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
  690. # expand attention_mask
  691. if attention_mask is not None:
  692. # [batch_size, seq_len] -> [batch_size, 1, target_seq_len, source_seq_len]
  693. attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
  694. encoder_states = () if output_hidden_states else None
  695. all_attentions = () if output_attentions else None
  696. for i, encoder_layer in enumerate(self.layers):
  697. if output_hidden_states:
  698. encoder_states = encoder_states + (hidden_states,)
  699. # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
  700. to_drop = False
  701. if self.training:
  702. dropout_probability = torch.rand([])
  703. if dropout_probability < self.layerdrop: # skip the layer
  704. to_drop = True
  705. if to_drop:
  706. layer_outputs = (None, None)
  707. else:
  708. # we add object_queries as extra input to the encoder_layer
  709. layer_outputs = encoder_layer(
  710. hidden_states,
  711. attention_mask,
  712. object_queries=object_queries,
  713. output_attentions=output_attentions,
  714. )
  715. hidden_states = layer_outputs[0]
  716. if output_attentions:
  717. all_attentions = all_attentions + (layer_outputs[1],)
  718. if output_hidden_states:
  719. encoder_states = encoder_states + (hidden_states,)
  720. if not return_dict:
  721. return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
  722. return BaseModelOutput(
  723. last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
  724. )
  725. class DetrDecoder(DetrPreTrainedModel):
  726. """
  727. Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`DetrDecoderLayer`].
  728. The decoder updates the query embeddings through multiple self-attention and cross-attention layers.
  729. Some small tweaks for DETR:
  730. - object_queries and query_position_embeddings are added to the forward pass.
  731. - if self.config.auxiliary_loss is set to True, also returns a stack of activations from all decoding layers.
  732. Args:
  733. config: DetrConfig
  734. """
  735. def __init__(self, config: DetrConfig):
  736. super().__init__(config)
  737. self.dropout = config.dropout
  738. self.layerdrop = config.decoder_layerdrop
  739. self.layers = nn.ModuleList([DetrDecoderLayer(config) for _ in range(config.decoder_layers)])
  740. # in DETR, the decoder uses layernorm after the last decoder layer output
  741. self.layernorm = nn.LayerNorm(config.d_model)
  742. self.gradient_checkpointing = False
  743. # Initialize weights and apply final processing
  744. self.post_init()
  745. def forward(
  746. self,
  747. inputs_embeds=None,
  748. attention_mask=None,
  749. encoder_hidden_states=None,
  750. encoder_attention_mask=None,
  751. object_queries=None,
  752. query_position_embeddings=None,
  753. output_attentions=None,
  754. output_hidden_states=None,
  755. return_dict=None,
  756. ):
  757. r"""
  758. Args:
  759. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
  760. The query embeddings that are passed into the decoder.
  761. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
  762. Mask to avoid performing attention on certain queries. Mask values selected in `[0, 1]`:
  763. - 1 for queries that are **not masked**,
  764. - 0 for queries that are **masked**.
  765. [What are attention masks?](../glossary#attention-mask)
  766. encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
  767. Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
  768. of the decoder.
  769. encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
  770. Mask to avoid performing cross-attention on padding pixel_values of the encoder. Mask values selected
  771. in `[0, 1]`:
  772. - 1 for pixels that are real (i.e. **not masked**),
  773. - 0 for pixels that are padding (i.e. **masked**).
  774. object_queries (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  775. Object queries that are added to the queries and keys in each cross-attention layer.
  776. query_position_embeddings (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
  777. , *optional*): Position embeddings that are added to the values and keys in each self-attention layer.
  778. output_attentions (`bool`, *optional*):
  779. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  780. returned tensors for more detail.
  781. output_hidden_states (`bool`, *optional*):
  782. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
  783. for more detail.
  784. return_dict (`bool`, *optional*):
  785. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  786. """
  787. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  788. output_hidden_states = (
  789. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  790. )
  791. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  792. if inputs_embeds is not None:
  793. hidden_states = inputs_embeds
  794. input_shape = inputs_embeds.size()[:-1]
  795. combined_attention_mask = None
  796. if attention_mask is not None and combined_attention_mask is not None:
  797. # [batch_size, seq_len] -> [batch_size, 1, target_seq_len, source_seq_len]
  798. combined_attention_mask = combined_attention_mask + _prepare_4d_attention_mask(
  799. attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
  800. )
  801. # expand encoder attention mask
  802. if encoder_hidden_states is not None and encoder_attention_mask is not None:
  803. # [batch_size, seq_len] -> [batch_size, 1, target_seq_len, source_seq_len]
  804. encoder_attention_mask = _prepare_4d_attention_mask(
  805. encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
  806. )
  807. # optional intermediate hidden states
  808. intermediate = () if self.config.auxiliary_loss else None
  809. # decoder layers
  810. all_hidden_states = () if output_hidden_states else None
  811. all_self_attns = () if output_attentions else None
  812. all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
  813. for idx, decoder_layer in enumerate(self.layers):
  814. # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
  815. if output_hidden_states:
  816. all_hidden_states += (hidden_states,)
  817. if self.training:
  818. dropout_probability = torch.rand([])
  819. if dropout_probability < self.layerdrop:
  820. continue
  821. layer_outputs = decoder_layer(
  822. hidden_states,
  823. combined_attention_mask,
  824. object_queries,
  825. query_position_embeddings,
  826. encoder_hidden_states, # as a positional argument for gradient checkpointing
  827. encoder_attention_mask=encoder_attention_mask,
  828. output_attentions=output_attentions,
  829. )
  830. hidden_states = layer_outputs[0]
  831. if self.config.auxiliary_loss:
  832. hidden_states = self.layernorm(hidden_states)
  833. intermediate += (hidden_states,)
  834. if output_attentions:
  835. all_self_attns += (layer_outputs[1],)
  836. if encoder_hidden_states is not None:
  837. all_cross_attentions += (layer_outputs[2],)
  838. # finally, apply layernorm
  839. hidden_states = self.layernorm(hidden_states)
  840. # add hidden states from the last decoder layer
  841. if output_hidden_states:
  842. all_hidden_states += (hidden_states,)
  843. # stack intermediate decoder activations
  844. if self.config.auxiliary_loss:
  845. intermediate = torch.stack(intermediate)
  846. if not return_dict:
  847. return tuple(
  848. v
  849. for v in [hidden_states, all_hidden_states, all_self_attns, all_cross_attentions, intermediate]
  850. if v is not None
  851. )
  852. return DetrDecoderOutput(
  853. last_hidden_state=hidden_states,
  854. hidden_states=all_hidden_states,
  855. attentions=all_self_attns,
  856. cross_attentions=all_cross_attentions,
  857. intermediate_hidden_states=intermediate,
  858. )
  859. @auto_docstring(
  860. custom_intro="""
  861. The bare DETR Model (consisting of a backbone and encoder-decoder Transformer) outputting raw hidden-states without
  862. any specific head on top.
  863. """
  864. )
  865. class DetrModel(DetrPreTrainedModel):
  866. def __init__(self, config: DetrConfig):
  867. super().__init__(config)
  868. # Create backbone + positional encoding
  869. backbone = DetrConvEncoder(config)
  870. object_queries = build_position_encoding(config)
  871. self.backbone = DetrConvModel(backbone, object_queries)
  872. # Create projection layer
  873. self.input_projection = nn.Conv2d(backbone.intermediate_channel_sizes[-1], config.d_model, kernel_size=1)
  874. self.query_position_embeddings = nn.Embedding(config.num_queries, config.d_model)
  875. self.encoder = DetrEncoder(config)
  876. self.decoder = DetrDecoder(config)
  877. # Initialize weights and apply final processing
  878. self.post_init()
  879. def get_encoder(self):
  880. return self.encoder
  881. def freeze_backbone(self):
  882. for name, param in self.backbone.conv_encoder.model.named_parameters():
  883. param.requires_grad_(False)
  884. def unfreeze_backbone(self):
  885. for name, param in self.backbone.conv_encoder.model.named_parameters():
  886. param.requires_grad_(True)
  887. @auto_docstring
  888. def forward(
  889. self,
  890. pixel_values: torch.FloatTensor,
  891. pixel_mask: Optional[torch.LongTensor] = None,
  892. decoder_attention_mask: Optional[torch.FloatTensor] = None,
  893. encoder_outputs: Optional[torch.FloatTensor] = None,
  894. inputs_embeds: Optional[torch.FloatTensor] = None,
  895. decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
  896. output_attentions: Optional[bool] = None,
  897. output_hidden_states: Optional[bool] = None,
  898. return_dict: Optional[bool] = None,
  899. ) -> Union[tuple[torch.FloatTensor], DetrModelOutput]:
  900. r"""
  901. decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
  902. Not used by default. Can be used to mask object queries.
  903. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  904. Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
  905. can choose to directly pass a flattened representation of an image.
  906. decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
  907. Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
  908. embedded representation.
  909. Examples:
  910. ```python
  911. >>> from transformers import AutoImageProcessor, DetrModel
  912. >>> from PIL import Image
  913. >>> import requests
  914. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  915. >>> image = Image.open(requests.get(url, stream=True).raw)
  916. >>> image_processor = AutoImageProcessor.from_pretrained("facebook/detr-resnet-50")
  917. >>> model = DetrModel.from_pretrained("facebook/detr-resnet-50")
  918. >>> # prepare image for the model
  919. >>> inputs = image_processor(images=image, return_tensors="pt")
  920. >>> # forward pass
  921. >>> outputs = model(**inputs)
  922. >>> # the last hidden states are the final query embeddings of the Transformer decoder
  923. >>> # these are of shape (batch_size, num_queries, hidden_size)
  924. >>> last_hidden_states = outputs.last_hidden_state
  925. >>> list(last_hidden_states.shape)
  926. [1, 100, 256]
  927. ```"""
  928. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  929. output_hidden_states = (
  930. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  931. )
  932. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  933. batch_size, num_channels, height, width = pixel_values.shape
  934. device = pixel_values.device
  935. if pixel_mask is None:
  936. pixel_mask = torch.ones(((batch_size, height, width)), device=device)
  937. # First, sent pixel_values + pixel_mask through Backbone to obtain the features
  938. # pixel_values should be of shape (batch_size, num_channels, height, width)
  939. # pixel_mask should be of shape (batch_size, height, width)
  940. features, object_queries_list = self.backbone(pixel_values, pixel_mask)
  941. # get final feature map and downsampled mask
  942. feature_map, mask = features[-1]
  943. if mask is None:
  944. raise ValueError("Backbone does not return downsampled pixel mask")
  945. # Second, apply 1x1 convolution to reduce the channel dimension to d_model (256 by default)
  946. projected_feature_map = self.input_projection(feature_map)
  947. # Third, flatten the feature map + position embeddings of shape NxCxHxW to NxCxHW, and permute it to NxHWxC
  948. # In other words, turn their shape into (batch_size, sequence_length, hidden_size)
  949. flattened_features = projected_feature_map.flatten(2).permute(0, 2, 1)
  950. object_queries = object_queries_list[-1].flatten(2).permute(0, 2, 1)
  951. flattened_mask = mask.flatten(1)
  952. # Fourth, sent flattened_features + flattened_mask + position embeddings through encoder
  953. # flattened_features is a Tensor of shape (batch_size, height*width, hidden_size)
  954. # flattened_mask is a Tensor of shape (batch_size, height*width)
  955. if encoder_outputs is None:
  956. encoder_outputs = self.encoder(
  957. inputs_embeds=flattened_features,
  958. attention_mask=flattened_mask,
  959. object_queries=object_queries,
  960. output_attentions=output_attentions,
  961. output_hidden_states=output_hidden_states,
  962. return_dict=return_dict,
  963. )
  964. # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
  965. elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
  966. encoder_outputs = BaseModelOutput(
  967. last_hidden_state=encoder_outputs[0],
  968. hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
  969. attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
  970. )
  971. # Fifth, sent query embeddings + object_queries through the decoder (which is conditioned on the encoder output)
  972. query_position_embeddings = self.query_position_embeddings.weight.unsqueeze(0).repeat(batch_size, 1, 1)
  973. queries = torch.zeros_like(query_position_embeddings)
  974. # decoder outputs consists of (dec_features, dec_hidden, dec_attn)
  975. decoder_outputs = self.decoder(
  976. inputs_embeds=queries,
  977. attention_mask=None,
  978. object_queries=object_queries,
  979. query_position_embeddings=query_position_embeddings,
  980. encoder_hidden_states=encoder_outputs[0],
  981. encoder_attention_mask=flattened_mask,
  982. output_attentions=output_attentions,
  983. output_hidden_states=output_hidden_states,
  984. return_dict=return_dict,
  985. )
  986. if not return_dict:
  987. return decoder_outputs + encoder_outputs
  988. return DetrModelOutput(
  989. last_hidden_state=decoder_outputs.last_hidden_state,
  990. decoder_hidden_states=decoder_outputs.hidden_states,
  991. decoder_attentions=decoder_outputs.attentions,
  992. cross_attentions=decoder_outputs.cross_attentions,
  993. encoder_last_hidden_state=encoder_outputs.last_hidden_state,
  994. encoder_hidden_states=encoder_outputs.hidden_states,
  995. encoder_attentions=encoder_outputs.attentions,
  996. intermediate_hidden_states=decoder_outputs.intermediate_hidden_states,
  997. )
  998. # taken from https://github.com/facebookresearch/detr/blob/master/models/detr.py
  999. class DetrMLPPredictionHead(nn.Module):
  1000. """
  1001. Very simple multi-layer perceptron (MLP, also called FFN), used to predict the normalized center coordinates,
  1002. height and width of a bounding box w.r.t. an image.
  1003. Copied from https://github.com/facebookresearch/detr/blob/master/models/detr.py
  1004. """
  1005. def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
  1006. super().__init__()
  1007. self.num_layers = num_layers
  1008. h = [hidden_dim] * (num_layers - 1)
  1009. self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
  1010. def forward(self, x):
  1011. for i, layer in enumerate(self.layers):
  1012. x = nn.functional.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
  1013. return x
  1014. @auto_docstring(
  1015. custom_intro="""
  1016. DETR Model (consisting of a backbone and encoder-decoder Transformer) with object detection heads on top, for tasks
  1017. such as COCO detection.
  1018. """
  1019. )
  1020. class DetrForObjectDetection(DetrPreTrainedModel):
  1021. def __init__(self, config: DetrConfig):
  1022. super().__init__(config)
  1023. # DETR encoder-decoder model
  1024. self.model = DetrModel(config)
  1025. # Object detection heads
  1026. self.class_labels_classifier = nn.Linear(
  1027. config.d_model, config.num_labels + 1
  1028. ) # We add one for the "no object" class
  1029. self.bbox_predictor = DetrMLPPredictionHead(
  1030. input_dim=config.d_model, hidden_dim=config.d_model, output_dim=4, num_layers=3
  1031. )
  1032. # Initialize weights and apply final processing
  1033. self.post_init()
  1034. @auto_docstring
  1035. def forward(
  1036. self,
  1037. pixel_values: torch.FloatTensor,
  1038. pixel_mask: Optional[torch.LongTensor] = None,
  1039. decoder_attention_mask: Optional[torch.FloatTensor] = None,
  1040. encoder_outputs: Optional[torch.FloatTensor] = None,
  1041. inputs_embeds: Optional[torch.FloatTensor] = None,
  1042. decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
  1043. labels: Optional[list[dict]] = None,
  1044. output_attentions: Optional[bool] = None,
  1045. output_hidden_states: Optional[bool] = None,
  1046. return_dict: Optional[bool] = None,
  1047. ) -> Union[tuple[torch.FloatTensor], DetrObjectDetectionOutput]:
  1048. r"""
  1049. decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
  1050. Not used by default. Can be used to mask object queries.
  1051. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  1052. Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
  1053. can choose to directly pass a flattened representation of an image.
  1054. decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
  1055. Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
  1056. embedded representation.
  1057. labels (`list[Dict]` of len `(batch_size,)`, *optional*):
  1058. Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
  1059. following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch
  1060. respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes
  1061. in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.
  1062. Examples:
  1063. ```python
  1064. >>> from transformers import AutoImageProcessor, DetrForObjectDetection
  1065. >>> import torch
  1066. >>> from PIL import Image
  1067. >>> import requests
  1068. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  1069. >>> image = Image.open(requests.get(url, stream=True).raw)
  1070. >>> image_processor = AutoImageProcessor.from_pretrained("facebook/detr-resnet-50")
  1071. >>> model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
  1072. >>> inputs = image_processor(images=image, return_tensors="pt")
  1073. >>> outputs = model(**inputs)
  1074. >>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
  1075. >>> target_sizes = torch.tensor([image.size[::-1]])
  1076. >>> results = image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)[
  1077. ... 0
  1078. ... ]
  1079. >>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
  1080. ... box = [round(i, 2) for i in box.tolist()]
  1081. ... print(
  1082. ... f"Detected {model.config.id2label[label.item()]} with confidence "
  1083. ... f"{round(score.item(), 3)} at location {box}"
  1084. ... )
  1085. Detected remote with confidence 0.998 at location [40.16, 70.81, 175.55, 117.98]
  1086. Detected remote with confidence 0.996 at location [333.24, 72.55, 368.33, 187.66]
  1087. Detected couch with confidence 0.995 at location [-0.02, 1.15, 639.73, 473.76]
  1088. Detected cat with confidence 0.999 at location [13.24, 52.05, 314.02, 470.93]
  1089. Detected cat with confidence 0.999 at location [345.4, 23.85, 640.37, 368.72]
  1090. ```"""
  1091. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1092. # First, sent images through DETR base model to obtain encoder + decoder outputs
  1093. outputs = self.model(
  1094. pixel_values,
  1095. pixel_mask=pixel_mask,
  1096. decoder_attention_mask=decoder_attention_mask,
  1097. encoder_outputs=encoder_outputs,
  1098. inputs_embeds=inputs_embeds,
  1099. decoder_inputs_embeds=decoder_inputs_embeds,
  1100. output_attentions=output_attentions,
  1101. output_hidden_states=output_hidden_states,
  1102. return_dict=return_dict,
  1103. )
  1104. sequence_output = outputs[0]
  1105. # class logits + predicted bounding boxes
  1106. logits = self.class_labels_classifier(sequence_output)
  1107. pred_boxes = self.bbox_predictor(sequence_output).sigmoid()
  1108. loss, loss_dict, auxiliary_outputs = None, None, None
  1109. if labels is not None:
  1110. outputs_class, outputs_coord = None, None
  1111. if self.config.auxiliary_loss:
  1112. intermediate = outputs.intermediate_hidden_states if return_dict else outputs[4]
  1113. outputs_class = self.class_labels_classifier(intermediate)
  1114. outputs_coord = self.bbox_predictor(intermediate).sigmoid()
  1115. loss, loss_dict, auxiliary_outputs = self.loss_function(
  1116. logits, labels, self.device, pred_boxes, self.config, outputs_class, outputs_coord
  1117. )
  1118. if not return_dict:
  1119. if auxiliary_outputs is not None:
  1120. output = (logits, pred_boxes) + auxiliary_outputs + outputs
  1121. else:
  1122. output = (logits, pred_boxes) + outputs
  1123. return ((loss, loss_dict) + output) if loss is not None else output
  1124. return DetrObjectDetectionOutput(
  1125. loss=loss,
  1126. loss_dict=loss_dict,
  1127. logits=logits,
  1128. pred_boxes=pred_boxes,
  1129. auxiliary_outputs=auxiliary_outputs,
  1130. last_hidden_state=outputs.last_hidden_state,
  1131. decoder_hidden_states=outputs.decoder_hidden_states,
  1132. decoder_attentions=outputs.decoder_attentions,
  1133. cross_attentions=outputs.cross_attentions,
  1134. encoder_last_hidden_state=outputs.encoder_last_hidden_state,
  1135. encoder_hidden_states=outputs.encoder_hidden_states,
  1136. encoder_attentions=outputs.encoder_attentions,
  1137. )
  1138. @auto_docstring(
  1139. custom_intro="""
  1140. DETR Model (consisting of a backbone and encoder-decoder Transformer) with a segmentation head on top, for tasks
  1141. such as COCO panoptic.
  1142. """
  1143. )
  1144. class DetrForSegmentation(DetrPreTrainedModel):
  1145. def __init__(self, config: DetrConfig):
  1146. super().__init__(config)
  1147. # object detection model
  1148. self.detr = DetrForObjectDetection(config)
  1149. # segmentation head
  1150. hidden_size, number_of_heads = config.d_model, config.encoder_attention_heads
  1151. intermediate_channel_sizes = self.detr.model.backbone.conv_encoder.intermediate_channel_sizes
  1152. self.mask_head = DetrMaskHeadSmallConv(
  1153. hidden_size + number_of_heads, intermediate_channel_sizes[::-1][-3:], hidden_size
  1154. )
  1155. self.bbox_attention = DetrMHAttentionMap(
  1156. hidden_size, hidden_size, number_of_heads, dropout=0.0, std=config.init_xavier_std
  1157. )
  1158. # Initialize weights and apply final processing
  1159. self.post_init()
  1160. @auto_docstring
  1161. def forward(
  1162. self,
  1163. pixel_values: torch.FloatTensor,
  1164. pixel_mask: Optional[torch.LongTensor] = None,
  1165. decoder_attention_mask: Optional[torch.FloatTensor] = None,
  1166. encoder_outputs: Optional[torch.FloatTensor] = None,
  1167. inputs_embeds: Optional[torch.FloatTensor] = None,
  1168. decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
  1169. labels: Optional[list[dict]] = None,
  1170. output_attentions: Optional[bool] = None,
  1171. output_hidden_states: Optional[bool] = None,
  1172. return_dict: Optional[bool] = None,
  1173. ) -> Union[tuple[torch.FloatTensor], DetrSegmentationOutput]:
  1174. r"""
  1175. decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
  1176. Not used by default. Can be used to mask object queries.
  1177. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  1178. Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
  1179. can choose to directly pass a flattened representation of an image.
  1180. decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
  1181. Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
  1182. embedded representation.
  1183. labels (`list[Dict]` of len `(batch_size,)`, *optional*):
  1184. Labels for computing the bipartite matching loss, DICE/F-1 loss and Focal loss. List of dicts, each
  1185. dictionary containing at least the following 3 keys: 'class_labels', 'boxes' and 'masks' (the class labels,
  1186. bounding boxes and segmentation masks of an image in the batch respectively). The class labels themselves
  1187. should be a `torch.LongTensor` of len `(number of bounding boxes in the image,)`, the boxes a
  1188. `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)` and the masks a
  1189. `torch.FloatTensor` of shape `(number of bounding boxes in the image, height, width)`.
  1190. Examples:
  1191. ```python
  1192. >>> import io
  1193. >>> import requests
  1194. >>> from PIL import Image
  1195. >>> import torch
  1196. >>> import numpy
  1197. >>> from transformers import AutoImageProcessor, DetrForSegmentation
  1198. >>> from transformers.image_transforms import rgb_to_id
  1199. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  1200. >>> image = Image.open(requests.get(url, stream=True).raw)
  1201. >>> image_processor = AutoImageProcessor.from_pretrained("facebook/detr-resnet-50-panoptic")
  1202. >>> model = DetrForSegmentation.from_pretrained("facebook/detr-resnet-50-panoptic")
  1203. >>> # prepare image for the model
  1204. >>> inputs = image_processor(images=image, return_tensors="pt")
  1205. >>> # forward pass
  1206. >>> outputs = model(**inputs)
  1207. >>> # Use the `post_process_panoptic_segmentation` method of the `image_processor` to retrieve post-processed panoptic segmentation maps
  1208. >>> # Segmentation results are returned as a list of dictionaries
  1209. >>> result = image_processor.post_process_panoptic_segmentation(outputs, target_sizes=[(300, 500)])
  1210. >>> # A tensor of shape (height, width) where each value denotes a segment id, filled with -1 if no segment is found
  1211. >>> panoptic_seg = result[0]["segmentation"]
  1212. >>> # Get prediction score and segment_id to class_id mapping of each segment
  1213. >>> panoptic_segments_info = result[0]["segments_info"]
  1214. ```"""
  1215. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1216. batch_size, num_channels, height, width = pixel_values.shape
  1217. device = pixel_values.device
  1218. if pixel_mask is None:
  1219. pixel_mask = torch.ones((batch_size, height, width), device=device)
  1220. # First, get list of feature maps and position embeddings
  1221. features, object_queries_list = self.detr.model.backbone(pixel_values, pixel_mask=pixel_mask)
  1222. # Second, apply 1x1 convolution to reduce the channel dimension to d_model (256 by default)
  1223. feature_map, mask = features[-1]
  1224. batch_size, num_channels, height, width = feature_map.shape
  1225. projected_feature_map = self.detr.model.input_projection(feature_map)
  1226. # Third, flatten the feature map + position embeddings of shape NxCxHxW to NxCxHW, and permute it to NxHWxC
  1227. # In other words, turn their shape into (batch_size, sequence_length, hidden_size)
  1228. flattened_features = projected_feature_map.flatten(2).permute(0, 2, 1)
  1229. object_queries = object_queries_list[-1].flatten(2).permute(0, 2, 1)
  1230. flattened_mask = mask.flatten(1)
  1231. # Fourth, sent flattened_features + flattened_mask + position embeddings through encoder
  1232. # flattened_features is a Tensor of shape (batch_size, height*width, hidden_size)
  1233. # flattened_mask is a Tensor of shape (batch_size, height*width)
  1234. if encoder_outputs is None:
  1235. encoder_outputs = self.detr.model.encoder(
  1236. inputs_embeds=flattened_features,
  1237. attention_mask=flattened_mask,
  1238. object_queries=object_queries,
  1239. output_attentions=output_attentions,
  1240. output_hidden_states=output_hidden_states,
  1241. return_dict=return_dict,
  1242. )
  1243. # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
  1244. elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
  1245. encoder_outputs = BaseModelOutput(
  1246. last_hidden_state=encoder_outputs[0],
  1247. hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
  1248. attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
  1249. )
  1250. # Fifth, sent query embeddings + position embeddings through the decoder (which is conditioned on the encoder output)
  1251. query_position_embeddings = self.detr.model.query_position_embeddings.weight.unsqueeze(0).repeat(
  1252. batch_size, 1, 1
  1253. )
  1254. queries = torch.zeros_like(query_position_embeddings)
  1255. # decoder outputs consists of (dec_features, dec_hidden, dec_attn)
  1256. decoder_outputs = self.detr.model.decoder(
  1257. inputs_embeds=queries,
  1258. attention_mask=None,
  1259. object_queries=object_queries,
  1260. query_position_embeddings=query_position_embeddings,
  1261. encoder_hidden_states=encoder_outputs[0],
  1262. encoder_attention_mask=flattened_mask,
  1263. output_attentions=output_attentions,
  1264. output_hidden_states=output_hidden_states,
  1265. return_dict=return_dict,
  1266. )
  1267. sequence_output = decoder_outputs[0]
  1268. # Sixth, compute logits, pred_boxes and pred_masks
  1269. logits = self.detr.class_labels_classifier(sequence_output)
  1270. pred_boxes = self.detr.bbox_predictor(sequence_output).sigmoid()
  1271. memory = encoder_outputs[0].permute(0, 2, 1).view(batch_size, self.config.d_model, height, width)
  1272. mask = flattened_mask.view(batch_size, height, width)
  1273. # FIXME h_boxes takes the last one computed, keep this in mind
  1274. # important: we need to reverse the mask, since in the original implementation the mask works reversed
  1275. # bbox_mask is of shape (batch_size, num_queries, number_of_attention_heads in bbox_attention, height/32, width/32)
  1276. bbox_mask = self.bbox_attention(sequence_output, memory, mask=~mask)
  1277. seg_masks = self.mask_head(projected_feature_map, bbox_mask, [features[2][0], features[1][0], features[0][0]])
  1278. pred_masks = seg_masks.view(batch_size, self.detr.config.num_queries, seg_masks.shape[-2], seg_masks.shape[-1])
  1279. loss, loss_dict, auxiliary_outputs = None, None, None
  1280. if labels is not None:
  1281. outputs_class, outputs_coord = None, None
  1282. if self.config.auxiliary_loss:
  1283. intermediate = decoder_outputs.intermediate_hidden_states if return_dict else decoder_outputs[-1]
  1284. outputs_class = self.detr.class_labels_classifier(intermediate)
  1285. outputs_coord = self.detr.bbox_predictor(intermediate).sigmoid()
  1286. loss, loss_dict, auxiliary_outputs = self.loss_function(
  1287. logits, labels, device, pred_boxes, pred_masks, self.config, outputs_class, outputs_coord
  1288. )
  1289. if not return_dict:
  1290. if auxiliary_outputs is not None:
  1291. output = (logits, pred_boxes, pred_masks) + auxiliary_outputs + decoder_outputs + encoder_outputs
  1292. else:
  1293. output = (logits, pred_boxes, pred_masks) + decoder_outputs + encoder_outputs
  1294. return ((loss, loss_dict) + output) if loss is not None else output
  1295. return DetrSegmentationOutput(
  1296. loss=loss,
  1297. loss_dict=loss_dict,
  1298. logits=logits,
  1299. pred_boxes=pred_boxes,
  1300. pred_masks=pred_masks,
  1301. auxiliary_outputs=auxiliary_outputs,
  1302. last_hidden_state=decoder_outputs.last_hidden_state,
  1303. decoder_hidden_states=decoder_outputs.hidden_states,
  1304. decoder_attentions=decoder_outputs.attentions,
  1305. cross_attentions=decoder_outputs.cross_attentions,
  1306. encoder_last_hidden_state=encoder_outputs.last_hidden_state,
  1307. encoder_hidden_states=encoder_outputs.hidden_states,
  1308. encoder_attentions=encoder_outputs.attentions,
  1309. )
  1310. def _expand(tensor, length: int):
  1311. return tensor.unsqueeze(1).repeat(1, int(length), 1, 1, 1).flatten(0, 1)
  1312. # taken from https://github.com/facebookresearch/detr/blob/master/models/segmentation.py
  1313. class DetrMaskHeadSmallConv(nn.Module):
  1314. """
  1315. Simple convolutional head, using group norm. Upsampling is done using a FPN approach
  1316. """
  1317. def __init__(self, dim, fpn_dims, context_dim):
  1318. super().__init__()
  1319. if dim % 8 != 0:
  1320. raise ValueError(
  1321. "The hidden_size + number of attention heads must be divisible by 8 as the number of groups in"
  1322. " GroupNorm is set to 8"
  1323. )
  1324. inter_dims = [dim, context_dim // 2, context_dim // 4, context_dim // 8, context_dim // 16, context_dim // 64]
  1325. self.lay1 = nn.Conv2d(dim, dim, 3, padding=1)
  1326. self.gn1 = nn.GroupNorm(8, dim)
  1327. self.lay2 = nn.Conv2d(dim, inter_dims[1], 3, padding=1)
  1328. self.gn2 = nn.GroupNorm(min(8, inter_dims[1]), inter_dims[1])
  1329. self.lay3 = nn.Conv2d(inter_dims[1], inter_dims[2], 3, padding=1)
  1330. self.gn3 = nn.GroupNorm(min(8, inter_dims[2]), inter_dims[2])
  1331. self.lay4 = nn.Conv2d(inter_dims[2], inter_dims[3], 3, padding=1)
  1332. self.gn4 = nn.GroupNorm(min(8, inter_dims[3]), inter_dims[3])
  1333. self.lay5 = nn.Conv2d(inter_dims[3], inter_dims[4], 3, padding=1)
  1334. self.gn5 = nn.GroupNorm(min(8, inter_dims[4]), inter_dims[4])
  1335. self.out_lay = nn.Conv2d(inter_dims[4], 1, 3, padding=1)
  1336. self.dim = dim
  1337. self.adapter1 = nn.Conv2d(fpn_dims[0], inter_dims[1], 1)
  1338. self.adapter2 = nn.Conv2d(fpn_dims[1], inter_dims[2], 1)
  1339. self.adapter3 = nn.Conv2d(fpn_dims[2], inter_dims[3], 1)
  1340. for m in self.modules():
  1341. if isinstance(m, nn.Conv2d):
  1342. nn.init.kaiming_uniform_(m.weight, a=1)
  1343. nn.init.constant_(m.bias, 0)
  1344. def forward(self, x: Tensor, bbox_mask: Tensor, fpns: list[Tensor]):
  1345. # here we concatenate x, the projected feature map, of shape (batch_size, d_model, height/32, width/32) with
  1346. # the bbox_mask = the attention maps of shape (batch_size, n_queries, n_heads, height/32, width/32).
  1347. # We expand the projected feature map to match the number of heads.
  1348. x = torch.cat([_expand(x, bbox_mask.shape[1]), bbox_mask.flatten(0, 1)], 1)
  1349. x = self.lay1(x)
  1350. x = self.gn1(x)
  1351. x = nn.functional.relu(x)
  1352. x = self.lay2(x)
  1353. x = self.gn2(x)
  1354. x = nn.functional.relu(x)
  1355. cur_fpn = self.adapter1(fpns[0])
  1356. if cur_fpn.size(0) != x.size(0):
  1357. cur_fpn = _expand(cur_fpn, x.size(0) // cur_fpn.size(0))
  1358. x = cur_fpn + nn.functional.interpolate(x, size=cur_fpn.shape[-2:], mode="nearest")
  1359. x = self.lay3(x)
  1360. x = self.gn3(x)
  1361. x = nn.functional.relu(x)
  1362. cur_fpn = self.adapter2(fpns[1])
  1363. if cur_fpn.size(0) != x.size(0):
  1364. cur_fpn = _expand(cur_fpn, x.size(0) // cur_fpn.size(0))
  1365. x = cur_fpn + nn.functional.interpolate(x, size=cur_fpn.shape[-2:], mode="nearest")
  1366. x = self.lay4(x)
  1367. x = self.gn4(x)
  1368. x = nn.functional.relu(x)
  1369. cur_fpn = self.adapter3(fpns[2])
  1370. if cur_fpn.size(0) != x.size(0):
  1371. cur_fpn = _expand(cur_fpn, x.size(0) // cur_fpn.size(0))
  1372. x = cur_fpn + nn.functional.interpolate(x, size=cur_fpn.shape[-2:], mode="nearest")
  1373. x = self.lay5(x)
  1374. x = self.gn5(x)
  1375. x = nn.functional.relu(x)
  1376. x = self.out_lay(x)
  1377. return x
  1378. class DetrMHAttentionMap(nn.Module):
  1379. """This is a 2D attention module, which only returns the attention softmax (no multiplication by value)"""
  1380. def __init__(self, query_dim, hidden_dim, num_heads, dropout=0.0, bias=True, std=None):
  1381. super().__init__()
  1382. self.num_heads = num_heads
  1383. self.hidden_dim = hidden_dim
  1384. self.dropout = nn.Dropout(dropout)
  1385. self.q_linear = nn.Linear(query_dim, hidden_dim, bias=bias)
  1386. self.k_linear = nn.Linear(query_dim, hidden_dim, bias=bias)
  1387. self.normalize_fact = float(hidden_dim / self.num_heads) ** -0.5
  1388. def forward(self, q, k, mask: Optional[Tensor] = None):
  1389. q = self.q_linear(q)
  1390. k = nn.functional.conv2d(k, self.k_linear.weight.unsqueeze(-1).unsqueeze(-1), self.k_linear.bias)
  1391. queries_per_head = q.view(q.shape[0], q.shape[1], self.num_heads, self.hidden_dim // self.num_heads)
  1392. keys_per_head = k.view(k.shape[0], self.num_heads, self.hidden_dim // self.num_heads, k.shape[-2], k.shape[-1])
  1393. weights = torch.einsum("bqnc,bnchw->bqnhw", queries_per_head * self.normalize_fact, keys_per_head)
  1394. if mask is not None:
  1395. weights = weights.masked_fill(mask.unsqueeze(1).unsqueeze(1), torch.finfo(weights.dtype).min)
  1396. weights = nn.functional.softmax(weights.flatten(2), dim=-1).view(weights.size())
  1397. weights = self.dropout(weights)
  1398. return weights
  1399. __all__ = [
  1400. "DetrForObjectDetection",
  1401. "DetrForSegmentation",
  1402. "DetrModel",
  1403. "DetrPreTrainedModel",
  1404. ]