Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(models): per-image DETR boxes, RT-DETR builder flag, odd sizes and r50vd_m depth, int64 processor sizes, PIL output (#6035)

Dmytro Mishkin7fab26733c33
diff --git a/changelog.d/6035.fixed.md b/changelog.d/6035.fixed.md
new file mode 100644
index 000000000..6b2c9d790
--- /dev/null
+++ b/changelog.d/6035.fixed.md
@@ -0,0 +1,11 @@
+Detection, processor and super-resolution wrappers of `kornia.models` and `kornia.contrib` return correct results:
+
+- `DETRPostProcessor` scales each image's boxes by that image's own row of `original_sizes`. It used the first image's size for the whole batch: with sizes `[[100, 200], [400, 800]]` (H, W), the normalised box `(0.5, 0.5, 0.25, 0.25)` of image 1 came back as `[75, 37.5, 50, 25]` (xywh) instead of `[300, 150, 200, 100]`, so `ObjectDetector` on images of different sizes misplaced the boxes of every image but the first. The boxes also keep their own dtype when the sizes have another one.
+- `RTDETRDetectorBuilder.build(confidence_filtering=False)` builds a post-processor that does not filter and returns the `(B, Q, 6)` tensor; the flag was ignored and the detections were filtered into a list. `None`, the default, still filters.
+- `ResNetD` runs on inputs that give an odd feature map, such as 636 x 636, which raised `RuntimeError: The size of tensor a (80) must match the size of tensor b (79)`: the stride-2 shortcut pools with `ceil_mode=True`, as in the reference `presnet.py`. `RTDETR` then runs wherever its neck can join the three feature levels, as in the reference: 636 x 636 runs, while 600 x 600 still stops in the neck. Inputs at multiples of 32 give the same outputs as before.
+- `rtdetr_r50vd_m` decodes with the third of its six decoder layers (`eval_idx: 2` in the reference configs of that checkpoint), as the published R50-M model does; it ran all six, which moved its logits by up to 3.5 on a sample image. `RTDETRConfig` gains `eval_idx` (`None` selects the variant's layer) and `RTDETRHead` an `eval_idx` argument; an index outside the decoder raises.
+- `ResizePreProcessor` records the original sizes as `int64` on the images' device. It stored them in the image dtype, so a `bfloat16` 667 x 1000 image was recorded as 668 x 1000 and a `float16` 4097 x 2051 image as 4096 x 2052, and `ResizePostProcessor`, as in `EdgeDetector`, returned a map one row too tall.
+- `output_type="pil"` in the `visualize` of `ObjectDetector`, `EdgeDetector`, `SuperResolution`, `SemanticSegmentation` and `DepthEstimation` returns a list of `PIL.Image.Image`, one per `(C, H, W)` or `(H, W)` image; it returned NumPy arrays.
+- `ModelBase.load_checkpoint(path, device=...)` moves the model to `device`; the parameters stayed where they were, on the CPU after `device=torch.device("mps")`.
+- `SuperResolution` built by `RRDBNetBuilder` runs a list of images one at a time; a list, even of one image, raised `RuntimeError: Sizes of tensors must match except in dimension 1`.
+- `save(output_type="pil")` raised in `SemanticSegmentation`, `EdgeDetector`, `SuperResolution` and `DepthEstimation` (`SemanticSegmentation`: a `ValueError` for a batch tensor and a `TypeError` for a list of images; the others: an `AttributeError` on the NumPy arrays). It now writes the same files as `output_type="torch"`, with the same pixels.
diff --git a/docs/export_support/cases_models.py b/docs/export_support/cases_models.py
index 967062f2a..c69a08ad2 100644
--- a/docs/export_support/cases_models.py
+++ b/docs/export_support/cases_models.py
@@ -1204,10 +1204,8 @@ A(
reuse(od, _e_od),
lambda m: m,
[torch.rand(1, 3, 200, 320)],
- note="ObjectDetector = ResizePreProcessor(256,256) + RTDETR + DETRPostProcessor; threshold 0 "
- "-> all 300 boxes (1,300,6). "
- "KORNIA BUG: builder passes `confidence_filtering or not is_in_onnx_export()` so confidence_filtering=False "
- "is ignored at build time (list output); forward is @torch.inference_mode()",
+ note="ObjectDetector = ResizePreProcessor(640,640) + RTDETR + DETRPostProcessor (image_size=256 is ignored "
+ "with a model_name); threshold 0 -> all 300 boxes (1,300,6). forward is @torch.inference_mode()",
tags=("model", "pretrained"),
)
)
@@ -1223,7 +1221,7 @@ A(
reuse(od_f, _e_odf),
lambda m: m,
[torch.rand(1, 3, 200, 320)],
- note="default confidence_filtering=True unless is_in_onnx_export(); list of (Di,6) tensors",
+ note="default confidence_filtering=True; list of (Di,6) tensors",
tags=("model", "pretrained"),
)
)
diff --git a/docs/source/_data/export_support.json b/docs/source/_data/export_support.json
index 1375554e5..704e0ca07 100644
--- a/docs/source/_data/export_support.json
+++ b/docs/source/_data/export_support.json
@@ -21937,7 +21937,7 @@
"export_detail": "",
"graph_breaks": 0,
"name": "contrib.RTDETRDetectorBuilder.build[r18vd,image_size=256,threshold=0]",
- "note": "ObjectDetector = ResizePreProcessor(256,256) + RTDETR + DETRPostProcessor; threshold 0 -> all 300 boxes (1,300,6). KORNIA BUG: builder passes `confidence_filtering or not is_in_onnx_export()` so confidence_filtering=False is ignored at build time (list output); forward is @torch.inference_mode() | to_onnx(save=False) OK (78.67 MB, ['ai.onnx:18'], in [['input', ['s34', 3, 256, 256]]], out [['output', ['u0', 6]]])",
+ "note": "ObjectDetector = ResizePreProcessor(640,640) + RTDETR + DETRPostProcessor (image_size=256 is ignored with a model_name); threshold 0 -> all 300 boxes (1,300,6). forward is @torch.inference_mode() | to_onnx(save=False) OK (78.67 MB, ['ai.onnx:18'], in [['input', ['s34', 3, 256, 256]]], out [['output', ['u0', 6]]])",
"onnx": "ok",
"onnx_detail": "",
"operator": "RTDETRDetectorBuilder.build",
@@ -21954,7 +21954,7 @@
"export_detail": "",
"graph_breaks": 1,
"name": "contrib.RTDETRDetectorBuilder.build[r18vd,threshold=0.3,list output]",
- "note": "default confidence_filtering=True unless is_in_onnx_export(); list of (Di,6) tensors | to_onnx(save=False) OK (78.22 MB, ['ai.onnx:18'], in [['input', ['s34', 3, 256, 256]]], out [['output', [1, 300, 80]], ['select_27', ['s34', 300, 4]]])",
+ "note": "default confidence_filtering=True; list of (Di,6) tensors | to_onnx(save=False) OK (78.22 MB, ['ai.onnx:18'], in [['input', ['s34', 3, 256, 256]]], out [['output', [1, 300, 80]], ['select_27', ['s34', 300, 4]]])",
"onnx": "ok",
"onnx_detail": "",
"operator": "RTDETRDetectorBuilder.build",
diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.py
index 1c4cc95b9..e3cd8fa97 100644
--- a/kornia/contrib/object_detection.py
+++ b/kornia/contrib/object_detection.py
@@ -160,7 +160,7 @@ class ObjectDetector(ModelBase, ONNXExportMixin):
"""
raise NotImplementedError(
"ObjectDetector.from_config() is not implemented. "
- "Use kornia.contrib.object_detection.RtdetrBuilder.build() or instantiate ObjectDetector directly."
+ "Use kornia.contrib.object_detection.RTDETRDetectorBuilder.build() or instantiate ObjectDetector directly."
)
@torch.inference_mode()
@@ -233,8 +233,7 @@ class ObjectDetector(ModelBase, ONNXExportMixin):
) -> onnx.ModelProto:
"""Export an RT-DETR object detection model to ONNX format.
- Either `model_name` or `config` must be provided. If neither is provided,
- a default pretrained model (`rtdetr_r18vd`) will be built.
+ Exports this detector, as built by :meth:`RTDETRDetectorBuilder.build` or the constructor.
Args:
onnx_name:
@@ -431,11 +430,12 @@ class RTDETRDetectorBuilder:
pretrained:
Whether to load a pretrained version of the model (applies when `model_name` is provided).
image_size:
- The size to which input images will be resized during preprocessing.
- If None, no resizing will be inferred from config file. Recommended scales include
+ The size to which input images will be resized during preprocessing, used only with `config`. If
+ None, `config.input_size` is used. With `model_name`, or without either, it is ignored: the input is
+ resized to the 640 px the published weights were trained for. Recommended scales include
[480, 512, 544, 576, 608, 640, 672, 704, 736, 768, 800].
confidence_threshold: Threshold to filter results based on confidence scores.
- confidence_filtering: Whether to filter results based on confidence scores.
+ confidence_filtering: Whether to filter results based on confidence scores. None filters.
Returns:
@@ -474,7 +474,7 @@ class RTDETRDetectorBuilder:
ResizePreProcessor(image_size, image_size),
DETRPostProcessor(
confidence_threshold=confidence_threshold,
- confidence_filtering=confidence_filtering or not torch.onnx.is_in_onnx_export(),
+ confidence_filtering=True if confidence_filtering is None else confidence_filtering,
num_classes=model.decoder.num_classes,
num_top_queries=model.decoder.num_queries,
),
diff --git a/kornia/contrib/super_resolution.py b/kornia/contrib/super_resolution.py
index 407dc43ad..dd43e5266 100644
--- a/kornia/contrib/super_resolution.py
+++ b/kornia/contrib/super_resolution.py
@@ -60,7 +60,12 @@ class SuperResolutionConfig:
the lightweight variant is ``"small_sr"``.
pretrained: If ``True``, load pretrained weights for the selected variant.
upscale_factor: Integer scale used by the lightweight variant. Ignored by
- the RRDB variants, whose scale is fixed by ``model_name``.
+ the RRDB variants, whose scale is fixed by ``model_name``. The lightweight
+ variant resizes every input to 224 x 224 first, discarding its aspect ratio,
+ so its output is ``224 * upscale_factor`` square (672 x 672 for 3, from a
+ 100 x 50 input as from a 480 x 640 one). Its pretrained weights exist only
+ for 3: another factor with ``pretrained=True`` raises a size-mismatch
+ :class:`RuntimeError`.
image_size: Optional fixed input size for the lightweight variant. It declares
the size fed to the wrapper; it does not change the pre-processor, which
always resizes to 224, so the output side stays ``224 * upscale_factor``.
@@ -155,7 +160,8 @@ class SuperResolution(ModelBase[SuperResolutionConfig], ONNXExportMixin):
"""
output = self.pre_processor(images)
- images = output[0] if isinstance(output, (list, tuple)) else output
+ # ``ResizePreProcessor`` returns an ``(images, sizes)`` tuple; a list of images goes through one at a time
+ images = output[0] if isinstance(output, tuple) else output
if isinstance(images, list):
out_images = [self.model(image[None])[0] for image in images]
else:
@@ -172,7 +178,7 @@ class SuperResolution(ModelBase[SuperResolutionConfig], ONNXExportMixin):
Args:
images: input torch.Tensor.
- edge_maps: detected edges.
+ edge_maps: super-resolved images; computed with :meth:`forward` when None.
output_type: type of the output.
Returns:
@@ -198,13 +204,9 @@ class SuperResolution(ModelBase[SuperResolutionConfig], ONNXExportMixin):
Args:
images: input torch.Tensor.
- edge_maps: detected edges.
- output_type: type of the output.
+ edge_maps: super-resolved images; computed with :meth:`forward` when None.
directory: where to save outputs.
- output_type: backend used to generate outputs.
-
- Returns:
- output torch.Tensor.
+ output_type: "torch" or "pil", passed to :meth:`visualize`; the files hold the same pixels either way.
"""
outputs = self.visualize(images, edge_maps, output_type)
@@ -225,9 +227,6 @@ class SuperResolution(ModelBase[SuperResolutionConfig], ONNXExportMixin):
onnx_name:
The name of the output ONNX file. If not provided, a default name in the
format "Kornia-<ClassName>.onnx" will be used.
- image_size:
- The size to which input images will be resized during preprocessing.
- If None, image_size will be dynamic. For DexiNed, recommended scale is 352.
include_pre_and_post_processor:
Whether to include the pre-processor and post-processor in the exported model.
save:
@@ -326,9 +325,12 @@ class SmallSRBuilder:
model_name: Name of the model variant to build. Currently only
``"small_sr"`` is supported.
pretrained: If ``True``, load pretrained weights for the selected model.
- upscale_factor: Integer scale used by ``SmallSRNetWrapper``.
- For example, ``3`` maps an input image of size ``H x W`` to an
- output image of approximately ``3H x 3W``.
+ upscale_factor: Integer scale used by ``SmallSRNetWrapper``. The pre-processor
+ first resizes every input to 224 x 224, discarding its aspect ratio, so the
+ output is ``224 * upscale_factor`` square: with ``3``, a 100 x 50 and a
+ 480 x 640 input both give 672 x 672. Pretrained weights exist only for
+ ``3``; another factor with ``pretrained=True`` raises a size-mismatch
+ :class:`RuntimeError`.
image_size: Optional fixed input size. It declares the size fed to the
wrapper and does not change the pre-processor, which always resizes to
224; the output side is therefore ``224 * upscale_factor``.
diff --git a/kornia/models/base.py b/kornia/models/base.py
index db4365390..3dedfd2a2 100644
--- a/kornia/models/base.py
+++ b/kornia/models/base.py
@@ -28,8 +28,7 @@ from torch import nn
from kornia.core.download import load_state_dict_from_url
from kornia.core.external import PILImage as Image
-from kornia.core.mixin.image_module import _to_uint8_image
-from kornia.image.utils import tensor_to_image
+from kornia.core.mixin.image_module import ImageModuleMixIn, _to_uint8_image
from kornia.io import write_image
logger = logging.getLogger(__name__)
@@ -37,7 +36,7 @@ logger = logging.getLogger(__name__)
ModelConfig = TypeVar("ModelConfig")
-def _write_png_batch(path_stem: str, image: torch.Tensor) -> None:
+def _write_png_batch(path_stem: str, image: Union[torch.Tensor, Image.Image]) -> None:
"""Write one image, or one file per item of a batch.
``visualize`` returns float images in ``[0, 1]``, but ``write_image`` writes
@@ -54,7 +53,13 @@ def _write_png_batch(path_stem: str, image: torch.Tensor) -> None:
A batch of one still gets an index suffix, so a caller does not have to
guess whether a file will be ``name.png`` or ``name_0.png``.
+
+ A PIL image, what ``visualize(output_type="pil")`` returns, was made 8-bit by
+ the same conversion and is written as it is, to ``name.png``.
"""
+ if not isinstance(image, torch.Tensor):
+ image.save(f"{path_stem}.png")
+ return
image = _to_uint8_image(image)
if image.dim() == 4:
for i, item in enumerate(image):
@@ -79,25 +84,39 @@ class ModelBaseMixin:
is_batch: If True, the output is expected to be a batch of tensors.
Returns:
- The converted output tensor or list of tensors.
+ The output unchanged for "torch". For "pil", a list of PIL images, one per :math:`(C, H, W)` or
+ :math:`(H, W)` image: a :math:`(B, C, H, W)` tensor gives B images, and a list gives the images of each
+ element in turn. They are converted as :meth:`~kornia.core.mixin.image_module.ImageModuleMixIn.to_pil`
+ does: a floating image is clamped to ``[0, 1]`` and rounded to 8 bits, and a one-channel or
+ :math:`(H, W)` image becomes a mode ``"L"`` image.
Raises:
RuntimeError: If the output type is not supported.
"""
- if output_type == "torch":
- return output
+ self._check_output_type(output_type)
if output_type == "pil":
- if isinstance(output, list):
- return [tensor_to_image(t) for t in output]
- return tensor_to_image(output)
- raise RuntimeError(f"Output type {output_type} is not supported. Accepted values are 'torch' and 'pil'.")
+ images = []
+ for t in output if isinstance(output, list) else [output]:
+ # an (H, W) item is one single-channel image; larger items are split into (C, H, W) slices
+ t = t[None] if t.dim() == 2 else t
+ images.extend(ImageModuleMixIn._chw_to_pil(chw) for chw in t.reshape(-1, *t.shape[-3:]))
+ return images
+ return output
+
+ @staticmethod
+ def _check_output_type(output_type: str) -> None:
+ """Raise ``RuntimeError`` unless ``output_type`` is "torch" or "pil"."""
+ if output_type not in ("torch", "pil"):
+ raise RuntimeError(f"Output type {output_type} is not supported. Accepted values are 'torch' and 'pil'.")
- def save(self, output: Union[torch.Tensor, List[torch.Tensor]], directory: str, is_batch: bool = False) -> None:
+ def save(
+ self, output: Union[torch.Tensor, List[torch.Tensor], List[Image.Image]], directory: str, is_batch: bool = False
+ ) -> None:
"""Save the output tensor to a directory.
Args:
- output: The output tensor or list of tensors.
+ output: The output tensor, or a list of tensors or PIL images.
directory: The directory to save the output.
is_batch: If True, the output is expected to be a batch of tensors.
@@ -112,12 +131,15 @@ class ModelBaseMixin:
logger.info(f"Outputs are saved in {directory}")
def _save_outputs(
- self, output: Union[torch.Tensor, List[torch.Tensor]], directory: Optional[str] = None, suffix: str = ""
+ self,
+ output: Union[torch.Tensor, List[torch.Tensor], List[Image.Image]],
+ directory: Optional[str] = None,
+ suffix: str = "",
) -> None:
"""Save the output tensor to a directory with an optional suffix.
Args:
- output: The output tensor or list of tensors.
+ output: The output tensor, or a list of tensors or PIL images.
directory: The directory to save the output. If None, a default directory is used.
suffix: Optional suffix to add to the filename.
@@ -159,6 +181,8 @@ class ModelBase(ABC, nn.Module, ModelBaseMixin, Generic[ModelConfig]):
state_dict = load_state_dict_from_url(checkpoint, map_location=device)
self.load_state_dict(state_dict)
+ if device is not None:
+ self.to(device)
@staticmethod
@abstractmethod
diff --git a/kornia/models/common.py b/kornia/models/common.py
index bc79f46af..38dd13cf4 100644
--- a/kornia/models/common.py
+++ b/kornia/models/common.py
@@ -25,15 +25,20 @@ from torch import nn
class ConvNormAct(nn.Sequential):
"""Apply a sequence of Convolution, Normalization, and Activation layers.
+ The convolution has no bias and is followed by :class:`nn.BatchNorm2d`. Its padding follows from ``kernel_size``:
+ ``(kernel_size - 1) // 2`` on each side for an odd kernel, and for an even kernel a zero padding with one more
+ pixel at the bottom and right, as in PaddlePaddle.
+
Args:
in_channels: Number of input channels.
out_channels: Number of output channels.
kernel_size: Size of the convolution kernel.
stride: Stride of the convolution. Default: 1.
- padding: Zero-padding added to both sides of the input. Default: 0.
+ act: Activation, ``"relu"``, ``"silu"`` or ``"none"`` (identity). Default: ``"relu"``.
groups: Number of blocked connections from input to output. Default: 1.
- norm: Normalization layer type. Default: :class:`nn.BatchNorm2d`.
- act: Activation layer type. Default: :class:`nn.ReLU`.
+ conv_naming: Attribute name of the convolution, which sets its parameter names. Default: ``"conv"``.
+ norm_naming: Attribute name of the normalization layer. Default: ``"norm"``.
+ act_naming: Attribute name of the activation. Default: ``"act"``.
"""
def __init__(
diff --git a/kornia/models/processors/__init__.py b/kornia/models/processors/__init__.py
index eabfb1ed4..a5906261a 100644
--- a/kornia/models/processors/__init__.py
+++ b/kornia/models/processors/__init__.py
@@ -68,12 +68,15 @@ class ResizePreProcessor(nn.Module):
Returns:
Tuple containing:
- resized_imgs: Resized images as a tensor of shape :math:`(B, C, H_{\text{new}}, W_{\text{new}})`.
- - original_sizes: Original image sizes of shape :math:`(B, 2)` containing (height, width).
+ - original_sizes: Original image sizes of shape :math:`(B, 2)` containing (height, width), as
+ ``int64`` on the images' device.
"""
resized_imgs: List[Tensor] = []
iters = len(imgs) if isinstance(imgs, list) else imgs.shape[0]
- original_sizes = imgs[0].new_zeros((iters, 2))
+ # int64: a half-precision image dtype cannot hold every size (bfloat16 rounds 667 to 668). Filled per image
+ # rather than built with ``torch.tensor``, which the TorchScript ONNX exporter bakes in as constants.
+ original_sizes = imgs[0].new_zeros((iters, 2), dtype=torch.long)
for i in range(iters):
img = imgs[i]
@@ -115,8 +118,8 @@ class ResizePostProcessor(nn.Module):
(height, width) pairs.
Returns:
- Resized images in a batch with original dimensions. If ONNX export is active,
- returns inputs unchanged with a warning.
+ A list of :math:`(1, C, H, W)` tensors, one per image, each resized to its original size. If ONNX export
+ is active, returns inputs unchanged with a warning.
Warning:
ResizePostProcessor is not fully supported in ONNX export mode.
diff --git a/kornia/models/rt_detr/architecture/resnet_d.py b/kornia/models/rt_detr/architecture/resnet_d.py
index 013d78e7f..b0c4fb81c 100644
--- a/kornia/models/rt_detr/architecture/resnet_d.py
+++ b/kornia/models/rt_detr/architecture/resnet_d.py
@@ -35,7 +35,16 @@ from kornia.models.common import ConvNormAct
def _make_shortcut(in_channels: int, out_channels: int, stride: int) -> nn.Module:
return (
nn.Sequential(
- OrderedDict([("pool", nn.AvgPool2d(2, 2)), ("conv", ConvNormAct(in_channels, out_channels, 1, act="none"))])
+ OrderedDict(
+ [
+ # ``ceil_mode`` as in the reference ``presnet.py``: an odd input keeps the size of the strided
+ # conv branch, ceil(H / 2). ``count_include_pad=False`` is the same in eager, with no padding;
+ # in ONNX it makes onnxruntime <= 1.28 average a partial window over the pixels inside it, as
+ # eager and Paddle's ``exclusive=True`` do, instead of dividing it by 4
+ ("pool", nn.AvgPool2d(2, 2, 0, ceil_mode=True, count_include_pad=False)),
+ ("conv", ConvNormAct(in_channels, out_channels, 1, act="none")),
+ ]
+ )
)
if stride == 2
else ConvNormAct(in_channels, out_channels, 1, act="none")
diff --git a/kornia/models/rt_detr/architecture/rtdetr_head.py b/kornia/models/rt_detr/architecture/rtdetr_head.py
index c85541b8f..37c285962 100644
--- a/kornia/models/rt_detr/architecture/rtdetr_head.py
+++ b/kornia/models/rt_detr/architecture/rtdetr_head.py
@@ -26,6 +26,7 @@ from typing import Optional
import torch
from torch import nn
+from kornia.core.check import KORNIA_CHECK
from kornia.models.common import MLP, ConvNormAct
@@ -239,6 +240,11 @@ class TransformerDecoder(nn.Module):
self.hidden_dim = hidden_dim
self.num_layers = num_layers
self.eval_idx = eval_idx if eval_idx >= 0 else num_layers + eval_idx
+ KORNIA_CHECK(
+ 0 <= self.eval_idx < num_layers,
+ f"eval_idx must index one of the {num_layers} decoder layers ({-num_layers} to {num_layers - 1}), "
+ f"got {eval_idx}.",
+ )
def forward(
self,
@@ -317,7 +323,11 @@ class TransformerDecoder(nn.Module):
class RTDETRHead(nn.Module):
- """Implement the RT-DETR prediction head for object detection."""
+ """Implement the RT-DETR prediction head for object detection.
+
+ ``eval_idx`` selects the decoder layer whose predictions the head returns; a negative value counts back from the
+ last layer (``-1``), and the layers after the selected one do not run.
+ """
def __init__(
self,
@@ -331,6 +341,7 @@ class RTDETRHead(nn.Module):
num_levels: int = 3,
dropout: float = 0.0,
num_denoising: int = 100,
+ eval_idx: int = -1,
) -> None:
super().__init__()
self.num_classes = num_classes
@@ -357,7 +368,7 @@ class RTDETRHead(nn.Module):
)
self.decoder = TransformerDecoder(
- hidden_dim=hidden_dim, decoder_layer=decoder_layer, num_layers=num_decoder_layers
+ hidden_dim=hidden_dim, decoder_layer=decoder_layer, num_layers=num_decoder_layers, eval_idx=eval_idx
)
# denoising part
diff --git a/kornia/models/rt_detr/model.py b/kornia/models/rt_detr/model.py
index d889ec96c..5090d8f4a 100644
--- a/kornia/models/rt_detr/model.py
+++ b/kornia/models/rt_detr/model.py
@@ -83,15 +83,27 @@ class RTDETRConfig:
- 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`
+ - ResNetD-50-M: ``6``, ``'resnet50d_m'`` or :attr:`RTDETRModelType.resnet50d_m`
num_classes: number of classes.
- checkpoint: URL or local path of model weights.
+ input_size: size of the square image that
+ :meth:`~kornia.contrib.object_detection.RTDETRDetectorBuilder.build` resizes the input to.
+ checkpoint: URL or local path of a state dict with kornia's parameter names, loaded by
+ :meth:`RTDETR.from_config`. The published RT-DETR checkpoints keep the reference implementation's names and
+ load only through :meth:`RTDETR.from_pretrained`.
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.
+ confidence_threshold: score threshold of the post-processor that
+ :meth:`~kornia.contrib.object_detection.RTDETRDetectorBuilder.build` creates from this config when it is
+ given no ``confidence_threshold``.
+ eval_idx: index of the decoder layer whose predictions the model returns; a negative value counts back from
+ the last layer (``-1``), and the layers after the selected one do not run. ``None`` selects the variant's
+ layer: index 2, the third of six, for ``resnet50d_m``, as in the reference configs of that checkpoint (or
+ the last layer of a decoder with fewer than three), and the last layer for the other variants.
"""
@@ -107,6 +119,7 @@ class RTDETRConfig:
head_num_queries: int = 300
head_num_decoder_layers: Optional[int] = None
confidence_threshold: float = 0.3
+ eval_idx: Optional[int] = None
@staticmethod
def from_name(model_name: str, num_classes: int = 80) -> RTDETRConfig:
@@ -173,6 +186,8 @@ class RTDETR(ONNXExportMixin, ModelBase[RTDETRConfig]):
model_type = getattr(RTDETRModelType, model_type)
backbone: ResNetD | PPHGNetV2
+ # the last decoder layer, except for R50-M below
+ default_eval_idx = -1
if model_type == RTDETRModelType.resnet18d:
backbone = ResNetD.from_config(18)
@@ -201,6 +216,9 @@ class RTDETR(ONNXExportMixin, ModelBase[RTDETRConfig]):
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 0.5
+ # R50-M decodes with the third of its six layers: ``eval_idx: 2`` in both reference configs,
+ # ``rtdetr_r50vd_m_6x_coco.yml`` of lyuwenyu/RT-DETR rtdetr_pytorch and rtdetr_paddle
+ default_eval_idx = min(2, head_num_decoder_layers - 1)
elif model_type == RTDETRModelType.resnet101d:
backbone = ResNetD.from_config(101)
@@ -232,6 +250,7 @@ class RTDETR(ONNXExportMixin, ModelBase[RTDETRConfig]):
num_queries=config.head_num_queries,
in_channels=[neck_hidden_dim] * 3,
num_decoder_layers=head_num_decoder_layers,
+ eval_idx=config.eval_idx if config.eval_idx is not None else default_eval_idx,
),
)
diff --git a/kornia/models/rt_detr/post_processor.py b/kornia/models/rt_detr/post_processor.py
index 890830d1d..c7160066a 100644
--- a/kornia/models/rt_detr/post_processor.py
+++ b/kornia/models/rt_detr/post_processor.py
@@ -54,8 +54,10 @@ def mod(a: torch.Tensor, b: int) -> torch.Tensor:
class DETRPostProcessor(nn.Module):
"""Convert raw DETR model outputs into final bounding box detections.
- This module applies the softmax function to scores and transforms normalized
- bounding box coordinates into the pixel coordinate system of the input image.
+ This module applies the sigmoid function to the class logits, as RT-DETR was trained with a focal loss, keeps the
+ ``num_top_queries`` highest (query, class) scores of each image, and transforms the normalized
+ ``(cx, cy, w, h)`` boxes into ``(x, y, w, h)`` in the pixel coordinate system of each input image, scaled by that
+ image's own size.
Args:
num_classes: The number of object classes.
@@ -97,8 +99,11 @@ class DETRPostProcessor(nn.Module):
represents the image size of (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).
+ Processed detections, each a row (class_id, confidence_score, x, y, w, h). A tensor of shape
+ :math:`(N, T, 6)`, :math:`T` = ``num_top_queries``, when ``confidence_filtering`` is ``False`` or
+ ``confidence_threshold`` is 0; with ``filter_as_zero``, the same tensor with the detections at or below the
+ threshold set to zero. Otherwise a list of :math:`N` tensors of shape :math:`(D, 6)`, where :math:`D` is the
+ number of detections above the threshold in that image.
"""
# NOTE: consider using kornia BoundingBox
@@ -112,8 +117,8 @@ class DETRPostProcessor(nn.Module):
cxcy, wh = boxes[..., :2], boxes[..., 2:]
boxes_xy = torch.cat([cxcy - wh * 0.5, wh], -1)
- # Get dynamic size from the input tensor itself
- sizes_wh = original_sizes[0].flip(0).unsqueeze(0).unsqueeze(0).repeat(1, 1, 2)
+ # (B, 2) (H, W) -> (B, 1, 4) (W, H, W, H): each image is scaled by its own size
+ sizes_wh = original_sizes.flip(-1).repeat(1, 2).unsqueeze(1).to(boxes_xy.dtype)
boxes_xy = boxes_xy * sizes_wh
scores = logits.sigmoid() # RT-DETR was trained with focal loss. thus sigmoid is used instead of softmax
diff --git a/kornia/models/segmentation/base.py b/kornia/models/segmentation/base.py
index 67107698c..32d1bbfa6 100644
--- a/kornia/models/segmentation/base.py
+++ b/kornia/models/segmentation/base.py
@@ -219,7 +219,7 @@ class SemanticSegmentation(ModelBase):
If torch.Tensor, a torch.Tensor with shape :math:`(B, 3, H, W)`.
semantic_masks: If list of segmentation masks. Each mask is a torch.Tensor with shape :math:`(C, H, W)`.
If torch.Tensor, a torch.Tensor with shape :math:`(B, C, H, W)`.
- output_type: The type of output, can be "torch" or "PIL".
+ output_type: The type of output, can be "torch" or "pil".
colormap: The colormap to use, can be "random" or a custom color map.
manual_seed: The manual seed to use for the colormap.
@@ -267,12 +267,14 @@ class SemanticSegmentation(ModelBase):
semantic_masks: If list of segmentation masks. Each mask is a torch.Tensor with shape :math:`(C, H, W)`.
If torch.Tensor, a torch.Tensor with shape :math:`(B, C, H, W)`.
directory: The directory to save the results.
- output_type: The type of output, can be "torch" or "PIL".
+ output_type: "torch" or "pil", as in :meth:`visualize`; it does not change the files written.
colormap: The colormap to use, can be "random" or a custom color map.
manual_seed: The manual seed to use for the colormap.
"""
- colored_masks = self.visualize(images, semantic_masks, output_type, colormap=colormap, manual_seed=manual_seed)
+ self._check_output_type(output_type)
+ # The overlay and the files are made from the tensors, whatever output type was asked for.
+ colored_masks = self.visualize(images, semantic_masks, "torch", colormap=colormap, manual_seed=manual_seed)
overlaid: Union[torch.Tensor, list[torch.Tensor]]
if isinstance(images, torch.Tensor) and isinstance(colored_masks, torch.Tensor):
overlaid = kornia.enhance.add_weighted(images, 0.5, colored_masks, 0.5, 1.0)
diff --git a/kornia/models/small_sr.py b/kornia/models/small_sr.py
index b86f81514..12052ee9a 100644
--- a/kornia/models/small_sr.py
+++ b/kornia/models/small_sr.py
@@ -32,6 +32,10 @@ class SmallSRNet(nn.Module):
"Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network"
- Shi et al for increasing the resolution of an image by an upscale factor.
Taken from https://pytorch.org/tutorials/advanced/super_resolution_with_onnxruntime.html.
+
+ The pretrained weights are that tutorial's, trained for ``upscale_factor=3``; with ``pretrained=True`` any other
+ factor raises a size-mismatch :class:`RuntimeError`. Through :class:`~kornia.contrib.SmallSRBuilder` every input
+ is first resized to 224 x 224, so the output there is ``224 * upscale_factor`` square.
"""
def __init__(self, upscale_factor: int, inplace: bool = False, pretrained: bool = True) -> None:
diff --git a/tests/contrib/test_super_resolution.py b/tests/contrib/test_super_resolution.py
index 0b626352a..85c6d4f7a 100644
--- a/tests/contrib/test_super_resolution.py
+++ b/tests/contrib/test_super_resolution.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+import re
import sys
import pytest
@@ -52,6 +53,45 @@ class TestSuperResolutionBuilders(BaseTester):
assert out.shape[0] == 1
assert out.shape[1] == 3
+ @pytest.mark.parametrize("num_images", [1, 2])
+ def test_rrdb_list_input(self, device, dtype, num_images):
+ # Every RRDB variant has the same identity pre-processor; the 6-block one keeps CPU half precision fast.
+ model = RRDBNetBuilder.build("RealESRGAN_x4plus_anime_6B", pretrained=False).to(device, dtype)
+ images = [torch.rand(3, 16, 20, device=device, dtype=dtype) for _ in range(num_images)]
+
+ out = model(images)
+
+ assert isinstance(out, list)
+ assert len(out) == num_images
+ for image, actual in zip(images, out):
+ # RealESRGAN_x4plus_anime_6B upscales by 4
+ assert actual.shape == (3, 64, 80)
+ self.assert_close(actual, model(image[None])[0])
+
+ def test_save_pil_writes_the_torch_pixels(self, tmp_path):
+ pytest.importorskip("PIL.Image")
+ from kornia.io import ImageLoadType, load_image
+
+ # the 6-block RRDB variant, random init, on small images
+ model = RRDBNetBuilder.build("RealESRGAN_x4plus_anime_6B", pretrained=False)
+ images = torch.rand(2, 3, 16, 20)
+
+ written = {}
+ for output_type in ("torch", "pil"):
+ directory = tmp_path / output_type
+ model.save(images, directory=str(directory), output_type=output_type)
+ # file names carry a "_YYYYmmdd_HHMMSS" timestamp, which may differ between the two calls
+ written[output_type] = {
+ re.sub(r"_\d{8}_\d{6}", "", p.name): load_image(str(p), ImageLoadType.UNCHANGED)
+ for p in sorted(directory.iterdir())
+ }
+
+ # source and super-resolved image of each of the two images, under the same names and with the same pixels
+ assert len(written["torch"]) == 4
+ assert written["pil"].keys() == written["torch"].keys()
+ for name, decoded in written["torch"].items():
+ assert torch.equal(written["pil"][name], decoded), name
+
@pytest.mark.parametrize("model_name", ["small_sr", "RealESRNet_x4plus"])
def test_from_config_dispatches_to_both_families(self, device, dtype, model_name):
config = SuperResolutionConfig(model_name=model_name, pretrained=False)
diff --git a/tests/models/test_model_base.py b/tests/models/test_model_base.py
index 8e7f35053..7600d0310 100644
--- a/tests/models/test_model_base.py
+++ b/tests/models/test_model_base.py
@@ -19,12 +19,16 @@ from __future__ import annotations
import os
import pickle
+import re
from unittest.mock import patch
+import numpy as np
import pytest
import torch
from torch import nn
+from kornia.contrib.edge_detection import EdgeDetectorBuilder
+from kornia.io import ImageLoadType, load_image
from kornia.models.base import ModelBase, ModelBaseMixin
from testing.base import BaseTester
@@ -48,20 +52,47 @@ class TestModelBaseMixinTensorToType:
out = mixin._tensor_to_type(tensors, "torch")
assert out is tensors
- def test_pil_output_single_tensor(self):
+ @staticmethod
+ def _assert_pil_images(images, tensors, modes):
+ """Each image is one (C, H, W) slice, converted as ``ImageModuleMixIn.to_pil`` does."""
+ Image = pytest.importorskip("PIL.Image")
+ slices = [chw for t in tensors for chw in t.reshape(-1, *t.shape[-3:])]
+ assert isinstance(images, list)
+ assert len(images) == len(slices) == len(modes)
+ for image, chw, mode in zip(images, slices, modes):
+ assert isinstance(image, Image.Image)
+ assert image.mode == mode
+ # PIL sizes are (W, H)
+ assert image.size == (chw.shape[-1], chw.shape[-2])
+ # clamped to [0, 1], scaled to 0..255 and rounded; (H, W, 3) for "RGB", (H, W) for "L"
+ expected = (chw.clamp(0, 1) * 255).round().byte().permute(1, 2, 0)
+ if mode == "L":
+ expected = expected[..., 0]
+ assert np.array_equal(np.asarray(image), expected.numpy())
+
+ @pytest.mark.parametrize(
+ ("shape", "modes"), [((3, 4, 5), ["RGB"]), ((1, 4, 5), ["L"]), ((2, 3, 4, 5), ["RGB", "RGB"])]
+ )
+ def test_pil_output_single_tensor(self, shape, modes):
mixin = DummyMixin()
- # (C, H, W) tensor in [0, 1]
- t = torch.rand(3, 16, 16)
+ # values beyond [0, 1] check the clamp
+ t = torch.rand(*shape) * 1.2 - 0.1
out = mixin._tensor_to_type(t, "pil")
- # tensor_to_image returns a PIL Image or ndarray depending on implementation
- assert out is not None
+ self._assert_pil_images(out, [t], modes)
def test_pil_output_list_of_tensors(self):
mixin = DummyMixin()
- tensors = [torch.rand(3, 16, 16), torch.rand(3, 16, 16)]
+ tensors = [torch.rand(3, 4, 5), torch.rand(1, 4, 5), torch.rand(2, 3, 4, 5)]
out = mixin._tensor_to_type(tensors, "pil")
- assert isinstance(out, list)
- assert len(out) == 2
+ self._assert_pil_images(out, tensors, ["RGB", "L", "RGB", "RGB"])
+
+ def test_pil_output_2d_items(self):
+ mixin = DummyMixin()
+ # values beyond [0, 1] check the clamp
+ t = torch.rand(4, 5) * 1.2 - 0.1
+ # an (H, W) map converts as the same map with one channel, (1, H, W): one mode "L" image
+ self._assert_pil_images(mixin._tensor_to_type(t, "pil"), [t[None]], ["L"])
+ self._assert_pil_images(mixin._tensor_to_type([t, t[None]], "pil"), [t[None], t[None]], ["L", "L"])
def test_unsupported_output_type_raises(self):
mixin = DummyMixin()
@@ -70,6 +101,68 @@ class TestModelBaseMixinTensorToType:
mixin._tensor_to_type(t, "numpy")
+def _decoded_files(directory):
+ """The decoded images of a directory, keyed by file name without its ``_YYYYmmdd_HHMMSS`` timestamp."""
+ return {
+ re.sub(r"_\d{8}_\d{6}", "", p.name): load_image(str(p), ImageLoadType.UNCHANGED)
+ for p in sorted(directory.iterdir())
+ }
+
+
+class TestModelBaseWrappersPilOutput:
+ """``output_type="pil"`` in a wrapper's ``visualize`` and ``save``, on a random-init ``EdgeDetector``."""
+
+ # edge maps in the forms EdgeDetector.visualize accepts: the (B, 1, H, W) tensor and a list of (1, H, W) maps,
+ # whose items it reduces to (H, W), and a list of (1, 1, H, W) maps as its forward returns, reduced to (3, H, W)
+ _FORMS = ("tensor (B, 1, H, W)", "list of (1, H, W)", "list of (1, 1, H, W)")
+
+ @staticmethod
+ def _edge_maps(form):
+ maps = torch.rand(2, 1, 8, 10)
+ if form == "list of (1, H, W)":
+ return list(maps)
+ if form == "list of (1, 1, H, W)":
+ return [m[None] for m in maps]
+ return maps
+
+ @pytest.mark.parametrize("form", _FORMS)
+ def test_edge_detector_visualize_pil(self, form):
+ Image = pytest.importorskip("PIL.Image")
+ detector = EdgeDetectorBuilder.build(pretrained=False)
+ images = torch.rand(2, 3, 8, 10)
+ edge_maps = self._edge_maps(form)
+
+ out = detector.visualize(images, edge_maps, output_type="pil")
+
+ drawn = detector.visualize(images, edge_maps)
+ assert isinstance(out, list)
+ assert len(out) == len(drawn) == 2
+ for image, tensor in zip(out, drawn):
+ assert isinstance(image, Image.Image)
+ # (H, W) items become mode "L", (3, H, W) items "RGB", each clamped, scaled to 0..255 and rounded
+ expected = (tensor.clamp(0, 1) * 255).round().byte()
+ expected = expected.permute(1, 2, 0) if expected.dim() == 3 else expected
+ assert image.mode == ("RGB" if tensor.dim() == 3 else "L")
+ assert np.array_equal(np.asarray(image), expected.numpy())
+
+ @pytest.mark.parametrize("form", _FORMS)
+ def test_edge_detector_save_pil_writes_the_torch_pixels(self, form, tmp_path):
+ pytest.importorskip("PIL.Image")
+ detector = EdgeDetectorBuilder.build(pretrained=False)
+ images = torch.rand(2, 3, 8, 10)
+ edge_maps = self._edge_maps(form)
+
+ for output_type in ("torch", "pil"):
+ detector.save(images, edge_maps, directory=str(tmp_path / output_type), output_type=output_type)
+ written = {output_type: _decoded_files(tmp_path / output_type) for output_type in ("torch", "pil")}
+
+ # source and edge map of each of the two images, under the same names and with the same pixels
+ assert len(written["torch"]) == 4
+ assert written["pil"].keys() == written["torch"].keys()
+ for name, decoded in written["torch"].items():
+ assert torch.equal(written["pil"][name], decoded), name
+
+
class TestModelBaseMixinSave:
def test_save_single_tensor_calls_write_image_once(self, tmp_path):
mixin = DummyMixin()
@@ -259,6 +352,29 @@ class TestModelBaseLoadCheckpoint(BaseTester):
self.assert_close(model.linear.weight, source.linear.weight)
self.assert_close(model.linear.bias, source.linear.bias)
+ def test_load_checkpoint_moves_the_model(self, tmp_path, device) -> None:
+ path = tmp_path / "model.pth"
+ torch.save(_TinyModel().state_dict(), path)
+
+ model = _TinyModel()
+ model.load_checkpoint(str(path), device=device)
+
+ assert {p.device for p in model.parameters()} == {device}
+
+ @pytest.mark.device_agnostic
+ def test_load_checkpoint_calls_to_with_the_device(self, tmp_path) -> None:
+ path = tmp_path / "model.pth"
+ torch.save(_TinyModel().state_dict(), path)
+ model = _TinyModel()
+
+ with patch.object(_TinyModel, "to", autospec=True, side_effect=nn.Module.to) as to:
+ model.load_checkpoint(str(path))
+ to.assert_not_called()
+
+ model.load_checkpoint(str(path), device=torch.device("cpu"))
+ assert to.call_count == 1
+ assert torch.device("cpu") in (*to.call_args.args[1:], *to.call_args.kwargs.values())
+
def test_load_checkpoint_keeps_the_mode(self, tmp_path) -> None:
path = tmp_path / "model.pth"
torch.save(_TinyModel().state_dict(), path)
diff --git a/tests/models/test_object_detector.py b/tests/models/test_object_detector.py
index a3c83ec7b..acb65ba57 100644
--- a/tests/models/test_object_detector.py
+++ b/tests/models/test_object_detector.py
@@ -113,6 +113,18 @@ class TestObjectDetector(BaseTester):
assert torch.all(dets[:, 0].int() == dets[:, 0])
assert torch.all(dets[:, 1] >= 0.3)
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize(("confidence_filtering", "expected"), [(False, False), (None, True), (True, True)])
+ def test_builder_honours_confidence_filtering_false(self, confidence_filtering, expected):
+ detector = kornia.contrib.object_detection.RTDETRDetectorBuilder.build(
+ "rtdetr_r18vd", pretrained=False, confidence_filtering=confidence_filtering
+ )
+ assert detector.post_processor.confidence_filtering is expected
+
+ # Without filtering the post-processor returns the (B, Q, 6) tensor, with it a list of (D, 6) tensors.
+ out = detector.post_processor(torch.zeros(1, 300, 80), torch.zeros(1, 300, 4), torch.tensor([[640, 640]]))
+ assert isinstance(out, list) is expected
+
@pytest.mark.slow
@pytest.mark.timeout(120)
@pytest.mark.skipif(torch_version_lt(2, 0, 0), reason="Unsupported ONNX opset version: 16")
diff --git a/tests/models/test_processors.py b/tests/models/test_processors.py
new file mode 100644
index 000000000..309e8cdc1
--- /dev/null
+++ b/tests/models/test_processors.py
@@ -0,0 +1,61 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import pytest
+import torch
+
+from kornia.models.processors import ResizePostProcessor, ResizePreProcessor
+
+from testing.base import BaseTester
+
+# Image sizes that a half-precision image dtype cannot hold. bfloat16 keeps 8 significant bits, so 667 rounds to 668,
+# 1001 to 1000 and 333 to 332; float16 keeps 11, so 4097 rounds to 4096 and 2051 to 2052.
+_HALF_SIZE_CASES = [
+ pytest.param(torch.bfloat16, [(667, 1000)], False, id="bfloat16-batch-of-one"),
+ pytest.param(torch.bfloat16, [(667, 1000)], True, id="bfloat16-list-of-one"),
+ pytest.param(torch.float16, [(4097, 2051)], True, id="float16-list-of-one"),
+ pytest.param(torch.bfloat16, [(667, 1000), (1001, 333)], True, id="bfloat16-list-of-two"),
+]
+
+
+class TestResizePreProcessor(BaseTester):
+ @pytest.mark.parametrize(("image_dtype", "sizes", "as_list"), _HALF_SIZE_CASES)
+ def test_resize_preprocessor_records_int64_sizes(self, device, image_dtype, sizes, as_list):
+ images = [torch.rand(3, h, w, device=device).to(image_dtype) for h, w in sizes]
+
+ resized, original_sizes = ResizePreProcessor(8, 8)(images if as_list else torch.stack(images))
+
+ assert resized.shape == (len(sizes), 3, 8, 8)
+ assert original_sizes.dtype == torch.int64
+ assert original_sizes.device == device
+ assert original_sizes.tolist() == [list(size) for size in sizes]
+
+
+class TestResizePostProcessor(BaseTester):
+ @pytest.mark.parametrize(
+ ("image_dtype", "sizes"), [(torch.bfloat16, [(667, 1000)]), (torch.bfloat16, [(667, 1000), (1001, 333)])]
+ )
+ def test_resize_postprocessor_returns_original_size(self, device, dtype, image_dtype, sizes):
+ images = [torch.rand(3, h, w, device=device).to(image_dtype) for h, w in sizes]
+ _, original_sizes = ResizePreProcessor(8, 8)(images)
+ maps = torch.rand(len(sizes), 1, 8, 8, device=device, dtype=dtype)
+
+ out = ResizePostProcessor()(maps, original_sizes)
+
+ # a list of (1, C, H, W) maps, each at its image's original size
+ assert isinstance(out, list)
+ assert [tuple(item.shape) for item in out] == [(1, 1, h, w) for h, w in sizes]
diff --git a/tests/models/test_rt_detr.py b/tests/models/test_rt_detr.py
index 81862152d..bc44b29e9 100644
--- a/tests/models/test_rt_detr.py
+++ b/tests/models/test_rt_detr.py
@@ -20,11 +20,13 @@ from functools import partial
import pytest
import torch
+from kornia.core.exceptions import BaseError
from kornia.models.rt_detr.architecture.hgnetv2 import PPHGNetV2
from kornia.models.rt_detr.architecture.hybrid_encoder import HybridEncoder, RepVggBlock
from kornia.models.rt_detr.architecture.resnet_d import ResNetD
from kornia.models.rt_detr.architecture.rtdetr_head import RTDETRHead
from kornia.models.rt_detr.model import RTDETR, RTDETRConfig
+from kornia.models.rt_detr.post_processor import DETRPostProcessor
from testing.base import BaseTester, assert_close
@@ -88,6 +90,32 @@ def test_regvgg_optimize_for_deployment(device, dtype):
assert_close(actual, expected, atol=1e-3, rtol=1e-2)
+class TestDETRPostProcessor(BaseTester):
+ @pytest.mark.parametrize("sizes_dtype", [torch.float32, torch.int64])
+ def test_postprocessor_scales_each_image_by_its_size(self, device, dtype, sizes_dtype):
+ post_processor = DETRPostProcessor(
+ confidence_threshold=0.0, num_classes=2, num_top_queries=1, confidence_filtering=False
+ )
+ logits = torch.tensor([[[5.0, -5.0]]] * 2, device=device, dtype=dtype)
+ # one normalised (cx, cy, w, h) box per image
+ boxes = torch.tensor([[[0.5, 0.5, 0.25, 0.25]]] * 2, device=device, dtype=dtype)
+ # (H, W) of each image
+ sizes = torch.tensor([[100, 200], [400, 800]], device=device, dtype=sizes_dtype)
+
+ out = post_processor(logits, boxes, sizes)
+
+ # xywh in the pixels of each image's own size: x = (cx - w / 2) * W, y = (cy - h / 2) * H, w * W, h * H.
+ # Image 0: (0.375 * 200, 0.375 * 100, 0.25 * 200, 0.25 * 100); image 1: the same with H = 400, W = 800.
+ expected = torch.tensor(
+ [[[75.0, 37.5, 50.0, 25.0]], [[300.0, 150.0, 200.0, 100.0]]], device=device, dtype=dtype
+ )
+ assert out.shape == (2, 1, 6)
+ assert out.dtype == dtype
+ self.assert_close(out[..., 2:], expected)
+ # the top query of sigmoid([5, -5]) is class 0
+ assert out[..., 0].tolist() == [[0.0], [0.0]]
+
+
class TestRTDETR(BaseTester):
@pytest.mark.slow # This will be slow for the bigger variants
@pytest.mark.parametrize("variant", ["resnet18d", "resnet34d", "resnet50d", "resnet101d", "hgnetv2_l", "hgnetv2_x"])
@@ -112,6 +140,67 @@ class TestRTDETR(BaseTester):
assert logits.shape == (shape[0], num_queries, num_classes)
assert boxes.shape == (shape[0], num_queries, 4)
+ def test_resnet_d_odd_sizes(self, device, dtype):
+ backbone = ResNetD.from_config(18).to(device, dtype).eval()
+ # The stem takes a height of 636 to 159, an odd size. A stride-2 stage then gives ceil(159 / 2) = 80 on both
+ # paths only when the shortcut pool rounds up, as the reference ``nn.AvgPool2d(2, 2, 0, ceil_mode=True)`` of
+ # lyuwenyu/RT-DETR ``presnet.py`` does; 80 -> 40 -> 20 for the next two stages. The width, 64 -> 16 after the
+ # stem, stays even (a narrow width keeps the run short in CPU half precision).
+ fmaps = backbone(torch.rand(1, 3, 636, 64, device=device, dtype=dtype))
+ assert [tuple(fmap.shape[-2:]) for fmap in fmaps] == [(80, 8), (40, 4), (20, 2)]
+
+ # The whole detector: the stem takes 92 x 96 to 23 x 24, an odd height, and the backbone returns 12 x 12,
+ # 6 x 6 and 3 x 3, sizes the neck's nearest x2 upsampling joins again.
+ model = RTDETR.from_config(RTDETRConfig("resnet18d", 10, head_num_queries=10)).to(device, dtype).eval()
+ logits, boxes = model(torch.rand(1, 3, 92, 96, device=device, dtype=dtype))
+ assert logits.shape == (1, 10, 10)
+ assert boxes.shape == (1, 10, 4)
+
+ def test_resnet_d_shortcut_pool_partial_windows(self, device, dtype):
+ pools = [m for name, m in ResNetD.from_config(18).named_modules() if name.endswith("short.pool")]
+ assert len(pools) == 3
+ # A window that runs past the bottom or right edge averages only the pixels inside it, as the reference
+ # ``nn.AvgPool2d(2, 2, 0, ceil_mode=True)`` does: on a map of ones every window, partial or not, gives 1.
+ x = torch.ones(1, 1, 3, 5, device=device, dtype=dtype)
+ for pool in pools:
+ self.assert_close(pool.to(device, dtype)(x), torch.ones(1, 1, 2, 3, device=device, dtype=dtype))
+
+ @pytest.mark.device_agnostic
+ def test_decoder_eval_idx(self):
+ in_channels = [32, 64, 128]
+ head = RTDETRHead(5, 32, 10, in_channels, 3, eval_idx=0).eval()
+ ran = []
+ for i, layer in enumerate(head.decoder.layers):
+ layer.register_forward_hook(lambda module, args, output, i=i: ran.append(i))
+ generator = torch.Generator().manual_seed(0)
+ fmaps = [
+ torch.rand(1, ch, h, w, generator=generator) for ch, (h, w) in zip(in_channels, [(16, 12), (8, 6), (4, 3)])
+ ]
+ logits, boxes = head(fmaps)
+ assert ran == [0]
+ assert logits.shape == (1, 10, 5)
+ assert boxes.shape == (1, 10, 4)
+
+ def eval_idx(config: RTDETRConfig) -> int:
+ return RTDETR.from_config(config).decoder.decoder.eval_idx
+
+ # Both reference configs of the r50vd_m checkpoint (lyuwenyu/RT-DETR rtdetr_pytorch and rtdetr_paddle
+ # ``rtdetr_r50vd_m_6x_coco.yml``) set ``eval_idx: 2`` on a 6-layer decoder; the other variants decode with
+ # their last layer: 3 layers for r18, 6 for r50.
+ assert eval_idx(RTDETRConfig("resnet50d_m", 80)) == 2
+ assert eval_idx(RTDETRConfig("resnet18d", 80)) == 2
+ assert eval_idx(RTDETRConfig("resnet50d", 80)) == 5
+ assert eval_idx(RTDETRConfig("resnet50d_m", 80, eval_idx=4)) == 4
+ assert eval_idx(RTDETRConfig("resnet50d_m", 80, eval_idx=0)) == 0
+ assert eval_idx(RTDETRConfig("resnet18d", 80, eval_idx=-2)) == 1
+ # a 2-layer r50vd_m decoder keeps its last layer, min(2, 2 - 1)
+ assert eval_idx(RTDETRConfig("resnet50d_m", 80, head_num_decoder_layers=2)) == 1
+
+ # a 3-layer decoder accepts -3..2
+ for out_of_range in (3, -4):
+ with pytest.raises(BaseError, match="eval_idx"):
+ RTDETRHead(5, 32, 10, in_channels, 3, eval_idx=out_of_range)
+
@pytest.mark.device_agnostic
def test_from_pretrained_mode(self, monkeypatch):
monkeypatch.setattr(
diff --git a/tests/models/test_rtdetr_onnx.py b/tests/models/test_rtdetr_onnx.py
index deb7de789..c36139f2b 100644
--- a/tests/models/test_rtdetr_onnx.py
+++ b/tests/models/test_rtdetr_onnx.py
@@ -18,8 +18,15 @@
"""ONNX export tests for RT-DETR."""
import pytest
+import torch
+from torch import nn
+from kornia.contrib.object_detection import ObjectDetector
+from kornia.models.processors import ResizePreProcessor
from kornia.models.rt_detr.model import RTDETR, RTDETRConfig
+from kornia.models.rt_detr.post_processor import DETRPostProcessor
+
+from testing.base import DYNAMO_UNAVAILABLE_REASON, assert_close, dynamo_is_available
# Every test in this module must stay device-free: the mark deselects the whole file on non-CPU devices.
pytestmark = pytest.mark.device_agnostic
@@ -45,3 +52,131 @@ def test_rtdetr_to_onnx(tmp_path):
output_names = [o.name for o in op.graph.output]
assert "pred_logits" in output_names, f"Expected 'pred_logits' in outputs, got {output_names}"
assert "pred_boxes" in output_names, f"Expected 'pred_boxes' in outputs, got {output_names}"
+
+
+def _post_processor() -> DETRPostProcessor:
+ return DETRPostProcessor(confidence_threshold=0.0, num_classes=2, num_top_queries=1, confidence_filtering=False)
+
+
[email protected]("sizes_dtype", [torch.float32, torch.int64])
+def test_postprocessor_onnx_per_image_sizes(tmp_path, sizes_dtype):
+ """The exported post-processor scales each image of a batch by its own size, as eager does."""
+ pytest.importorskip("onnx")
+ ort = pytest.importorskip("onnxruntime")
+ pytest.importorskip("onnxscript")
+
+ logits = torch.tensor([[[5.0, -5.0]]] * 2)
+ # one normalised (cx, cy, w, h) box per image
+ boxes = torch.tensor([[[0.5, 0.5, 0.25, 0.25]]] * 2)
+ # (H, W) of each image
+ sizes = torch.tensor([[100, 200], [400, 800]], dtype=sizes_dtype)
+
+ onnx_path = tmp_path / "detr_post_processor.onnx"
+ torch.onnx.export(
+ _post_processor(),
+ (logits, boxes, sizes),
+ str(onnx_path),
+ input_names=["logits", "boxes", "sizes"],
+ output_names=["detections"],
+ dynamic_axes={"logits": {0: "N"}, "boxes": {0: "N"}, "sizes": {0: "N"}, "detections": {0: "N"}},
+ opset_version=18,
+ )
+ session = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
+
+ (detections,) = session.run(None, {"logits": logits.numpy(), "boxes": boxes.numpy(), "sizes": sizes.numpy()})
+ # xywh, x = (cx - w / 2) * W, y = (cy - h / 2) * H, w * W, h * H, with each image's own (H, W)
+ expected = torch.tensor([[[75.0, 37.5, 50.0, 25.0]], [[300.0, 150.0, 200.0, 100.0]]])
+ assert_close(torch.from_numpy(detections)[..., 2:], expected)
+ assert_close(torch.from_numpy(detections), _post_processor()(logits, boxes, sizes))
+
+ # the batch axis is dynamic: image 1 alone
+ (detections,) = session.run(
+ None, {"logits": logits[1:].numpy(), "boxes": boxes[1:].numpy(), "sizes": sizes[1:].numpy()}
+ )
+ assert_close(torch.from_numpy(detections)[..., 2:], expected[1:])
+
+
+class _FixedDetections(nn.Module):
+ """Stand-in for RT-DETR: one fixed query per image, a box in normalised (cx, cy, w, h)."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.register_buffer("logits", torch.tensor([[[5.0, -5.0]]]))
+ self.register_buffer("boxes", torch.tensor([[[0.5, 0.5, 0.25, 0.25]]]))
+
+ def forward(self, images: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ batch = images.shape[0]
+ return self.logits.expand(batch, -1, -1), self.boxes.expand(batch, -1, -1)
+
+
+def test_resize_preprocessor_onnx_dynamic_sizes():
+ """With a dynamic H and W, the exported detector reads each input's size instead of the trace's."""
+ pytest.importorskip("onnx")
+ ort = pytest.importorskip("onnxruntime")
+ pytest.importorskip("onnxscript")
+
+ detector = ObjectDetector(_FixedDetections(), ResizePreProcessor(32, 32), _post_processor())
+ exported = detector.to_onnx(image_size=None, include_pre_and_post_processor=True, save=False)
+ session = ort.InferenceSession(exported.SerializeToString(), providers=["CPUExecutionProvider"])
+
+ generator = torch.Generator().manual_seed(0)
+ for height, width in [(77, 128), (96, 100)]:
+ images = torch.rand(1, 3, height, width, generator=generator)
+ (detections,) = session.run(None, {"input": images.numpy()})
+ detections = torch.from_numpy(detections)
+
+ assert_close(detections, detector(images))
+ # xywh of the normalised box (0.5, 0.5, 0.25, 0.25) in this image's pixels
+ expected = torch.tensor([[[0.375 * width, 0.375 * height, 0.25 * width, 0.25 * height]]])
+ assert_close(detections[..., 2:], expected)
+
+
+ "dynamo",
+ [False, pytest.param(True, marks=pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON))],
+)
+def test_resnet_d_onnx_odd_sizes(tmp_path, dynamo):
+ """At an odd feature map the exported ResNet-D matches eager in old and new ONNX Runtime alike.
+
+ Runtimes disagree on a partial ``ceil_mode`` window of an ``AveragePool`` with ``count_include_pad=1``: ONNX
+ Runtime up to 1.28 divides it by the whole 2 x 2 window, 1.29 and later by the pixels inside it, as eager does.
+ With ``count_include_pad=0`` both divide by the pixels inside it. The graph is checked as well as the runtime, as
+ the runtime that runs this test may be one that hides the difference.
+ """
+ onnx = pytest.importorskip("onnx")
+ ort = pytest.importorskip("onnxruntime")
+ pytest.importorskip("onnxscript")
+ from kornia.models.rt_detr.architecture.resnet_d import ResNetD
+
+ class _Features(nn.Module):
+ def __init__(self) -> None:
+ super().__init__()
+ self.backbone = ResNetD.from_config(18)
+
+ def forward(self, images: torch.Tensor) -> tuple[torch.Tensor, ...]:
+ return tuple(self.backbone(images))
+
+ model = _Features().eval()
+ # the stem takes 92 x 96 to 23 x 24: the first stride-2 shortcut pool has a partial window at the bottom
+ images = torch.rand(1, 3, 92, 96, generator=torch.Generator().manual_seed(0))
+ onnx_path = tmp_path / "resnet_d.onnx"
+ if dynamo:
+ torch.onnx.export(model, (images,), dynamo=True, opset_version=18).save(str(onnx_path))
+ else:
+ torch.onnx.export(model, (images,), str(onnx_path), dynamo=False, opset_version=17, input_names=["images"])
+
+ pools = [node for node in onnx.load(str(onnx_path)).graph.node if node.op_type == "AveragePool"]
+ assert len(pools) == 3
+ for node in pools:
+ attributes = {a.name: onnx.helper.get_attribute_value(a) for a in node.attribute}
+ assert attributes.get("count_include_pad", 0) == 0
+
+ session = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
+ outputs = session.run(None, {session.get_inputs()[0].name: images.numpy()})
+ with torch.no_grad():
+ expected = model(images)
+ for actual, fmap in zip(outputs, expected):
+ assert_close(torch.from_numpy(actual), fmap, atol=1e-4, rtol=1e-4)
diff --git a/tests/models/test_segmentation_models.py b/tests/models/test_segmentation_models.py
index 38ee3bcda..be6b94ff1 100644
--- a/tests/models/test_segmentation_models.py
+++ b/tests/models/test_segmentation_models.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+import re
+
import pytest
import torch
from torch import nn
@@ -192,6 +194,37 @@ class TestSemanticSegmentation(BaseTester):
with pytest.raises(ValueError, match="softmax"):
model.visualize(torch.rand(1, 3, 6, 6, device=device, dtype=dtype))
+ @pytest.mark.parametrize("as_list", [False, True])
+ def test_save_writes_the_same_files_for_every_output_type(self, device, dtype, as_list, tmp_path):
+ model = SegmentationModelsBuilder.build(_stand_in_network(3), IMAGENET_PARAMS).to(device, dtype)
+ images = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
+ if as_list:
+ images = list(images)
+
+ written = {}
+ for output_type in ("torch", "pil"):
+ directory = tmp_path / output_type
+ model.save(images, directory=str(directory), output_type=output_type, manual_seed=7)
+ # file names carry a "_YYYYmmdd_HHMMSS" timestamp, which may differ between the two calls
+ written[output_type] = {re.sub(r"_\d{8}_\d{6}", "", p.name): p.read_bytes() for p in directory.iterdir()}
+
+ # source, mask and overlay of each of the two images
+ assert len(written["torch"]) == 6
+ assert written["pil"] == written["torch"]
+
+ # the mask files are the visualization with the colormap seed given to save
+ reference = tmp_path / "reference"
+ model._save_outputs(model.visualize(images, manual_seed=7), str(reference), suffix="_mask")
+ masks = {name: data for name, data in written["torch"].items() if "_mask_" in name}
+ assert masks == {re.sub(r"_\d{8}_\d{6}", "", p.name): p.read_bytes() for p in reference.iterdir()}
+ # and the colormap reaches it too: "random" is the only one there is
+ with pytest.raises(ValueError, match="Unsupported colormap"):
+ model.save(images, directory=str(tmp_path / "jet"), colormap="jet")
+
+ with pytest.raises(RuntimeError, match="Output type numpy is not supported"):
+ model.save(images, directory=str(tmp_path / "numpy"), output_type="numpy")
+ assert not (tmp_path / "numpy").exists()
+
def test_preprocessing_onnx_export(self, device):
# The pipeline is documented as ONNX-friendly: export it and compare the runtime against eager.
pytest.importorskip("onnx")