Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add RT-DETR and ObjectDetection API (#2363)

Thien Tran64a9e351ced7
diff --git a/docs/source/contrib.rst b/docs/source/contrib.rst
index 12ed712ff..45a96d45d 100644
--- a/docs/source/contrib.rst
+++ b/docs/source/contrib.rst
@@ -14,6 +14,7 @@ Base
Structures
^^^^^^^^^^
+
.. _anchor SegmentationResults:
.. autoclass:: kornia.contrib.models.SegmentationResults
:members:
@@ -56,11 +57,39 @@ Interactive Demo
Visit the `Kornia face detection demo on the Hugging Face Spaces
<https://huggingface.co/spaces/kornia/Face-Detection>`_.
+Object Detection
+----------------
+
+.. autoclass:: ObjectDetector
+ :members:
+ :undoc-members:
+ :special-members: __init__,
+
+Real-Time Detection Transformer (RT-DETR)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autoclass:: kornia.contrib.models.rt_detr.RTDETRModelType
+ :members:
+ :undoc-members:
+ :member-order: bysource
+
+.. autoclass:: kornia.contrib.models.rt_detr.RTDETRConfig
+ :members:
+ :undoc-members:
+
+.. autoclass:: kornia.contrib.models.rt_detr.RTDETR
+ :members: from_config, forward, load_checkpoint
+ :undoc-members:
+ :special-members: __init__,
+
+.. autoclass:: kornia.contrib.models.rt_detr.DETRPostProcessor
+ :members:
+ :undoc-members:
+
Image Segmentation
------------------
.. autofunction:: connected_components
-
Segment Anything (SAM)
^^^^^^^^^^^^^^^^^^^^^^
diff --git a/docs/source/index.rst b/docs/source/index.rst
index 276cfb74b..ed9703903 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -91,6 +91,7 @@ Join the community
:caption: KORNIA MODELS
:hidden:
+ models/rt_detr
models/segment_anything
models/yunet
models/vit
diff --git a/docs/source/models/rt_detr.rst b/docs/source/models/rt_detr.rst
new file mode 100644
index 000000000..cfeaa06c8
--- /dev/null
+++ b/docs/source/models/rt_detr.rst
@@ -0,0 +1,32 @@
+Real-Time Detection Transformer (RT-DETR)
+=========================================
+
+.. card::
+ :link: https://arxiv.org/abs/2304.08069
+
+ **RT-DETR**
+ ^^^
+ **Abstract:** Recently, end-to-end transformer-based detectors (DETRs) have achieved remarkable performance.
+ However, the issue of the high computational cost of DETRs has not been effectively addressed, limiting their
+ practical application and preventing them from fully exploiting the benefits of no post-processing, such as
+ non-maximum suppression (NMS). In this paper, we first analyze the influence of NMS in modern real-time object
+ detectors on inference speed, and establish an end-to-end speed benchmark. To avoid the inference delay caused
+ by NMS, we propose a Real-Time DEtection TRansformer (RT-DETR), the first real-time end-to-end object detector
+ to our best knowledge. Specifically, we design an efficient hybrid encoder to efficiently process multi-scale
+ features by decoupling the intra-scale interaction and cross-scale fusion, and propose IoU-aware query selection
+ to improve the initialization of object queries. In addition, our proposed detector supports flexibly adjustment
+ of the inference speed by using different decoder layers without the need for retraining, which facilitates the
+ practical application of real-time object detectors. Our RT-DETR-L achieves 53.0% AP on COCO val2017 and 114 FPS
+ on T4 GPU, while RT-DETR-X achieves 54.8% AP and 74 FPS, outperforming all YOLO detectors of the same scale in
+ both speed and accuracy. Furthermore, our RT-DETR-R50 achieves 53.1% AP and 108 FPS, outperforming
+ DINO-Deformable-DETR-R50 by 2.2% AP in accuracy and by about 21 times in FPS. Source code and pretrained models
+ will be available at PaddleDetection.
+
+ **Tasks:** Detection
+
+ **Datasets:** MS-COCO
+
+ **Licence:** Apache 2.0
+
+ +++
+ **Authors:** Wenyu Lv, Shangliang Xu, Yian Zhao, Guanzhong Wang, Jinman Wei, Cheng Cui, Yuning Du, Qingqing Dang, Yi Liu
diff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.py
index e742e77a9..69a62a9b9 100644
--- a/kornia/contrib/__init__.py
+++ b/kornia/contrib/__init__.py
@@ -14,6 +14,7 @@ from .face_detection import *
from .histogram_matching import histogram_matching, interp
from .image_stitching import ImageStitcher
from .lambda_module import Lambda
+from .object_detection import ObjectDetector
from .vit import VisionTransformer
from .vit_mobile import MobileViT
@@ -35,4 +36,5 @@ __all__ = [
"distance_transform",
"DistanceTransform",
"diamond_square",
+ "ObjectDetector",
]
diff --git a/kornia/contrib/models/common.py b/kornia/contrib/models/common.py
new file mode 100644
index 000000000..d5f201385
--- /dev/null
+++ b/kornia/contrib/models/common.py
@@ -0,0 +1,47 @@
+from __future__ import annotations
+
+import torch.nn.functional as F
+from torch import nn
+
+from kornia.core import Module, Tensor
+
+
+class ConvNormAct(nn.Sequential):
+ def __init__(
+ self, in_channels: int, out_channels: int, kernel_size: int, stride: int = 1, act: str = "relu", groups: int = 1
+ ) -> None:
+ super().__init__()
+ if kernel_size % 2 == 0:
+ # even kernel_size -> asymmetric padding
+ # PPHGNetV2 (for RT-DETR) uses kernel 2
+ # follow TensorFlow/PaddlePaddle: bottom/right side is padded 1 more than top/left
+ # NOTE: this does not account for stride=2
+ p1 = (kernel_size - 1) // 2
+ p2 = kernel_size - 1 - p1
+ self.pad = nn.ZeroPad2d((p1, p2, p1, p2))
+ padding = 0
+ else:
+ padding = (kernel_size - 1) // 2
+ self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, 1, groups, False)
+ self.norm = nn.BatchNorm2d(out_channels)
+ self.act = dict(relu=nn.ReLU, silu=nn.SiLU, none=nn.Identity)[act](inplace=True)
+
+
+# Lightly adapted from
+# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py
+class MLP(Module):
+ def __init__(
+ self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, sigmoid_output: bool = False
+ ) -> None:
+ super().__init__()
+ self.num_layers = num_layers
+ h = [hidden_dim] * (num_layers - 1)
+ self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
+ self.sigmoid_output = sigmoid_output
+
+ def forward(self, x: Tensor) -> Tensor:
+ for i, layer in enumerate(self.layers):
+ x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
+ if self.sigmoid_output:
+ x = F.sigmoid(x)
+ return x
diff --git a/kornia/contrib/models/rt_detr/__init__.py b/kornia/contrib/models/rt_detr/__init__.py
new file mode 100644
index 000000000..6c3d06e78
--- /dev/null
+++ b/kornia/contrib/models/rt_detr/__init__.py
@@ -0,0 +1,2 @@
+from kornia.contrib.models.rt_detr.model import RTDETR, RTDETRConfig, RTDETRModelType
+from kornia.contrib.models.rt_detr.post_processor import DETRPostProcessor
diff --git a/kornia/contrib/models/rt_detr/architecture/__init__.py b/kornia/contrib/models/rt_detr/architecture/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/kornia/contrib/models/rt_detr/architecture/hgnetv2.py b/kornia/contrib/models/rt_detr/architecture/hgnetv2.py
new file mode 100644
index 000000000..db12bf7a8
--- /dev/null
+++ b/kornia/contrib/models/rt_detr/architecture/hgnetv2.py
@@ -0,0 +1,130 @@
+"""Based on code from
+https://github.com/PaddlePaddle/PaddleDetection/blob/ec37e66685f3bc5a38cd13f60685acea175922e1/
+ppdet/modeling/backbones/hgnet_v2.py."""
+
+from __future__ import annotations
+
+from typing import NamedTuple
+
+from torch import nn
+
+from kornia.contrib.models.common import ConvNormAct
+from kornia.core import Module, Tensor, concatenate
+from kornia.core.check import KORNIA_CHECK
+
+
+class StemBlock(Module):
+ def __init__(self, in_channels: int, mid_channels: int, out_channels: int) -> None:
+ super().__init__()
+ self.stem1 = ConvNormAct(in_channels, mid_channels, 3, 2)
+ self.stem2a = ConvNormAct(mid_channels, mid_channels // 2, 2)
+ self.stem2b = ConvNormAct(mid_channels // 2, mid_channels, 2)
+ self.stem3 = ConvNormAct(mid_channels * 2, mid_channels, 3, 2)
+ self.stem4 = ConvNormAct(mid_channels, out_channels, 1)
+ self.pool = nn.Sequential(nn.ZeroPad2d((0, 1, 0, 1)), nn.MaxPool2d(2, 1))
+
+ def forward(self, x: Tensor) -> Tensor:
+ x = self.stem1(x)
+ x = concatenate([self.pool(x), self.stem2b(self.stem2a(x))], 1)
+ x = self.stem4(self.stem3(x))
+ return x
+
+
+# Separable conv
+class LightConvNormAct(nn.Sequential):
+ def __init__(self, in_channels: int, out_channels: int, kernel_size: int) -> None:
+ super().__init__()
+ self.conv1 = ConvNormAct(in_channels, out_channels, 1, act="none") # point-wise
+ self.conv2 = ConvNormAct(out_channels, out_channels, kernel_size, groups=out_channels) # depth-wise
+
+
+class StageConfig(NamedTuple):
+ in_channels: int
+ mid_channels: int
+ out_channels: int
+ num_blocks: int
+ downsample: bool
+ light_block: bool
+ kernel_size: int
+ layer_num: int
+
+
+class HGBlock(Module):
+ def __init__(self, in_channels: int, config: StageConfig, identity: bool) -> None:
+ super().__init__()
+ self.identity = identity
+
+ layer_cls = LightConvNormAct if config.light_block else ConvNormAct
+ self.layers = nn.ModuleList()
+ for i in range(config.layer_num):
+ ch_in = in_channels if i == 0 else config.mid_channels
+ self.layers.append(layer_cls(ch_in, config.mid_channels, config.kernel_size))
+
+ total_channels = in_channels + config.mid_channels * config.layer_num
+ self.aggregation_squeeze_conv = ConvNormAct(total_channels, config.out_channels // 2, 1)
+ self.aggregation_excitation_conv = ConvNormAct(config.out_channels // 2, config.out_channels, 1)
+
+ def forward(self, x: Tensor) -> Tensor:
+ feats = [x]
+ for layer in self.layers:
+ feats.append(layer(feats[-1]))
+ out = concatenate(feats, 1)
+ out = self.aggregation_squeeze_conv(out)
+ out = self.aggregation_excitation_conv(out)
+ return x + out if self.identity else out
+
+
+class HGStage(nn.Sequential):
+ def __init__(self, config: StageConfig) -> None:
+ super().__init__()
+ ch_in = config.in_channels
+ self.downsample = ConvNormAct(ch_in, ch_in, 3, 2, "none", ch_in) if config.downsample else None
+ self.blocks = nn.Sequential(
+ HGBlock(ch_in, config, False),
+ *[HGBlock(config.out_channels, config, True) for _ in range(config.num_blocks - 1)],
+ )
+
+
+class PPHGNetV2(Module):
+ def __init__(self, stem_channels: list[int], stage_configs: list[StageConfig]) -> None:
+ KORNIA_CHECK(len(stem_channels) == 3)
+ KORNIA_CHECK(len(stage_configs) == 4)
+ super().__init__()
+ self.out_channels = [config.out_channels for config in stage_configs[-3:]]
+ self.stem = StemBlock(*stem_channels)
+ self.stages = nn.ModuleList()
+ for cfg in stage_configs:
+ self.stages.append(HGStage(cfg))
+
+ def forward(self, x: Tensor) -> list[Tensor]:
+ x = self.stem(x)
+ s2 = self.stages[0](x)
+ s3 = self.stages[1](s2)
+ s4 = self.stages[2](s3)
+ s5 = self.stages[3](s4)
+ return [s3, s4, s5]
+
+ @staticmethod
+ def from_config(variant: str) -> PPHGNetV2:
+ if variant == "L":
+ return PPHGNetV2(
+ stem_channels=[3, 32, 48],
+ stage_configs=[
+ StageConfig(48, 48, 128, 1, False, False, 3, 6),
+ StageConfig(128, 96, 512, 1, True, False, 3, 6),
+ StageConfig(512, 192, 1024, 3, True, True, 5, 6),
+ StageConfig(1024, 384, 2048, 1, True, True, 5, 6),
+ ],
+ )
+ elif variant == "X":
+ return PPHGNetV2(
+ stem_channels=[3, 32, 64],
+ stage_configs=[
+ StageConfig(64, 64, 128, 1, False, False, 3, 6),
+ StageConfig(128, 128, 512, 2, True, False, 3, 6),
+ StageConfig(512, 256, 1024, 5, True, True, 5, 6),
+ StageConfig(1024, 512, 2048, 2, True, True, 5, 6),
+ ],
+ )
+ else:
+ raise ValueError("Only variant L and X are supported")
diff --git a/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py b/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py
new file mode 100644
index 000000000..e9f1a5856
--- /dev/null
+++ b/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py
@@ -0,0 +1,195 @@
+"""Based on the code from
+https://github.com/PaddlePaddle/PaddleDetection/blob/ec37e66685f3bc5a38cd13f60685acea175922e1/
+ppdet/modeling/transformers/hybrid_encoder.py."""
+
+from __future__ import annotations
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+from torch.nn.utils.fusion import fuse_conv_bn_weights
+
+from kornia.contrib.models.common import ConvNormAct
+from kornia.core import Module, Tensor, concatenate, pad
+
+
+class RepVggBlock(Module):
+ def __init__(self, in_channels: int, out_channels: int) -> None:
+ super().__init__()
+ self.conv1 = ConvNormAct(in_channels, out_channels, 3, act="none")
+ self.conv2 = ConvNormAct(in_channels, out_channels, 1, act="none")
+ self.act = nn.SiLU(inplace=True)
+ self.conv: nn.Conv2d | None = None
+
+ def forward(self, x: Tensor) -> Tensor:
+ if self.conv is not None:
+ out = self.act(self.conv(x))
+ else:
+ out = self.act(self.conv1(x) + self.conv2(x))
+ return out
+
+ @torch.no_grad()
+ def optimize_for_deployment(self) -> None:
+ def _fuse_conv_bn_weights(m: ConvNormAct) -> tuple[nn.Parameter, nn.Parameter]:
+ return fuse_conv_bn_weights(
+ m.conv.weight,
+ m.conv.bias,
+ m.norm.running_mean,
+ m.norm.running_var,
+ m.norm.eps,
+ m.norm.weight,
+ m.norm.bias,
+ )
+
+ kernel3x3, bias3x3 = _fuse_conv_bn_weights(self.conv1)
+ kernel1x1, bias1x1 = _fuse_conv_bn_weights(self.conv2)
+ kernel3x3.add_(pad(kernel1x1, [1, 1, 1, 1]))
+ bias3x3.add_(bias1x1)
+
+ self.conv = nn.Conv2d(kernel3x3.shape[1], kernel3x3.shape[0], 3, 1, 1)
+ self.conv.weight = kernel3x3
+ self.conv.bias = bias3x3
+
+
+class CSPRepLayer(Module):
+ def __init__(self, in_channels: int, out_channels: int, num_blocks: int, expansion: float = 1.0) -> None:
+ super().__init__()
+ hidden_channels = int(out_channels * expansion)
+ self.conv1 = ConvNormAct(in_channels, hidden_channels, 1, act="silu")
+ self.conv2 = ConvNormAct(in_channels, hidden_channels, 1, act="silu")
+ self.bottlenecks = nn.Sequential(*[RepVggBlock(hidden_channels, hidden_channels) for _ in range(num_blocks)])
+ self.conv3 = (
+ ConvNormAct(hidden_channels, out_channels, 1, act="silu")
+ if hidden_channels != out_channels
+ else nn.Identity()
+ )
+
+ def forward(self, x: Tensor) -> Tensor:
+ return self.conv3(self.bottlenecks(self.conv1(x)) + self.conv2(x))
+
+
+# almost identical to nn.TransformerEncoderLayer
+# but add positional embeddings to q and k
+class AIFI(Module):
+ def __init__(self, embed_dim: int, num_heads: int, dim_feedforward: int, dropout: float = 0.0) -> None:
+ super().__init__()
+ self.self_attn = nn.MultiheadAttention(embed_dim, num_heads, dropout) # NOTE: batch_first = False
+ self.dropout1 = nn.Dropout(dropout)
+ self.norm1 = nn.LayerNorm(embed_dim)
+
+ self.linear1 = nn.Linear(embed_dim, dim_feedforward)
+ self.act = nn.GELU()
+ self.dropout = nn.Dropout(dropout)
+ self.linear2 = nn.Linear(dim_feedforward, embed_dim)
+ self.dropout2 = nn.Dropout(dropout)
+ self.norm2 = nn.LayerNorm(embed_dim)
+
+ def forward(self, x: Tensor) -> Tensor:
+ # using post-norm
+ N, C, H, W = x.shape
+ x = x.permute(2, 3, 0, 1).flatten(0, 1) # (N, C, H, W) -> (H * W, N, C)
+
+ # NOTE: cache pos_emb as buffer
+ pos_emb = self.build_2d_sincos_pos_emb(W, H, C, device=x.device, dtype=x.dtype)
+ q = k = x + pos_emb
+ x = self.norm1(x + self.dropout1(self.self_attn(q, k, x, need_weights=False)[0]))
+ x = self.norm2(x + self.dropout2(self.ffn(x)))
+
+ x = x.view(H, W, N, C).permute(2, 3, 0, 1) # (H * W, N, C) -> (N, C, H, W)
+ return x
+
+ def ffn(self, x: Tensor) -> Tensor:
+ return self.linear2(self.dropout(self.act(self.linear1(x))))
+
+ # TODO: make this into a reusable function
+ # https://github.com/facebookresearch/moco-v3/blob/main/vits.py#L53
+ # https://github.com/PaddlePaddle/PaddleDetection/blob/79267419e1743157f376a7cb251e01caa3338ce0/ppdet/modeling/transformers/hybrid_encoder.py#L217
+ @staticmethod
+ def build_2d_sincos_pos_emb(
+ w: int,
+ h: int,
+ embed_dim: int,
+ temp: float = 10_000.0,
+ device: torch.device | None = None,
+ dtype: torch.dtype | None = None,
+ ) -> Tensor:
+ """Construct 2D sin-cos positional embeddings.
+
+ Args:
+ w: width of the image or feature map
+ h: height of the image or feature map
+ embed_dim: embedding dimension
+ temp: temperature coefficient
+ device: device to place the positional embeddings
+ dtype: data type of the positional embeddings
+
+ Returns:
+ positional embeddings, shape :math:`(H * W, 1, C)`
+ """
+ xs = torch.arange(w, device=device, dtype=dtype)
+ ys = torch.arange(h, device=device, dtype=dtype)
+ grid_x, grid_y = torch.meshgrid(xs, ys)
+
+ pos_dim = embed_dim // 4
+ omega = torch.arange(pos_dim, device=device, dtype=dtype) / pos_dim
+ omega = 1.0 / (temp**omega)
+
+ out_x = grid_x.reshape(-1, 1) * omega.view(1, -1)
+ out_y = grid_y.reshape(-1, 1) * omega.view(1, -1)
+
+ pos_emb = concatenate([out_x.sin(), out_x.cos(), out_y.sin(), out_y.cos()], 1)
+ return pos_emb.unsqueeze(1) # (H * W, 1, C)
+
+
+class CCFM(Module):
+ def __init__(self, num_fmaps: int, hidden_dim: int, expansion: float = 1.0) -> None:
+ super().__init__()
+ self.lateral_convs = nn.ModuleList()
+ self.fpn_blocks = nn.ModuleList()
+ for _ in range(num_fmaps - 1):
+ self.lateral_convs.append(ConvNormAct(hidden_dim, hidden_dim, 1, 1, "silu"))
+ self.fpn_blocks.append(CSPRepLayer(hidden_dim * 2, hidden_dim, 3, expansion))
+
+ self.downsample_convs = nn.ModuleList()
+ self.pan_blocks = nn.ModuleList()
+ for _ in range(num_fmaps - 1):
+ self.downsample_convs.append(ConvNormAct(hidden_dim, hidden_dim, 3, 2, "silu"))
+ self.pan_blocks.append(CSPRepLayer(hidden_dim * 2, hidden_dim, 3, expansion))
+
+ def forward(self, fmaps: list[Tensor]) -> list[Tensor]:
+ # fmaps is ordered from hi-res to low-res
+ fmaps = list(fmaps) # shallow clone
+
+ # new_fmaps is ordered from low-res to hi-res
+ new_fmaps = [fmaps.pop()]
+ while fmaps:
+ new_fmaps[-1] = self.lateral_convs[len(new_fmaps) - 1](new_fmaps[-1])
+ up_lowres_fmap = F.interpolate(new_fmaps[-1], scale_factor=2.0, mode="nearest")
+ hires_fmap = fmaps.pop()
+
+ concat_fmap = concatenate([up_lowres_fmap, hires_fmap], 1)
+ new_fmaps.append(self.fpn_blocks[len(new_fmaps) - 1](concat_fmap))
+
+ fmaps = [new_fmaps.pop()]
+ while new_fmaps:
+ down_hires_fmap = self.downsample_convs[len(fmaps) - 1](fmaps[-1])
+ lowres_fmap = new_fmaps.pop()
+
+ concat_fmap = concatenate([down_hires_fmap, lowres_fmap], 1)
+ fmaps.append(self.pan_blocks[len(fmaps) - 1](concat_fmap))
+
+ return fmaps
+
+
+class HybridEncoder(Module):
+ def __init__(self, in_channels: list[int], hidden_dim: int, dim_feedforward: int, expansion: float = 1.0) -> None:
+ super().__init__()
+ self.input_proj = nn.ModuleList([ConvNormAct(in_ch, hidden_dim, 1, act="none") for in_ch in in_channels])
+ self.aifi = AIFI(hidden_dim, 8, dim_feedforward)
+ self.ccfm = CCFM(len(in_channels), hidden_dim, expansion)
+
+ def forward(self, fmaps: list[Tensor]) -> list[Tensor]:
+ fmaps = [proj(fmap) for proj, fmap in zip(self.input_proj, fmaps)]
+ fmaps[-1] = self.aifi(fmaps[-1])
+ fmaps = self.ccfm(fmaps)
+ return fmaps
diff --git a/kornia/contrib/models/rt_detr/architecture/resnet_d.py b/kornia/contrib/models/rt_detr/architecture/resnet_d.py
new file mode 100644
index 000000000..d144e200b
--- /dev/null
+++ b/kornia/contrib/models/rt_detr/architecture/resnet_d.py
@@ -0,0 +1,110 @@
+"""ResNet-D as described in https://arxiv.org/abs/1812.01187.
+
+Based on the code from https://github.com/pytorch/vision/blob/v0.15.1/torchvision/models/resnet.py
+https://github.com/PaddlePaddle/PaddleDetection/blob/release/2.6/ppdet/modeling/backbones/resnet.py
+"""
+from __future__ import annotations
+
+from torch import nn
+
+from kornia.contrib.models.common import ConvNormAct
+from kornia.core import Module, Tensor
+from kornia.core.check import KORNIA_CHECK
+
+
+def _make_shortcut(in_channels: int, out_channels: int, stride: int) -> Module:
+ return (
+ nn.Sequential(nn.AvgPool2d(2, 2), ConvNormAct(in_channels, out_channels, 1, act="none"))
+ if stride == 2
+ else ConvNormAct(in_channels, out_channels, 1, act="none")
+ )
+
+
+class BasicBlockD(Module):
+ expansion = 1
+
+ def __init__(self, in_channels: int, out_channels: int, stride: int, shortcut: bool) -> None:
+ KORNIA_CHECK(stride in {1, 2})
+ super().__init__()
+ self.convs = nn.Sequential(
+ ConvNormAct(in_channels, out_channels, 3, stride=stride),
+ ConvNormAct(out_channels, out_channels, 3, act="none"),
+ )
+ self.shortcut = nn.Identity() if shortcut else _make_shortcut(in_channels, out_channels, stride)
+ self.relu = nn.ReLU(inplace=True)
+
+ def forward(self, x: Tensor) -> Tensor:
+ return self.relu(self.convs(x) + self.shortcut(x))
+
+
+class BottleneckD(Module):
+ expansion = 4
+
+ def __init__(self, in_channels: int, out_channels: int, stride: int, shortcut: bool) -> None:
+ KORNIA_CHECK(stride in {1, 2})
+ super().__init__()
+ expanded_out_channels = out_channels * self.expansion
+ self.convs = nn.Sequential(
+ ConvNormAct(in_channels, out_channels, 1),
+ ConvNormAct(out_channels, out_channels, 3, stride=stride),
+ ConvNormAct(out_channels, expanded_out_channels, 1, act="none"),
+ )
+ self.shortcut = nn.Identity() if shortcut else _make_shortcut(in_channels, expanded_out_channels, stride)
+ self.relu = nn.ReLU(inplace=True)
+
+ def forward(self, x: Tensor) -> Tensor:
+ return self.relu(self.convs(x) + self.shortcut(x))
+
+
+class ResNetD(Module):
+ def __init__(self, n_blocks: list[int], block: type[BasicBlockD | BottleneckD]) -> None:
+ KORNIA_CHECK(len(n_blocks) == 4)
+ super().__init__()
+ in_channels = 64
+ self.conv1 = nn.Sequential(
+ ConvNormAct(3, in_channels // 2, 3, stride=2),
+ ConvNormAct(in_channels // 2, in_channels // 2, 3),
+ ConvNormAct(in_channels // 2, in_channels, 3),
+ nn.MaxPool2d(3, stride=2, padding=1),
+ )
+
+ self.res2, in_channels = self.make_stage(in_channels, 64, 1, n_blocks[0], block)
+ self.res3, in_channels = self.make_stage(in_channels, 128, 2, n_blocks[1], block)
+ self.res4, in_channels = self.make_stage(in_channels, 256, 2, n_blocks[2], block)
+ self.res5, in_channels = self.make_stage(in_channels, 512, 2, n_blocks[3], block)
+
+ self.out_channels = [ch * block.expansion for ch in [128, 256, 512]]
+
+ @staticmethod
+ def make_stage(
+ in_channels: int, out_channels: int, stride: int, n_blocks: int, block: type[BasicBlockD | BottleneckD]
+ ) -> tuple[Module, int]:
+ stage = nn.Sequential(
+ block(in_channels, out_channels, stride, False),
+ *[block(out_channels * block.expansion, out_channels, 1, True) for _ in range(n_blocks - 1)],
+ )
+ return stage, out_channels * block.expansion
+
+ def forward(self, x: Tensor) -> list[Tensor]:
+ x = self.conv1(x)
+ res2 = self.res2(x)
+ res3 = self.res3(res2)
+ res4 = self.res4(res3)
+ res5 = self.res5(res4)
+ return [res3, res4, res5]
+
+ @staticmethod
+ def from_config(variant: str | int) -> ResNetD:
+ variant = str(variant)
+ if variant == "18":
+ return ResNetD([2, 2, 2, 2], BasicBlockD)
+ elif variant == "34":
+ return ResNetD([3, 4, 6, 3], BasicBlockD)
+ elif variant == "50":
+ return ResNetD([3, 4, 6, 3], BottleneckD)
+ elif variant == "101":
+ return ResNetD([3, 4, 23, 3], BottleneckD)
+ elif variant == "152":
+ return ResNetD([3, 8, 36, 3], BottleneckD)
+ else:
+ raise ValueError("Only variant 18, 34, 50, 101, and 152 are supported")
diff --git a/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py b/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py
new file mode 100644
index 000000000..c9001da14
--- /dev/null
+++ b/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py
@@ -0,0 +1,236 @@
+"""Based on code from
+https://github.com/PaddlePaddle/PaddleDetection/blob/ec37e66685f3bc5a38cd13f60685acea175922e1/
+ppdet/modeling/transformers/rtdetr_transformer.py."""
+
+from __future__ import annotations
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from kornia.contrib.models.common import MLP, ConvNormAct
+from kornia.core import Module, Tensor, concatenate
+from kornia.utils import create_meshgrid
+
+
+class MultiScaleDeformableAttention(Module):
+ """Multi-scale Deformable Attention used in Deformable DETR, as described in
+ https://arxiv.org/abs/2010.04159."""
+
+ def __init__(self, embed_dim: int, num_heads: int, num_levels: int, num_points: int) -> None:
+ super().__init__()
+ self.num_heads = num_heads
+ self.num_levels = num_levels
+ self.num_points = num_points
+ self.total_points = num_heads * num_levels * num_points
+
+ self.sampling_offsets = nn.Linear(embed_dim, self.total_points * 2)
+ self.attention_weights = nn.Linear(embed_dim, self.total_points)
+ self.value_proj = nn.Linear(embed_dim, embed_dim)
+ self.output_proj = nn.Linear(embed_dim, embed_dim)
+
+ def forward(
+ self, query: Tensor, ref_points: Tensor, value: Tensor, value_spatial_shapes: list[tuple[int, int]]
+ ) -> Tensor:
+ """
+ Args:
+ query: shape (N, Lq, C)
+ ref_points: shape (N, Lq, n_levels, 4)
+ value: shape (N, Lv, C)
+ value_spatial_shapes: [(H0, W0), (H1, W1), ...]
+
+ Returns:
+ output, shape (N, Lq, C)
+ """
+ N, Lq, C = query.shape
+ sampling_offsets = self.sampling_offsets(query).view(N, Lq, self.num_heads, self.num_levels, self.num_points, 2)
+ attention_weights = self.attention_weights(query).view(N, Lq, self.num_heads, self.num_levels * self.num_points)
+ attention_weights = attention_weights.softmax(-1).view(N, Lq, self.num_heads, self.num_levels, self.num_points)
+
+ # (N, Lq, num_heads, num_levels, num_points, 2)
+ ref_points_cxcy = ref_points[:, :, None, :, None, :2]
+ ref_points_wh = ref_points[:, :, None, :, None, 2:]
+ sampling_locations = ref_points_cxcy + sampling_offsets / self.num_points * ref_points_wh * 0.5
+
+ # https://github.com/PaddlePaddle/PaddleDetection/blob/release/2.6/ppdet/modeling/transformers/utils.py#L71
+ # https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/ops/functions/ms_deform_attn_func.py#L41
+ split_size = [H * W for H, W in value_spatial_shapes]
+ value_list = self.value_proj(value).split(split_size, 1)
+ sampling_grids = 2 * sampling_locations - 1
+
+ # NOTE: this can be sped up with torch.vmap() ?
+ sampling_value_list = []
+ for level, (H, W) in enumerate(value_spatial_shapes):
+ # (N * num_heads, head_dim, H, W)
+ value_l_ = value_list[level].permute(0, 2, 1).reshape(N * self.num_heads, -1, H, W)
+ # (N * num_heads, Lq, num_points, 2)
+ sampling_grid_l_ = sampling_grids[:, :, :, level].permute(0, 2, 1, 3, 4).flatten(0, 1)
+ # (N * num_heads, head_dim, Lq, num_points)
+ sampling_value_list.append(F.grid_sample(value_l_, sampling_grid_l_, "bilinear", "zeros", False))
+
+ # (N * num_heads, head_dim, Lq, num_levels * num_points)
+ sampling_value = concatenate(sampling_value_list, -1)
+
+ # NOTE: probably can be simplified and sped up with einsum
+ attention_weights = attention_weights.permute(0, 2, 1, 3, 4)
+ attention_weights = attention_weights.reshape(N * self.num_heads, 1, Lq, self.num_levels * self.num_points)
+ out = (sampling_value * attention_weights).sum(-1)
+ out = out.reshape(N, C, Lq).permute(0, 2, 1)
+ return self.output_proj(out)
+
+
+# this is similar to nn.TransformerDecoderLayer, but replace cross attention with deformable attention
+# add use positional embeddings
+# https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/deformable_transformer.py#L261
+class DeformableTransformerDecoderLayer(Module):
+ """Deformable Transformer Decoder layer used in Deformable DETR, as described in
+ https://arxiv.org/abs/2010.04159."""
+
+ def __init__(
+ self, embed_dim: int, num_levels: int, num_heads: int = 8, num_points: int = 4, dropout: float = 0.0
+ ) -> None:
+ super().__init__()
+ self.self_attn = nn.MultiheadAttention(embed_dim, num_heads, dropout, batch_first=True)
+ self.dropout1 = nn.Dropout(dropout)
+ self.norm1 = nn.LayerNorm(embed_dim)
+
+ self.cross_attn = MultiScaleDeformableAttention(embed_dim, num_heads, num_levels, num_points)
+ self.dropout2 = nn.Dropout(dropout)
+ self.norm2 = nn.LayerNorm(embed_dim)
+
+ self.linear1 = nn.Linear(embed_dim, embed_dim * 4)
+ self.act = nn.ReLU(inplace=True)
+ self.dropout3 = nn.Dropout(dropout)
+ self.linear2 = nn.Linear(embed_dim * 4, embed_dim)
+ self.dropout4 = nn.Dropout(dropout)
+ self.norm3 = nn.LayerNorm(embed_dim)
+
+ def forward(
+ self,
+ tgt: Tensor,
+ ref_points: Tensor,
+ memory: Tensor,
+ memory_spatial_shapes: list[tuple[int, int]],
+ query_pos_embed: Tensor,
+ ) -> Tensor:
+ q = k = tgt + query_pos_embed
+ out, _ = self.self_attn(q, k, tgt, need_weights=False)
+ tgt = self.norm1(tgt + self.dropout1(out))
+
+ out = self.cross_attn(tgt + query_pos_embed, ref_points, memory, memory_spatial_shapes)
+ tgt = self.norm2(tgt + self.dropout2(out))
+
+ return self.norm3(tgt + self.dropout4(self.ffn(tgt)))
+
+ def ffn(self, x: Tensor) -> Tensor:
+ return self.linear2(self.dropout3(self.act(self.linear1(x))))
+
+
+class RTDETRHead(Module):
+ def __init__(
+ self,
+ num_classes: int,
+ hidden_dim: int,
+ num_queries: int,
+ in_channels: list[int],
+ num_decoder_layers: int,
+ num_heads: int = 8,
+ num_decoder_points: int = 4,
+ ) -> None:
+ super().__init__()
+ self.num_queries = num_queries
+ self.input_proj = nn.ModuleList()
+ for ch_in in in_channels:
+ self.input_proj.append(ConvNormAct(ch_in, hidden_dim, 1, act="none"))
+
+ self.enc_output = nn.Sequential(nn.Linear(hidden_dim, hidden_dim), nn.LayerNorm(hidden_dim))
+ self.enc_score_head = nn.Linear(hidden_dim, num_classes)
+ self.enc_bbox_head = MLP(hidden_dim, hidden_dim, 4, 3)
+
+ self.denoising_class_embed = nn.Embedding(num_classes, hidden_dim) # not used in evaluation
+ self.query_pos_head = MLP(4, hidden_dim * 2, hidden_dim, 2)
+
+ self.decoder_layers = nn.ModuleList()
+ self.dec_score_head = nn.ModuleList()
+ self.dec_bbox_head = nn.ModuleList()
+ for _ in range(num_decoder_layers):
+ layer = DeformableTransformerDecoderLayer(hidden_dim, len(in_channels), num_heads, num_decoder_points)
+ self.decoder_layers.append(layer)
+ self.dec_score_head.append(nn.Linear(hidden_dim, num_classes))
+ self.dec_bbox_head.append(MLP(hidden_dim, hidden_dim, 4, 3))
+
+ def forward(self, fmaps: list[Tensor]) -> tuple[Tensor, Tensor]:
+ # NOTE: remove this once training is supported
+ if self.training:
+ raise RuntimeError("Only evaluation mode is supported. Please call model.eval().")
+
+ N = fmaps[0].shape[0]
+ fmaps = [proj(fmap) for proj, fmap in zip(self.input_proj, fmaps)]
+ spatial_shapes = [(fmap.shape[2], fmap.shape[3]) for fmap in fmaps]
+
+ feats = [fmap.flatten(2).permute(0, 2, 1) for fmap in fmaps] # (N, C, H, W) -> (N, H*W, C)
+ memory = concatenate(feats, 1) # rename to match original impl
+
+ # TODO: cache anchors and valid_mask as buffers
+ anchors, valid_mask = self.generate_anchors(spatial_shapes, device=memory.device, dtype=memory.dtype)
+
+ # NOTE: why not use the mask to gather the values here, instead of filling zeros with torch.where()?
+ zero = torch.zeros([], device=memory.device, dtype=memory.dtype)
+ out_memory = torch.where(valid_mask, memory, zero)
+ out_memory = self.enc_output(out_memory)
+
+ enc_out_logits = self.enc_score_head(out_memory)
+ enc_out_bboxes = anchors + self.enc_bbox_head(out_memory)
+
+ # only consider class with highest score at each spatial location
+ _, topk_indices = enc_out_logits.max(-1)[0].topk(self.num_queries, 1) # (N, num_queries)
+ batch_indices = torch.arange(N, dtype=topk_indices.dtype, device=topk_indices.device).unsqueeze(1)
+ ref_points = enc_out_bboxes[batch_indices, topk_indices]
+ tgt = out_memory[batch_indices, topk_indices]
+
+ # iterative box refinements
+ for decoder_layer, bbox_head in zip(self.decoder_layers, self.dec_bbox_head):
+ ref_points_sigmoid = ref_points.sigmoid()
+ query_pos_embed = self.query_pos_head(ref_points_sigmoid)
+ tgt = decoder_layer(tgt, ref_points_sigmoid.unsqueeze(2), memory, spatial_shapes, query_pos_embed)
+ ref_points = ref_points + bbox_head(tgt)
+ logits = self.dec_score_head[-1](tgt) # in evaluation, only last score head is used
+
+ return logits, ref_points.sigmoid()
+
+ @staticmethod
+ def generate_anchors(
+ spatial_shapes: list[tuple[int, int]],
+ grid_size: float = 0.05,
+ eps: float = 0.01,
+ device: torch.device | None = None,
+ dtype: torch.dtype = torch.float32,
+ ) -> tuple[Tensor, Tensor]:
+ """Generate anchors for RT-DETR.
+
+ Args:
+ spatial_shapes: shape (width, height) of the feature maps
+ grid_size: size of the grid
+ eps: specify the minimum and maximum size of the anchors
+ device: device to place the anchors
+ dtype: data type for the anchors
+
+ Returns:
+ logit of anchors and mask
+ """
+ # TODO: might make this (or some parts of it) into a separate reusable function
+ anchors_list = []
+ for i, (H, W) in enumerate(spatial_shapes):
+ grid_xy = create_meshgrid(H, W, normalized_coordinates=False, device=device, dtype=dtype)
+ grid_xy = (grid_xy + 0.5) / torch.tensor([H, W], device=device, dtype=dtype)
+ wh = torch.ones_like(grid_xy) * grid_size * 2**i
+ anchors_list.append(concatenate([grid_xy, wh], -1).reshape(-1, H * W, 4))
+
+ anchors = concatenate(anchors_list, 1)
+ valid_mask = ((anchors > eps) & (anchors < 1 - eps)).all(-1, keepdim=True)
+ anchors = torch.log(anchors / (1 - anchors)) # anchors.logit() fails ONNX export
+
+ # anchors = torch.where(valid_mask, anchors, float("inf")) fails in PyTorch 1.9.1
+ inf = torch.tensor(float('inf'), device=device, dtype=dtype)
+ anchors = torch.where(valid_mask, anchors, inf)
+ return anchors, valid_mask
diff --git a/kornia/contrib/models/rt_detr/model.py b/kornia/contrib/models/rt_detr/model.py
new file mode 100644
index 000000000..ff69a5293
--- /dev/null
+++ b/kornia/contrib/models/rt_detr/model.py
@@ -0,0 +1,174 @@
+"""Based on code from PaddleDetection."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from enum import Enum
+
+from kornia.contrib.models.base import ModelBase
+from kornia.contrib.models.rt_detr.architecture.hgnetv2 import PPHGNetV2
+from kornia.contrib.models.rt_detr.architecture.hybrid_encoder import HybridEncoder
+from kornia.contrib.models.rt_detr.architecture.resnet_d import ResNetD
+from kornia.contrib.models.rt_detr.architecture.rtdetr_head import RTDETRHead
+from kornia.core import Tensor
+
+
+class RTDETRModelType(Enum):
+ """Enum class that maps RT-DETR model type."""
+
+ resnet18d = 0
+ resnet34d = 1
+ resnet50d = 2
+ resnet101d = 3
+ hgnetv2_l = 4
+ hgnetv2_x = 5
+
+
+@dataclass
+class RTDETRConfig:
+ """Configuration to construct RT-DETR model.
+
+ Args:
+ model_type: model variant. Available models are
+
+ - ResNetD-18: ``0``, ``'resnet18d'`` or :attr:`RTDETRModelType.resnet18d`
+ - ResNetD-34: ``1``, ``'resnet34d'`` or :attr:`RTDETRModelType.resnet34d`
+ - ResNetD-50: ``2``, ``'resnet50d'`` or :attr:`RTDETRModelType.resnet50d`
+ - ResNetD-101: ``3``, ``'resnet101d'`` or :attr:`RTDETRModelType.resnet101d`
+ - HGNetV2-L: ``4``, ``'hgnetv2_l'`` or :attr:`RTDETRModelType.hgnetv2_l`
+ - HGNetV2-X: ``5``, ``'hgnetv2_x'`` or :attr:`RTDETRModelType.hgnetv2_x`
+
+ num_classes: number of classes.
+ checkpoint: URL or local path of model weights.
+ neck_hidden_dim: hidden dim for neck.
+ neck_dim_feedforward: feed-forward network dim for neck.
+ neck_expansion: expansion ratio for neck.
+ head_hidden_dim: hidden dim for head.
+ head_num_queries: number of queries for Deformable DETR transformer decoder.
+ head_num_decoder_layers: number of decoder layers for Deformable DETR transformer decoder.
+ """
+
+ model_type: RTDETRModelType | str | int
+ num_classes: int
+ checkpoint: str | None = None
+
+ neck_hidden_dim: int | None = None
+ neck_dim_feedforward: int | None = None
+ neck_expansion: float | None = None
+ head_hidden_dim: int = 256
+ head_num_queries: int = 300
+ head_num_decoder_layers: int | None = None
+ confidence_threshold: float = 0.3
+
+
+class RTDETR(ModelBase[RTDETRConfig]):
+ """RT-DETR Object Detection model, as described in https://arxiv.org/abs/2304.08069."""
+
+ def __init__(self, backbone: ResNetD | PPHGNetV2, neck: HybridEncoder, head: RTDETRHead):
+ """Construct RT-DETR Object Detection model.
+
+ Args:
+ backbone: backbone network for feature extraction.
+ neck: neck network for feature fusion.
+ head: head network to decode features into detection results.
+ """
+ super().__init__()
+ self.backbone = backbone
+ self.neck = neck
+ self.head = head
+
+ @staticmethod
+ def from_config(config: RTDETRConfig) -> RTDETR:
+ """Construct RT-DETR Object Detection model from a config object.
+
+ Args:
+ config: configuration object for RT-DETR.
+
+ .. note::
+ For ``config.neck_hidden_dim``, ``config.neck_dim_feedforward``, ``config.neck_expansion``, and
+ ``config.head_num_decoder_layers``, if they are ``None``, their values will be replaced with the
+ default values depending on the ``config.model_type``. See the source code for the default values.
+ """
+ model_type = config.model_type
+ if isinstance(model_type, int):
+ model_type = RTDETRModelType(model_type)
+ elif isinstance(model_type, str):
+ model_type = getattr(RTDETRModelType, model_type)
+
+ backbone: ResNetD | PPHGNetV2
+
+ if model_type == RTDETRModelType.resnet18d:
+ backbone = ResNetD.from_config(18)
+ neck_hidden_dim = config.neck_hidden_dim or 256
+ neck_dim_feedforward = config.neck_dim_feedforward or 1024
+ head_num_decoder_layers = config.head_num_decoder_layers or 3
+ neck_expansion = config.neck_expansion or 0.5
+
+ elif model_type == RTDETRModelType.resnet34d:
+ backbone = ResNetD.from_config(34)
+ neck_hidden_dim = config.neck_hidden_dim or 256
+ neck_dim_feedforward = config.neck_dim_feedforward or 1024
+ head_num_decoder_layers = config.head_num_decoder_layers or 4
+ neck_expansion = config.neck_expansion or 0.5
+
+ elif model_type == RTDETRModelType.resnet50d:
+ backbone = ResNetD.from_config(50)
+ neck_hidden_dim = config.neck_hidden_dim or 256
+ neck_dim_feedforward = config.neck_dim_feedforward or 1024
+ head_num_decoder_layers = config.head_num_decoder_layers or 6
+ neck_expansion = config.neck_expansion or 1.0
+
+ elif model_type == RTDETRModelType.resnet101d:
+ backbone = ResNetD.from_config(101)
+ neck_hidden_dim = config.neck_hidden_dim or 384
+ neck_dim_feedforward = config.neck_dim_feedforward or 2048
+ head_num_decoder_layers = config.head_num_decoder_layers or 6
+ neck_expansion = config.neck_expansion or 1.0
+
+ elif model_type == RTDETRModelType.hgnetv2_l:
+ backbone = PPHGNetV2.from_config("L")
+ neck_hidden_dim = config.neck_hidden_dim or 256
+ neck_dim_feedforward = config.neck_dim_feedforward or 1024
+ head_num_decoder_layers = config.head_num_decoder_layers or 6
+ neck_expansion = config.neck_expansion or 1.0
+
+ elif model_type == RTDETRModelType.hgnetv2_x:
+ backbone = PPHGNetV2.from_config("X")
+ neck_hidden_dim = config.neck_hidden_dim or 384
+ neck_dim_feedforward = config.neck_dim_feedforward or 2048
+ head_num_decoder_layers = config.head_num_decoder_layers or 6
+ neck_expansion = config.neck_expansion or 1.0
+
+ model = RTDETR(
+ backbone,
+ HybridEncoder(backbone.out_channels, neck_hidden_dim, neck_dim_feedforward, neck_expansion),
+ RTDETRHead(
+ config.num_classes,
+ config.head_hidden_dim,
+ config.head_num_queries,
+ [neck_hidden_dim] * 3,
+ head_num_decoder_layers,
+ ),
+ )
+
+ if config.checkpoint:
+ model.load_checkpoint(config.checkpoint)
+ return model
+
+ def forward(self, images: Tensor) -> dict[str, Tensor]:
+ """Detect objects in an image.
+
+ Args:
+ images: images to be detected. Shape :math:`(N, C, H, W)`.
+
+ Returns:
+ Dictionary with keys ``logits`` and ``boxes``. ``logits`` has shape :math:`(N, Q, K)` and ``boxes`` has
+ shape :math:`(N, Q, 4)`, where :math:`Q` is the number of queries, :math:`K` is the number of classes.
+ """
+ if self.training:
+ raise RuntimeError("Only evaluation mode is supported. Please call model.eval().")
+
+ fmaps = self.backbone(images)
+ fmaps = self.neck(fmaps)
+ logits, boxes = self.head(fmaps)
+ return dict(logits=logits, boxes=boxes)
diff --git a/kornia/contrib/models/rt_detr/post_processor.py b/kornia/contrib/models/rt_detr/post_processor.py
new file mode 100644
index 000000000..20ebf322e
--- /dev/null
+++ b/kornia/contrib/models/rt_detr/post_processor.py
@@ -0,0 +1,55 @@
+from __future__ import annotations
+
+from typing import Any
+
+from kornia.core import Module, Tensor, concatenate, tensor
+
+
+class DETRPostProcessor(Module):
+ def __init__(self, confidence_threshold: float) -> None:
+ super().__init__()
+ self.confidence_threshold = confidence_threshold
+
+ def forward(self, data: dict[str, Tensor], meta: dict[str, Any]) -> list[Tensor]:
+ """Post-process outputs from DETR.
+
+ Args:
+ data: dictionary with keys ``logits`` and ``boxes``. ``logits`` has shape :math:`(N, Q, K)` and
+ ``boxes`` has shape :math:`(N, Q, 4)`, where :math:`Q` is the number of queries, :math:`K`
+ is the number of classes.
+ meta: dictionary containing meta information. It must have key ``original_size``, which is the
+ original image size of input images. Each tuple represent (img_height, img_width).
+
+ Returns:
+ Processed detections. For each image, the detections have shape (D, 6), where D is the number of detections
+ in that image, 6 represent (class_id, confidence_score, x, y, w, h).
+ """
+ logits = data["logits"]
+ boxes = data["boxes"]
+ original_sizes = meta["original_size"]
+
+ # NOTE: boxes are not clipped to image dimensions
+
+ # https://github.com/PaddlePaddle/PaddleDetection/blob/5d1f888362241790000950e2b63115dc8d1c6019/ppdet/modeling/post_process.py#L446
+ # box format is cxcywh
+ # convert to xywh
+ # bboxes[..., :2] -= bboxes[..., 2:] * 0.5 # in-place operation is not torch.compile()-friendly
+ cxcy = boxes[..., :2]
+ wh = boxes[..., 2:]
+ boxes = concatenate([cxcy - wh * 0.5, wh], -1)
+
+ boxes = boxes * tensor(original_sizes, device=boxes.device, dtype=boxes.dtype).flip(1).repeat(1, 2).unsqueeze(1)
+ scores = logits.sigmoid() # RT-DETR was trained with focal loss. thus sigmoid is used instead of softmax
+
+ # the original code is slightly different
+ # it allows 1 bounding box to have multiple classes (multi-label)
+ scores, labels = scores.max(-1)
+ detections = []
+ for i in range(scores.shape[0]):
+ mask = scores[i] >= self.confidence_threshold
+ labels_i = labels[i, mask].unsqueeze(-1)
+ scores_i = scores[i, mask].unsqueeze(-1)
+ boxes_i = boxes[i, mask]
+ detections.append(concatenate([labels_i, scores_i, boxes_i], -1))
+
+ return detections
diff --git a/kornia/contrib/models/sam/architecture/mask_decoder.py b/kornia/contrib/models/sam/architecture/mask_decoder.py
index 1f731d5cd..38943f0ad 100644
--- a/kornia/contrib/models/sam/architecture/mask_decoder.py
+++ b/kornia/contrib/models/sam/architecture/mask_decoder.py
@@ -7,8 +7,8 @@ from __future__ import annotations
import torch
from torch import nn
-from torch.nn import functional as F
+from kornia.contrib.models.common import MLP
from kornia.contrib.models.sam.architecture.common import LayerNorm2d
from kornia.core import Module, Tensor, concatenate, stack
@@ -137,23 +137,3 @@ class MaskDecoder(Module):
iou_pred = self.iou_prediction_head(iou_token_out)
return masks, iou_pred
-
-
-# Lightly adapted from
-# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py
-class MLP(Module):
- def __init__(
- self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, sigmoid_output: bool = False
- ) -> None:
- super().__init__()
- self.num_layers = num_layers
- h = [hidden_dim] * (num_layers - 1)
- self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
- self.sigmoid_output = sigmoid_output
-
- def forward(self, x):
- for i, layer in enumerate(self.layers):
- x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
- if self.sigmoid_output:
- x = F.sigmoid(x)
- return x
diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.py
new file mode 100644
index 000000000..e15eabcd3
--- /dev/null
+++ b/kornia/contrib/object_detection.py
@@ -0,0 +1,86 @@
+from __future__ import annotations
+
+from typing import Any
+
+import torch
+import torch.nn.functional as F
+
+from kornia.core import Module, Tensor, concatenate
+
+
+class ResizePreProcessor(Module):
+ """This module resizes a list of image tensors to the given size, and also returns the original image sizes for
+ further post-processing."""
+
+ def __init__(self, size: int | tuple[int, int], interpolation_mode: str = "bilinear") -> None:
+ """
+ Args:
+ size: images will be resized to this value. If a 2-integer tuple is given, it is interpreted as
+ (height, width). If an integer is given, images will be resized to a square.
+ interpolation_mode: interpolation mode for image resizing. Supported values: ``nearest``, ``bilinear``,
+ ``bicubic``, ``area``, and ``nearest-exact``.
+ """
+ super().__init__()
+ self.size = size
+ self.interpolation_mode = interpolation_mode
+
+ def forward(self, imgs: list[Tensor]) -> tuple[Tensor, dict[str, Any]]:
+ # TODO: support other input formats e.g. file path, numpy
+ # NOTE: antialias=False is used in F.interpolate()
+ original_sizes = [(img.shape[1], img.shape[2]) for img in imgs]
+ resized_imgs = [F.interpolate(img.unsqueeze(0), self.size, mode=self.interpolation_mode) for img in imgs]
+ return concatenate(resized_imgs), dict(original_size=original_sizes)
+
+
+class ObjectDetector:
+ """This class wraps an object detection model and performs pre-processing and post-processing."""
+
+ def __init__(self, model: Module, pre_processor: Module, post_processor: Module) -> None:
+ """Construct an Object Detector object.
+
+ Args:
+ model: an object detection model.
+ pre_processor: a pre-processing module
+ post_processor: a post-processing module.
+ """
+ super().__init__()
+ self.model = model.eval()
+ self.pre_processor = pre_processor.eval()
+ self.post_processor = post_processor.eval()
+
+ @torch.inference_mode()
+ def predict(self, imgs: list[Tensor]) -> list[Tensor]:
+ """Detect objects in a given list of images.
+
+ Args:
+ imgs: list of RGB images. Each image is a Tensor with shape :math:`(3, H, W)`.
+
+ Returns:
+ list of detections found in each image. For item in a batch, shape is :math:`(D, 6)`, where :math:`D` is the
+ number of detections in the given image, :math:`6` represents class id, score, and `xywh` bounding box.
+ """
+ imgs, meta = self.pre_processor(imgs)
+ out = self.model(imgs)
+ detections = self.post_processor(out, meta)
+ return detections
+
+ def compile(
+ self,
+ *,
+ fullgraph: bool = False,
+ dynamic: bool = False,
+ backend: str = 'inductor',
+ mode: str | None = None,
+ options: dict[str, str | int | bool] | None = None,
+ disable: bool = False,
+ ) -> None:
+ """Compile the internal object detection model with :py:func:`torch.compile()`."""
+ self.model = torch.compile( # type: ignore
+ self.model,
+ fullgraph=fullgraph,
+ dynamic=dynamic,
+ backend=backend,
+ mode=mode,
+ options=options,
+ disable=disable,
+ )
diff --git a/test/contrib/models/test_rt_detr.py b/test/contrib/models/test_rt_detr.py
new file mode 100644
index 000000000..4357be503
--- /dev/null
+++ b/test/contrib/models/test_rt_detr.py
@@ -0,0 +1,136 @@
+from functools import partial
+
+import pytest
+import torch
+
+from kornia.contrib.models.rt_detr.architecture.hgnetv2 import PPHGNetV2
+from kornia.contrib.models.rt_detr.architecture.hybrid_encoder import HybridEncoder, RepVggBlock
+from kornia.contrib.models.rt_detr.architecture.resnet_d import ResNetD
+from kornia.contrib.models.rt_detr.architecture.rtdetr_head import RTDETRHead
+from kornia.contrib.models.rt_detr.model import RTDETR, RTDETRConfig
+from kornia.testing import BaseTester, assert_close
+from kornia.utils._compat import torch_version
+
+
+ 'backbone_factory',
+ (partial(ResNetD.from_config, 18), partial(ResNetD.from_config, 50), partial(PPHGNetV2.from_config, "L")),
+)
+def test_backbone(backbone_factory, device, dtype):
+ backbone = backbone_factory().to(device, dtype)
+ assert hasattr(backbone, "out_channels")
+ assert len(backbone.out_channels) == 3
+
+ N, C, H, W = 2, 3, 224, 256
+ imgs = torch.randn(N, C, H, W, device=device, dtype=dtype)
+ fmaps = backbone(imgs)
+
+ assert len(fmaps) == 3
+ downscale = 8
+ for fmap, ch in zip(fmaps, backbone.out_channels):
+ assert fmap.shape == (N, ch, H // downscale, W // downscale)
+ downscale *= 2
+
+
+def test_neck(device, dtype):
+ N = 2
+ in_channels = [64, 128, 256]
+ sizes = [(32, 24), (16, 12), (8, 6)]
+ hidden_dim = 64
+ neck = HybridEncoder(in_channels, hidden_dim, 128).to(device, dtype)
+ fmaps = [torch.randn(N, ch_in, h, w, device=device, dtype=dtype) for ch_in, (h, w) in zip(in_channels, sizes)]
+
+ outs = neck(fmaps)
+ assert len(outs) == len(fmaps)
+ for out, (h, w) in zip(outs, sizes):
+ assert out.shape == (N, hidden_dim, h, w)
+
+
+def test_head(device, dtype):
+ N = 2
+ in_channels = [32, 64, 128]
+ sizes = [(32, 24), (16, 12), (8, 6)]
+ num_classes = 5
+ num_queries = 10
+ decoder = RTDETRHead(num_classes, 32, num_queries, in_channels, 2).to(device, dtype).eval()
+ fmaps = [torch.randn(N, ch_in, h, w, device=device, dtype=dtype) for ch_in, (h, w) in zip(in_channels, sizes)]
+
+ logits, boxes = decoder(fmaps)
+ assert logits.shape == (N, num_queries, num_classes)
+ assert boxes.shape == (N, num_queries, 4)
+
+
+def test_regvgg_optimize_for_deployment(device, dtype):
+ module = RepVggBlock(64, 64).to(device, dtype).eval()
+ x = torch.randn(2, 64, 9, 9, device=device, dtype=dtype)
+
+ expected = module(x)
+ module.optimize_for_deployment()
+ actual = module(x)
+ assert_close(actual, expected)
+
+
+class TestRTDETR(BaseTester):
+ @pytest.mark.parametrize("variant", ("resnet18d", "resnet34d", "resnet50d", "resnet101d", "hgnetv2_l", "hgnetv2_x"))
+ def test_smoke(self, variant, device, dtype):
+ model = RTDETR.from_config(RTDETRConfig(variant, 10)).to(device, dtype).eval()
+ images = torch.randn(2, 3, 224, 256, device=device, dtype=dtype)
+ out = model(images)
+
+ assert isinstance(out, dict)
+ assert set(out.keys()) == set(["logits", "boxes"])
+
+ @pytest.mark.parametrize("shape", ((1, 3, 96, 128), (2, 3, 224, 256)))
+ def test_cardinality(self, shape, device, dtype):
+ num_classes = 10
+ num_queries = 10
+ config = RTDETRConfig("resnet50d", num_classes, head_num_queries=num_queries)
+ model = RTDETR.from_config(config).to(device, dtype).eval()
+
+ images = torch.randn(shape, device=device, dtype=dtype)
+ out = model(images)
+
+ assert out["logits"].shape == (shape[0], num_queries, num_classes)
+ assert out["boxes"].shape == (shape[0], num_queries, 4)
+
+ @pytest.mark.skip("Unnecessary")
+ def test_exception(self):
+ ...
+
+ @pytest.mark.skip("Unnecessary")
+ def test_gradcheck(self):
+ ...
+
+ @pytest.mark.skip("Unnecessary")
+ def test_module(self):
+ ...
+
+ @pytest.mark.skip("Needs more investigation")
+ @pytest.mark.parametrize("variant", ("resnet50d", "hgnetv2_l"))
+ def test_dynamo(self, variant, device, dtype, torch_optimizer):
+ # NOTE: This test passes on Mac M1 CPU, PyTorch 2.0.0,
+ # but fails on GitHub Actions Ubuntu-latest CPU, PyTorch 2.0.0.
+ # Perhaps random weights cause outputs to be much more different?
+ # Using pre-trained weights might see a smaller difference.
+ model = RTDETR.from_config(RTDETRConfig(variant, 10, head_num_queries=10)).to(device, dtype).eval()
+ model_optimized = torch_optimizer(model)
+
+ img = torch.rand(1, 3, 224, 256, device=device, dtype=dtype)
+ expected = model(img)
+ actual = model_optimized(img)
+
+ self.assert_close(actual, expected)
+
+ @pytest.mark.skipif(
+ torch_version() in ("2.0.0", "2.0.1"),
+ reason="aten::scaled_dot_product_attention cannot be exported to ONNX. See https://github.com/pytorch/pytorch/issues/97262",
+ ) # remove this once the fix is released to stable
+ @pytest.mark.skipif(not hasattr(torch.onnx, "symbolic_opset16"), reason="F.grid_sample() requires ONNX opset 16")
+ @pytest.mark.parametrize("variant", ("resnet50d", "hgnetv2_l"))
+ def test_onnx(self, variant, tmp_path, dtype):
+ # NOTE: correctness check is not included
+ model = RTDETR.from_config(RTDETRConfig(variant, 80)).to(dtype).eval()
+ img = torch.rand(1, 3, 224, 256, dtype=dtype)
+ onnx_path = str(tmp_path / "rtdetr.onnx")
+
+ torch.onnx.export(model, img, onnx_path, opset_version=16)
diff --git a/test/contrib/test_contrib.py b/test/contrib/test_contrib.py
index cfc275e34..cdf4a15c7 100644
--- a/test/contrib/test_contrib.py
+++ b/test/contrib/test_contrib.py
@@ -7,6 +7,7 @@ from torch.autograd import gradcheck
import kornia
import kornia.testing as utils # test utils
from kornia.contrib.face_detection import FaceKeypoint
+from kornia.contrib.models.rt_detr import RTDETR, DETRPostProcessor, RTDETRConfig
from kornia.testing import assert_close
@@ -731,3 +732,24 @@ class TestEdgeDetector:
op = kornia.contrib.EdgeDetector().to(device, dtype)
op_jit = torch.jit.script(op)
assert op_jit is not None
+
+
+class TestObjectDetector:
+ def test_smoke(self, device, dtype):
+ batch_size = 3
+ confidence = 0.3
+ config = RTDETRConfig("resnet50d", 10, head_num_queries=10)
+ model = RTDETR.from_config(config).to(device, dtype).eval()
+ pre_processor = kornia.contrib.object_detection.ResizePreProcessor(32)
+ post_processor = DETRPostProcessor(confidence).to(device, dtype).eval()
+ detector = kornia.contrib.ObjectDetector(model, pre_processor, post_processor)
+
+ sizes = torch.randint(5, 10, (batch_size, 2)) * 32
+ imgs = [torch.randn(3, h, w, device=device, dtype=dtype) for h, w in sizes]
+ detections = detector.predict(imgs)
+
+ assert len(detections) == batch_size
+ for dets in detections:
+ assert dets.shape[1] == 6
+ assert torch.all(dets[:, 0].int() == dets[:, 0])
+ assert torch.all(dets[:, 1] >= 0.3)