π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[feature] rt-detr onnx (#2548)
Edgar Ribacbea73649b64
diff --git a/docs/source/contrib.rst b/docs/source/contrib.rstindex 12d58bafa..f4dbd1062 100644--- a/docs/source/contrib.rst+++ b/docs/source/contrib.rst@@ -60,11 +60,30 @@ Visit the `Kornia face detection demo on the Hugging Face SpacesObject Detection-----------------.. autoclass:: ObjectDetector+.. autoclass:: kornia.contrib.object_detection.BoundingBoxDataFormat+ :members:+ :undoc-members:+ :member-order: bysource++.. autoclass:: kornia.contrib.object_detection.BoundingBox+ :members:+ :undoc-members:++.. autoclass:: kornia.contrib.object_detection.ObjectDetectorResult+ :members:+ :undoc-members:++.. autoclass:: kornia.contrib.object_detection.ObjectDetector:members::undoc-members::special-members: __init__,+.. autoclass:: kornia.contrib.object_detection.ResizePreProcessor+ :members:+ :undoc-members:++.. autofunction:: kornia.contrib.object_detection.results_from_detections+Real-Time Detection Transformer (RT-DETR)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^diff --git a/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py b/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.pyindex e9f1a5856..b88be95ee 100644--- a/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py+++ b/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py@@ -92,7 +92,9 @@ class AIFI(Module):# NOTE: cache pos_emb as bufferpos_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]))++ attn, _ = self.self_attn(q, k, x, need_weights=True)+ x = self.norm1(x + self.dropout1(attn))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)@@ -128,7 +130,7 @@ class AIFI(Module):"""xs = torch.arange(w, device=device, dtype=dtype)ys = torch.arange(h, device=device, dtype=dtype)- grid_x, grid_y = torch.meshgrid(xs, ys)+ grid_x, grid_y = torch.meshgrid(xs, ys, indexing="ij")pos_dim = embed_dim // 4omega = torch.arange(pos_dim, device=device, dtype=dtype) / pos_dim@@ -189,7 +191,7 @@ class HybridEncoder(Module):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+ projected_maps = [proj(fmap) for proj, fmap in zip(self.input_proj, fmaps)]+ projected_maps[-1] = self.aifi(projected_maps[-1])+ new_fmaps = self.ccfm(projected_maps)+ return new_fmapsdiff --git a/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py b/kornia/contrib/models/rt_detr/architecture/rtdetr_head.pyindex c9001da14..f2cda4cb0 100644--- a/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py+++ b/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py@@ -1,21 +1,80 @@-"""Based on code from-https://github.com/PaddlePaddle/PaddleDetection/blob/ec37e66685f3bc5a38cd13f60685acea175922e1/-ppdet/modeling/transformers/rtdetr_transformer.py."""+# Based on code from:+# https://github.com/lyuwenyu/RT-DETR/blob/8a1b85a91f527bed0c4e2424a7a6b4bcdd200fb1/rtdetr_pytorch/src/zoo/rtdetr/rtdetr_decoder.pyfrom __future__ import annotationsimport torch-import torch.nn.functional as Ffrom torch import nnfrom kornia.contrib.models.common import MLP, ConvNormActfrom kornia.core import Module, Tensor, concatenate-from kornia.utils import create_meshgrid+++def _inverse_sigmoid(x: torch.Tensor, eps: float = 1e-5) -> torch.Tensor:+ """Inverse sigmoid function.++ Args:+ x: input tensor+ eps: epsilon value for numerical stability++ Returns:+ output tensor+ """+ out = x.clip(min=0.0, max=1.0)+ return torch.log(out.clip(min=eps) / (1.0 - out).clip(min=eps))+++def _deformable_attention_kernel(+ value: Tensor, value_spatial_shapes: list[tuple[int, int]], sampling_locations: Tensor, attention_weights: Tensor+) -> Tensor:+ """Deformable Attention Kernel used in Deformable DETR.++ Described in https://arxiv.org/abs/2010.04159.++ Args:+ value: shape (N, Lv, n_head * C)+ value_spatial_shapes: [(H0, W0), (H1, W1), ...]+ sampling_locations: shape (N, Lq, n_head, n_levels, n_points, 2)+ attention_weights: shape (N, Lq, n_head, n_levels, n_points)++ Returns:+ output, shape (N, Lq, n_head * C)+ """+ bs, _, n_head, c = value.shape+ _, Len_q, _, n_levels, n_points, _ = sampling_locations.shape++ split_shape: list[int] = [h * w for h, w in value_spatial_shapes]+ value_list = value.split(split_shape, dim=1)+ sampling_grids = 2 * sampling_locations - 1++ sampling_value_list: list[Tensor] = []+ for level, (h, w) in enumerate(value_spatial_shapes):+ # N_, H_*W_, M_, D_ -> N_, H_*W_, M_*D_ -> N_, M_*D_, H_*W_ -> N_*M_, D_, H_, W_+ value_l_ = value_list[level].flatten(2).permute(0, 2, 1).reshape(bs * n_head, c, h, w)+ # N_, Lq_, M_, P_, 2 -> N_, M_, Lq_, P_, 2 -> N_*M_, Lq_, P_, 2+ sampling_grid_l_ = sampling_grids[:, :, :, level].permute(0, 2, 1, 3, 4).flatten(0, 1)+ # N_*M_, D_, Lq_, P_+ sampling_value_l_ = torch.nn.functional.grid_sample(+ value_l_, sampling_grid_l_, mode='bilinear', padding_mode='zeros', align_corners=False+ )+ sampling_value_list.append(sampling_value_l_)++ # (N_, Lq_, M_, L_, P_) -> (N_, M_, Lq_, L_, P_) -> (N_*M_, 1, Lq_, L_*P_)+ attention_weights = attention_weights.permute(0, 2, 1, 3, 4).reshape(bs * n_head, 1, Len_q, n_levels * n_points)+ output = (+ (torch.stack(sampling_value_list, dim=-2).flatten(-2) * attention_weights)+ .sum(-1)+ .reshape(bs, n_head * c, Len_q)+ )++ return output.permute(0, 2, 1)class MultiScaleDeformableAttention(Module):- """Multi-scale Deformable Attention used in Deformable DETR, as described in- https://arxiv.org/abs/2010.04159."""+ """Multi-scale Deformable Attention used in Deformable DETR.++ 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__()@@ -24,106 +83,180 @@ class MultiScaleDeformableAttention(Module):self.num_points = num_pointsself.total_points = num_heads * num_levels * num_points+ self.head_dim = embed_dim // num_heads+ # KORNIA_CHECK not working with onnx+ # assert self.head_dim * num_heads == embed_dim, "embed_dim must be divisible by num_heads"+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]]+ self, query: Tensor, reference_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)+ reference_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."""+ N, Lenq, _ = query.shape+ _, Len_v, _ = value.shape- def __init__(- self, embed_dim: int, num_levels: int, num_heads: int = 8, num_points: int = 4, dropout: float = 0.0- ) -> None:+ sampling_offsets = self.sampling_offsets(query).reshape(+ N, Lenq, self.num_heads, self.num_levels, self.num_points, 2+ )+ attention_weights = self.attention_weights(query).reshape(+ N, Lenq, self.num_heads, self.num_levels * self.num_points+ )+ attention_weights = attention_weights.softmax(-1).reshape(+ N, Lenq, self.num_heads, self.num_levels, self.num_points+ )++ # prepare the spatial sampling grid+ reference_points_cxcy = reference_points[:, :, None, :, None, :2]+ reference_points_wh = reference_points[:, :, None, :, None, 2:]+ sampling_locations = reference_points_cxcy + sampling_offsets / self.num_points * reference_points_wh * 0.5++ value_buf = self.value_proj(value).reshape(N, Len_v, self.num_heads, self.head_dim)++ out = _deformable_attention_kernel(value_buf, value_spatial_shapes, sampling_locations, attention_weights)++ # final projection+ out = self.output_proj(out)++ return out+++class TransformerDecoderLayer(Module):+ """Deformable Transformer Decoder layer used in Deformable DETR.++ Described in: https://arxiv.org/abs/2010.04159.+ """++ def __init__(self, embed_dim: int, num_heads: int, dropout: float, num_levels: int, num_points: int) -> None:super().__init__()+ # self attnself.self_attn = nn.MultiheadAttention(embed_dim, num_heads, dropout, batch_first=True)self.dropout1 = nn.Dropout(dropout)self.norm1 = nn.LayerNorm(embed_dim)+ # cross attnself.cross_attn = MultiScaleDeformableAttention(embed_dim, num_heads, num_levels, num_points)self.dropout2 = nn.Dropout(dropout)self.norm2 = nn.LayerNorm(embed_dim)+ # ffnself.linear1 = nn.Linear(embed_dim, embed_dim * 4)- self.act = nn.ReLU(inplace=True)+ self.activation = 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 _ffn(self, x: Tensor) -> Tensor:+ return self.linear2(self.dropout3(self.activation(self.linear1(x))))+def forward(self,tgt: Tensor,ref_points: Tensor,memory: Tensor,memory_spatial_shapes: list[tuple[int, int]],- query_pos_embed: Tensor,+ memory_level_start_index: list[int] | None = None,+ attn_mask: Tensor | None = None,+ memory_mask: Tensor | None = None,+ query_pos_embed: Tensor | None = None,) -> Tensor:+ # TODO: rename variables because is confusing+ # self attentionq = k = tgt + query_pos_embed- out, _ = self.self_attn(q, k, tgt, need_weights=False)+ out, _ = self.self_attn(q, k, value=tgt)tgt = self.norm1(tgt + self.dropout1(out))+ # cross attentionout = 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)))+ # ffn+ out = self.norm3(tgt + self.dropout4(self._ffn(tgt)))++ return out- def ffn(self, x: Tensor) -> Tensor:- return self.linear2(self.dropout3(self.act(self.linear1(x))))++class TransformerDecoder:+ def __init__(self, hidden_dim: int, decoder_layers: nn.ModuleList, num_layers: int, eval_idx: int = -1) -> None:+ super().__init__()+ self.layers = decoder_layers+ # TODO: come back to this later+ # self.layers = nn.ModuleList([+ # copy.deepcopy(decoder_layer) for _ in range(num_layers)+ # ])+ self.hidden_dim = hidden_dim+ self.num_layers = num_layers+ self.eval_idx = eval_idx if eval_idx >= 0 else num_layers + eval_idx++ def forward(+ self,+ tgt: Tensor,+ ref_points_unact: Tensor,+ memory: Tensor,+ memory_spatial_shapes: list[tuple[int, int]],+ memory_level_start_index: list[int],+ bbox_head: nn.ModuleList,+ score_head: nn.ModuleList,+ query_pos_head: nn.Module,+ attn_mask: Tensor | None = None,+ memory_mask: Tensor | None = None,+ ) -> tuple[Tensor, Tensor]:+ output: Tensor = tgt+ dec_out_bboxes: list[Tensor] = []+ dec_out_logits: list[Tensor] = []+ ref_points_detach = torch.sigmoid(ref_points_unact)++ for i, layer in enumerate(self.layers):+ ref_points_input = ref_points_detach.unsqueeze(2)+ query_pos_embed: Tensor = query_pos_head(ref_points_detach)++ output = layer(+ output,+ ref_points_input,+ memory,+ memory_spatial_shapes,+ memory_level_start_index,+ attn_mask,+ memory_mask,+ query_pos_embed,+ )++ inter_ref_bbox = torch.sigmoid(bbox_head[i](output) + _inverse_sigmoid(ref_points_detach))++ # TODO: will be supported later+ # if self.training:+ # dec_out_logits.append(score_head[i](output))+ # if i == 0:+ # dec_out_bboxes.append(inter_ref_bbox)+ # else:+ # dec_out_bboxes.append(torch.sigmoid(bbox_head[i](output) + _inverse_sigmoid(ref_points)))+ # elif i == self.eval_idx:+ # dec_out_logits.append(score_head[i](output))+ # dec_out_bboxes.append(inter_ref_bbox)+ # break+ if i == self.eval_idx:+ dec_out_logits.append(score_head[i](output))+ dec_out_bboxes.append(inter_ref_bbox)+ break++ # ref_points_detach = inter_ref_bbox.detach(+ # ) if self.training else inter_ref_bbox+ ref_points_detach = inter_ref_bbox++ return torch.stack(dec_out_bboxes), torch.stack(dec_out_logits)class RTDETRHead(Module):@@ -136,75 +269,162 @@ class RTDETRHead(Module):num_decoder_layers: int,num_heads: int = 8,num_decoder_points: int = 4,+ # num_levels: int = 3,+ dropout: float = 0.0,) -> None:super().__init__()self.num_queries = num_queries+ # TODO: verify this is correct+ self.num_levels = len(in_channels)++ # build the input projection layersself.input_proj = nn.ModuleList()for ch_in in in_channels:self.input_proj.append(ConvNormAct(ch_in, hidden_dim, 1, act="none"))+ # NOTE: might be missing some layers here ?+ # https://github.com/lyuwenyu/RT-DETR/blob/main/rtdetr_pytorch/src/zoo/rtdetr/rtdetr_decoder.py#L403-L410++ # NOTE: need to be integrated with the TransformerDecoderLayer+ self.decoder_layers = nn.ModuleList(+ [+ TransformerDecoderLayer(+ embed_dim=hidden_dim,+ num_heads=num_heads,+ dropout=dropout,+ num_levels=len(in_channels),+ num_points=num_decoder_points,+ )+ for _ in range(num_decoder_layers)+ ]+ )++ self.decoder = TransformerDecoder(+ hidden_dim=hidden_dim, decoder_layers=self.decoder_layers, num_layers=num_decoder_layers+ )++ # denoising part+ self.denoising_class_embed = nn.Embedding(num_classes, hidden_dim) # not used in evaluation+ # decoder embedding+ self.query_pos_head = MLP(4, 2 * hidden_dim, hidden_dim, num_layers=2)++ # encoder headself.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.enc_bbox_head = MLP(hidden_dim, hidden_dim, 4, num_layers=3)++ # decoder head+ self.dec_score_head = nn.ModuleList([nn.Linear(hidden_dim, num_classes) for _ in range(num_decoder_layers)])+ self.dec_bbox_head = nn.ModuleList(+ [MLP(hidden_dim, hidden_dim, 4, num_layers=3) for _ in range(num_decoder_layers)]+ )++ def forward(self, feats: Tensor) -> tuple[Tensor, Tensor]:+ # input projection and embedding+ memory, spatial_shapes, level_start_index = self._get_encoder_input(feats)++ # prepare denoising training+ denoising_class, denoising_bbox_unact, attn_mask = None, None, None++ target, init_ref_points_unact, enc_topk_bboxes, enc_topk_logits = self._get_decoder_input(+ memory, spatial_shapes, denoising_class, denoising_bbox_unact+ )++ # decoder+ out_bboxes, out_logits = self.decoder.forward(+ target,+ init_ref_points_unact,+ memory,+ spatial_shapes,+ level_start_index,+ self.dec_bbox_head,+ self.dec_score_head,+ self.query_pos_head,+ attn_mask=attn_mask,+ )++ return out_logits[-1], out_bboxes[-1]++ def _get_encoder_input(self, feats: Tensor) -> tuple[Tensor, list[tuple[int, int]], list[int]]:+ # get projection features+ proj_feats: list[Tensor] = [self.input_proj[i](feat) for i, feat in enumerate(feats)]++ if self.num_levels > len(proj_feats):+ len_srcs = len(proj_feats)+ for i in range(len_srcs, self.num_levels):+ if i == len_srcs:+ proj_feats.append(self.input_proj[i](feats[-1]))+ else:+ proj_feats.append(self.input_proj[i](proj_feats[-1]))++ # get encoder inputs+ feat_flatten_list: list[Tensor] = []+ spatial_shapes: list[tuple[int, int]] = []+ level_start_index: list[int] = [0]++ for i, feat in enumerate(proj_feats):+ _, _, h, w = feat.shape+ # [b, c, h, w] -> [b, h*w, c]+ feat_flatten_list.append(feat.flatten(2).permute(0, 2, 1))+ # [num_levels, 2]+ spatial_shapes.append((h, w))+ # [l], start index of each level+ level_start_index.append(h * w + level_start_index[-1])++ # [b, l, c]+ feat_flatten: Tensor = torch.concat(feat_flatten_list, 1)++ level_start_index.pop()+ return feat_flatten, spatial_shapes, level_start_index++ def _get_decoder_input(+ self,+ memory: Tensor,+ spatial_shapes: list[tuple[int, int]],+ denoising_class: Tensor | None = None,+ denoising_bbox_unact: Tensor | None = None,+ ) -> tuple[Tensor, Tensor, Tensor, Tensor]:+ # prepare input for decoder+ # TODO: cache anchors and valid_mask as buffers+ anchors, valid_mask = self._generate_anchors(spatial_shapes, device=memory.device, dtype=memory.dtype)- 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)+ # memory = torch.where(valid_mask, memory, 0)+ memory = valid_mask.to(memory) * memory # TODO fix type error for onnx export- 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))+ output_memory = self.enc_output(memory)- 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().")+ enc_outputs_class = self.enc_score_head(output_memory)+ enc_outputs_coord_unact = self.enc_bbox_head(output_memory) + anchors- 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]+ _, topk_ind = torch.topk(enc_outputs_class.max(-1).values, self.num_queries, dim=1)- 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+ reference_points_unact = enc_outputs_coord_unact.gather(+ dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, enc_outputs_coord_unact.shape[-1])+ )- # TODO: cache anchors and valid_mask as buffers- anchors, valid_mask = self.generate_anchors(spatial_shapes, device=memory.device, dtype=memory.dtype)+ enc_topk_bboxes = torch.sigmoid(reference_points_unact)+ if denoising_bbox_unact is not None:+ reference_points_unact = torch.concat([denoising_bbox_unact, reference_points_unact], 1)- # 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_topk_logits = enc_outputs_class.gather(+ dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, enc_outputs_class.shape[-1])+ )- enc_out_logits = self.enc_score_head(out_memory)- enc_out_bboxes = anchors + self.enc_bbox_head(out_memory)+ # extract region features+ target = output_memory.gather(dim=1, index=topk_ind.unsqueeze(-1).repeat(1, 1, output_memory.shape[-1]))- # 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]+ if denoising_class is not None:+ target = torch.concat([denoising_class, target], 1)- # 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()+ return target.detach(), reference_points_unact.detach(), enc_topk_bboxes, enc_topk_logits@staticmethod- def generate_anchors(+ 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,+ dtype: torch.dtype | None = None,) -> tuple[Tensor, Tensor]:"""Generate anchors for RT-DETR.@@ -219,18 +439,31 @@ class RTDETRHead(Module):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_list: list[Tensor] = []++ for i, (h, w) in enumerate(spatial_shapes):+ # TODO: fix later kornia.utils.create_meshgrid()+ grid_y, grid_x = torch.meshgrid(+ torch.arange(h, device=device, dtype=dtype), torch.arange(w, device=device, dtype=dtype), indexing="ij"+ )+ grid_xy = torch.stack([grid_x, grid_y], -1) # HxWx2++ # this satisfies onnx export+ wh = torch.empty(2, device=device, dtype=dtype)+ wh[0] = w+ wh[1] = h++ grid_xy = (grid_xy + 0.5) / wh # normalize to [0, 1]+ grid_wh = torch.ones_like(grid_xy) * grid_size * (2.0**i)+ anchors_list.append(concatenate([grid_xy, grid_wh], -1).reshape(-1, h * w, 4))anchors = concatenate(anchors_list, 1)- valid_mask = ((anchors > eps) & (anchors < 1 - eps)).all(-1, keepdim=True)+ 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)+ inf_t = torch.empty(1, device=device, dtype=dtype)+ inf_t[0] = torch.inf++ anchors = torch.where(valid_mask, anchors, inf_t)+return anchors, valid_maskdiff --git a/kornia/contrib/models/rt_detr/model.py b/kornia/contrib/models/rt_detr/model.pyindex d9d382f78..c64154af9 100644--- a/kornia/contrib/models/rt_detr/model.py+++ b/kornia/contrib/models/rt_detr/model.py@@ -143,11 +143,11 @@ class RTDETR(ModelBase[RTDETRConfig]):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,+ num_classes=config.num_classes,+ hidden_dim=config.head_hidden_dim,+ num_queries=config.head_num_queries,+ in_channels=[neck_hidden_dim] * 3,+ num_decoder_layers=head_num_decoder_layers,),)@@ -155,20 +155,21 @@ class RTDETR(ModelBase[RTDETRConfig]):model.load_checkpoint(config.checkpoint)return model- def forward(self, images: Tensor) -> dict[str, Tensor]:+ def forward(self, images: Tensor) -> tuple[Tensor, 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.+ - **logits** - Tensor of shape :math:`(N, Q, K)`, where :math:`Q` is the number of queries,+ :math:`K` is the number of classes.+ - **boxes** - Tensor of shape :math:`(N, Q, 4)`, where :math:`Q` is the number of queries."""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 {"logits": logits, "boxes": boxes}+ feats = self.backbone(images)+ feats_buf = self.neck(feats)+ logits, boxes = self.head(feats_buf)+ return logits, boxesdiff --git a/kornia/contrib/models/rt_detr/post_processor.py b/kornia/contrib/models/rt_detr/post_processor.pyindex 20ebf322e..d5fce8387 100644--- a/kornia/contrib/models/rt_detr/post_processor.py+++ b/kornia/contrib/models/rt_detr/post_processor.py@@ -1,8 +1,10 @@from __future__ import annotations-from typing import Any+# TODO:+import torch-from kornia.core import Module, Tensor, concatenate, tensor+from kornia.core import Module, Tensor, concatenate+from kornia.image.base import ImageSizeclass DETRPostProcessor(Module):@@ -10,46 +12,49 @@ class DETRPostProcessor(Module):super().__init__()self.confidence_threshold = confidence_threshold- def forward(self, data: dict[str, Tensor], meta: dict[str, Any]) -> list[Tensor]:+ def forward(self, logits: Tensor, boxes: Tensor, original_sizes: list[ImageSize]) -> 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).+ logits: tensor with shape :math:`(N, Q, K)`, where :math:`N` is the batch size, :math:`Q` is the number of+ queries, :math:`K` is the number of classes.+ boxes: tensor with shape :math:`(N, Q, 4)`, where :math:`N` is the batch size, :math:`Q` is the number of+ queries.+ original_sizes: list of tuples, 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 detectionsin 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+ # NOTE: consider using kornia BoundingBox+ # NOTE: consider having a separate function to convert the detections to a list of bounding boxes# 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)+ # TODO: replace using kornia BoundingBox+ cxcy, wh = boxes[..., :2], boxes[..., 2:]+ boxes_xy = concatenate([cxcy - wh * 0.5, wh], -1)++ sizes_wh = torch.empty(1, 1, 2, device=boxes.device, dtype=boxes.dtype)+ sizes_wh[..., 0] = original_sizes[0].width+ sizes_wh[..., 1] = original_sizes[0].height+ sizes_wh = sizes_wh.repeat(1, 1, 2)- boxes = boxes * tensor(original_sizes, device=boxes.device, dtype=boxes.dtype).flip(1).repeat(1, 2).unsqueeze(1)+ boxes_xy = boxes_xy * sizes_whscores = 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 = []++ detections: list[Tensor] = []for i in range(scores.shape[0]):mask = scores[i] >= self.confidence_thresholdlabels_i = labels[i, mask].unsqueeze(-1)scores_i = scores[i, mask].unsqueeze(-1)- boxes_i = boxes[i, mask]+ boxes_i = boxes_xy[i, mask]detections.append(concatenate([labels_i, scores_i, boxes_i], -1))return detectionsdiff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.pyindex c9a4ff279..55821b98a 100644--- a/kornia/contrib/object_detection.py+++ b/kornia/contrib/object_detection.py@@ -1,16 +1,104 @@from __future__ import annotations-from typing import Any+from dataclasses import dataclass+from enum import Enumimport torchfrom kornia.core import Module, Tensor, concatenate-from kornia.geometry.transform import Resize+from kornia.core.check import KORNIA_CHECK_SHAPE+from kornia.image.base import ImageSize++__all__ = [+ "BoundingBoxDataFormat",+ "BoundingBox",+ "results_from_detections",+ "ResizePreProcessor",+ "ObjectDetector",+ "ObjectDetectorResult",+]+++class BoundingBoxDataFormat(Enum):+ """Enum class that maps bounding box data format."""++ XYWH = 0+ XYXY = 1+ CXCYWH = 2+ CENTER_XYWH = 2+++# NOTE: probably we should use a more generic name like BoundingBox2D+# and add a BoundingBox3D class for 3D bounding boxes. Also for serialization+# we should have an explicit class for each format to make it more production ready+# specially to serialize to protobuf and not saturate at a high rates.+++@dataclass(frozen=True)+class BoundingBox:+ """Bounding box data class.++ Useful for representing bounding boxes in different formats for object detection.++ Args:+ data: tuple of bounding box data. The length of the tuple depends on the data format.+ data_format: bounding box data format.+ """++ data: tuple[float, float, float, float]+ data_format: BoundingBoxDataFormat+++@dataclass(frozen=True)+class ObjectDetectorResult:+ """Object detection result.++ Args:+ class_id: class id of the detected object.+ confidence: confidence score of the detected object.+ bbox: bounding box of the detected object in xywh format.+ """++ class_id: int+ confidence: float+ bbox: BoundingBox+++def results_from_detections(detections: Tensor, format: str | BoundingBoxDataFormat) -> list[ObjectDetectorResult]:+ """Convert a detection tensor to a list of :py:class:`ObjectDetectorResult`.++ Args:+ detections: tensor with shape :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.++ Returns:+ list of :py:class:`ObjectDetectorResult`.+ """+ KORNIA_CHECK_SHAPE(detections, ["D", "6"])++ if isinstance(format, str):+ format = BoundingBoxDataFormat[format.upper()]++ results: list[ObjectDetectorResult] = []+ for det in detections:+ det = det.squeeze().tolist()+ if len(det) != 6:+ continue+ results.append(+ ObjectDetectorResult(+ class_id=int(det[0]),+ confidence=det[1],+ bbox=BoundingBox(data=(det[2], det[3], det[4], det[5]), data_format=format),+ )+ )+ return resultsclass 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."""+ """This module resizes a list of image tensors to the given size.++ Additionally, also returns the original image sizes for further post-processing.+ """def __init__(self, size: tuple[int, int], interpolation_mode: str = "bilinear") -> None:"""@@ -22,17 +110,24 @@ class ResizePreProcessor(Module):"""super().__init__()self.size = size- self.resizer = Resize(self.size, interpolation=interpolation_mode)+ self.interpolation_mode = interpolation_mode- def forward(self, imgs: list[Tensor]) -> tuple[Tensor, dict[str, Any]]:+ def forward(self, imgs: list[Tensor]) -> tuple[Tensor, list[ImageSize]]:# 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 = [self.resizer(img.unsqueeze(0)) for img in imgs]- return concatenate(resized_imgs), {"original_size": original_sizes}+ resized_imgs, original_sizes = [], []+ for i in range(len(imgs)):+ img = imgs[i]+ # NOTE: assume that image layout is CHW+ original_sizes.append(ImageSize(height=img.shape[1], width=img.shape[2]))+ resized_imgs.append(+ # TODO: fix kornia resize to support onnx+ torch.nn.functional.interpolate(img.unsqueeze(0), size=self.size, mode=self.interpolation_mode)+ )+ return concatenate(resized_imgs), original_sizes-class ObjectDetector:+# TODO: move this to kornia.models as AlgorithmicModel api+class ObjectDetector(Module):"""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:@@ -49,19 +144,19 @@ class ObjectDetector:self.post_processor = post_processor.eval()@torch.inference_mode()- def predict(self, imgs: list[Tensor]) -> list[Tensor]:+ def forward(self, images: 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)`.+ images: 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 thenumber 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)+ images, images_sizes = self.pre_processor(images)+ logits, boxes = self.model(images)+ detections = self.post_processor(logits, boxes, images_sizes)return detectionsdef compile(diff --git a/kornia/utils/image.py b/kornia/utils/image.pyindex 282e05753..e0e3b0ad5 100644--- a/kornia/utils/image.py+++ b/kornia/utils/image.py@@ -218,7 +218,7 @@ def perform_keep_shape_image(f: Callable[..., Tensor]) -> Callable[..., Tensor]:if not isinstance(input, Tensor):raise TypeError(f"Input input type is not a Tensor. Got {type(input)}")- if input.numel() == 0:+ if len(input.shape) == 0:raise ValueError("Invalid input tensor, it is empty.")input_shape = input.shapediff --git a/test/contrib/models/test_rt_detr.py b/test/contrib/models/test_rt_detr.pyindex 975acb5de..3d4fc8450 100644--- a/test/contrib/models/test_rt_detr.py+++ b/test/contrib/models/test_rt_detr.py@@ -77,8 +77,8 @@ class TestRTDETR(BaseTester):images = torch.randn(2, 3, 224, 256, device=device, dtype=dtype)out = model(images)- assert isinstance(out, dict)- assert set(out.keys()) == {"logits", "boxes"}+ assert isinstance(out, tuple)+ assert len(out) == 2@pytest.mark.parametrize("shape", ((1, 3, 96, 128), (2, 3, 224, 256)))def test_cardinality(self, shape, device, dtype):@@ -88,10 +88,10 @@ class TestRTDETR(BaseTester):model = RTDETR.from_config(config).to(device, dtype).eval()images = torch.randn(shape, device=device, dtype=dtype)- out = model(images)+ logits, boxes = model(images)- assert out["logits"].shape == (shape[0], num_queries, num_classes)- assert out["boxes"].shape == (shape[0], num_queries, 4)+ assert logits.shape == (shape[0], num_queries, num_classes)+ assert boxes.shape == (shape[0], num_queries, 4)@pytest.mark.skip("Unnecessary")def test_exception(self):diff --git a/test/contrib/test_contrib.py b/test/contrib/test_contrib.pyindex 018bc5cb4..0be010abc 100644--- a/test/contrib/test_contrib.py+++ b/test/contrib/test_contrib.py@@ -1,3 +1,4 @@+from pathlib import Pathfrom unittest.mock import PropertyMock, patchimport pytest@@ -750,7 +751,7 @@ class TestObjectDetector:sizes = torch.randint(5, 10, (batch_size, 2)) * 32imgs = [torch.randn(3, h, w, device=device, dtype=dtype) for h, w in sizes]pre_processor_out = pre_processor(imgs)- detections = detector.predict(imgs)+ detections = detector(imgs)assert pre_processor_out[0].shape[-1] == 32assert pre_processor_out[0].shape[-2] == 32@@ -759,3 +760,48 @@ class TestObjectDetector:assert dets.shape[1] == 6assert torch.all(dets[:, 0].int() == dets[:, 0])assert torch.all(dets[:, 1] >= 0.3)++ def test_onnx(self, tmp_path: Path):+ config = RTDETRConfig("resnet18d", 80)+ model = RTDETR.from_config(config)+ pre_processor = kornia.contrib.object_detection.ResizePreProcessor(640)+ post_processor = DETRPostProcessor(0.3)+ detector = kornia.contrib.ObjectDetector(model, pre_processor, post_processor)++ data = torch.rand(3, 400, 640)++ model_path = tmp_path / "rtdetr.onnx"++ dynamic_axes = {"images": {0: "N"}}+ torch.onnx.export(+ detector,+ [data],+ model_path,+ input_names=["images"],+ output_names=["detections"],+ dynamic_axes=dynamic_axes,+ opset_version=16,+ )++ assert model_path.is_file()++ def test_results_from_detections(self, device, dtype):+ # label_id, confidence, data+ detections = torch.tensor(+ [+ [0, 0.9, 0.0, 0.0, 1.0, 1.0],+ [1, 0.8, 0.0, 0.0, 1.0, 1.0],+ [2, 0.7, 0.0, 0.0, 1.0, 1.0],+ [3, 0.6, 0.0, 0.0, 1.0, 1.0],+ [4, 0.5, 0.0, 0.0, 1.0, 1.0],+ ],+ device=device,+ dtype=dtype,+ )++ detector_results: list = kornia.contrib.object_detection.results_from_detections(detections, format="xywh")++ assert len(detector_results) == 5+ for j, det in enumerate(detector_results):+ for i in range(4):+ assert det.bbox.data[i] == float(detections[j, i + 2])