π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
build(deps): declare optional extras `onnx` and `sd`; remove BoxMotTracker; import-free SegmentationModelsBuilder (#4301)
Dmytro Mishkinf61442a492c9
diff --git a/.github/actions/coverage/action.yml b/.github/actions/coverage/action.ymlindex 010ff259c..3e8ddf05e 100644--- a/.github/actions/coverage/action.yml+++ b/.github/actions/coverage/action.yml@@ -26,6 +26,10 @@ inputs:description: "Whether to continue on error"required: falsedefault: "false"+ extra-install:+ description: "Optional-dependency extra to install alongside dev, e.g. 'sd'"+ required: false+ default: ""runs:using: "composite"@@ -46,6 +50,11 @@ runs:shell: bashrun: pixi run -e ${{ steps.pixi-env.outputs.name }} install+ - name: Install optional extra ${{ inputs.extra-install }}+ if: inputs.extra-install != ''+ shell: bash+ run: pixi run -e ${{ steps.pixi-env.outputs.name }} uv sync --extra dev --extra ${{ inputs.extra-install }}+- name: Run CPU tests coverage ${{ inputs.pytorch-dtype }}continue-on-error: ${{ inputs.continue-on-error == 'true' }}shell: bashdiff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.ymlindex 45260e137..957ae8286 100644--- a/.github/workflows/coverage.yml+++ b/.github/workflows/coverage.yml@@ -60,6 +60,8 @@ jobs:pytorch-device: ${{ inputs.pytorch-device }}pytest-extra: '--runslow -k "slow and not test_dynamo"'coverage-artifact: coverage-slow-${{ matrix.pytorch-dtype }}+ # tests/filters/test_dissolving.py is slow-only and needs kornia[sd]+ extra-install: sddynamo:# Run all dynamo (torch.compile) related testsdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 390daea9e..0ebe47381 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+* Optional-dependency extras `kornia[onnx]` and `kornia[sd]` declare the third-party packages that+ the ONNX and Stable-Diffusion-dissolving wrappers lazily import, and are documented on the+ installation page. Missing-dependency errors now name the extra to install, and `dev` no longer+ pulls `diffusers` and `transformers`. (#4301)* KimiVL and SigLIP2 builders load their safetensors checkpoints with kornia's own downloader(`kornia.core.download_hf_file`/`download_file_from_url`, which share the retrying, rate-limit-awarecache every other checkpoint uses) and a pure-torch reader (`kornia.core.load_safetensors`);@@ -128,6 +132,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Breaking changes+* `kornia.contrib.BoxMotTracker` is removed, together with the `kornia.contrib.boxmot_tracker` module.+ It wrapped the [boxmot](https://github.com/mikel-brostrom/boxmot) tracker zoo around a kornia detector,+ but called the boxmot 10.x API (`boxmot.DeepOCSORT(model_weights=..., device=..., fp16=...)`), and no+ boxmot release that installs alongside the torch versions kornia supports (`torch>=2.5.1`) provides+ it, so the class could not be instantiated on any supported stack (see+ [#4320](https://github.com/kornia/kornia/issues/4320)). Track with boxmot directly, feeding it the+ output of a kornia detector such as `RTDETRDetectorBuilder`. `kornia.core.external.boxmot` is gone+ with it. (#4301)++* `SegmentationModelsBuilder.build()` no longer imports `segmentation_models_pytorch` (smp). It used+ to take `model_name`, `encoder_name`, `encoder_weights`, `in_channels`, `classes`, `activation` and+ `**kwargs`, import smp lazily, instantiate the smp architecture and look up the encoder's+ preprocessing parameters itself. It now takes a constructed `nn.Module` and the encoder's+ preprocessing-parameter dictionary (`build(model, preproc_params=None, name="segmentation_model")`),+ where `preproc_params` is what `smp.encoders.get_preprocessing_params(encoder_name)` returns; build+ the smp network and fetch its parameters yourself. Kornia no longer imports smp anywhere, and+ `kornia.core.external.segmentation_models_pytorch` is gone. `SemanticSegmentation` gained the+ `__init__(model, pre_processor, post_processor, name=None)` its siblings have, so the container the+ builder returns can be instantiated (it was abstract before). The `input_range: [0, 255]`+ preprocessing step is now `kornia.enhance.Rescale(255.0)`, a multiply by 255, instead of a+ `Normalize` by a stored `1/255`: bfloat16 rounds that reciprocal to a ~254.0 multiplier (0.5 mapped+ to 127.0 instead of 127.5), and float32 outputs of that step move by at most one ulp. (#4301)++* `kornia.core.external.transformers` was removed; it was a `LazyLoader` handle no kornia code used.+ Previously `from kornia.core.external import transformers` gave a lazy proxy that imported+ `transformers` on first attribute access; that name no longer exists, so import `transformers`+ directly instead. (#4301)* `KimiVLBuilder.from_pretrained_hf()` and `SigLip2Builder.from_pretrained_hf()` cache theircheckpoint where every other kornia checkpoint lives. `cache_dir=None` used to mean the HuggingFacecache (`~/.cache/huggingface/hub/models--<owner>--<name>/snapshots/<sha>/model.safetensors`) and now@@ -310,6 +341,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* `SemanticSegmentation.visualize` works for CUDA, MPS and half-precision models. It indexed the+ CPU-drawn colormap with the mask's `argmax`, which raises for CUDA and MPS masks, and recognised a+ softmax head with `torch.allclose(sum, 1)` at float32-sized default tolerances, which a float16 or+ bfloat16 sum of probabilities never meets; the tolerance now scales with the number of classes and the+ dtype's epsilon, and the colormap follows the mask's device and dtype, so the visualization keeps the+ model's dtype instead of coming back as float32. `OnnxLightGlue` without `onnxruntime` raises an+ `ImportError` that names `pip install "kornia[onnx]"`, like the lazy-loader handles do, instead of a+ bare `BaseError`. (#4301)* The generated example figures in the API reference are rendered from RGB input.`docs/generate_examples.py` decoded the sample images with `cv2.imdecode` and wrote them with`cv2.imwrite`, both BGR, so every tensor the examples fed to kornia held reversed channels. The twodiff --git a/README.md b/README.mdindex a436de1a2..f6e3788a8 100644--- a/README.md+++ b/README.md@@ -137,6 +137,8 @@ Kornia is an open-source project that is developed and maintained by volunteers.pip install kornia```+Some features (ONNX, Stable Diffusion dissolving) need extra packages; see [Optional extras](https://kornia.readthedocs.io/en/latest/get-started/installation.html#optional-extras).+<details><summary>Other installation options</summary>diff --git a/docs/export_support/cases_models.py b/docs/export_support/cases_models.pyindex 6dc281601..5d5de0e7b 100644--- a/docs/export_support/cases_models.py+++ b/docs/export_support/cases_models.py@@ -421,21 +421,29 @@ A(case("models.segmentation.SegmentationModelsBuilder.build","models.segmentation",- lambda d: SegmentationModelsBuilder.build("Unet", "resnet34", encoder_weights=None),+ SegmentationModelsBuilder.build(+ torch.nn.Sequential(torch.nn.Conv2d(3, 2, 1), torch.nn.Softmax(dim=1)),+ {+ "input_space": "BGR",+ "input_range": [0, 255],+ "mean": [0.485, 0.456, 0.406],+ "std": [0.229, 0.224, 0.225],+ },+ ),[IMG],- note="segmentation_models_pytorch not installed -> ImportError expected; even with it installed the builder "- "instantiates abstract SemanticSegmentation (no from_config, no __init__) -> TypeError (kornia bug)",+ note="builder wraps a user-built network (a 1x1 conv + softmax stand-in here; kornia does not import "+ "segmentation_models_pytorch) behind the BgrToRgb/rescale/Normalize preprocessing an smp encoder declares",))A(case("models.segmentation.SemanticSegmentation","models.segmentation",- lambda d: SemanticSegmentation(+ SemanticSegmentation(model=torch.nn.Identity(), pre_processor=torch.nn.Identity(), post_processor=torch.nn.Identity(), name="x"),[IMG],- note="KORNIA BUG: abstract class (ModelBase.from_config not implemented) -> cannot be instantiated",+ note="container with identity model/pre/post: the graph is the input",))A(case("models.base.ModelBase", "models.base", None, [], skip="abstract base class (from_config abstract)"))@@ -1311,8 +1319,6 @@ A("models.sam cases; default config is vit_h (>500 MB)",))-A(case("contrib.BoxMotTracker", "contrib.wrappers", None, [], skip="`boxmot` not installed; stateful tracker"))-# ============================================================================= kornia.trackingA(case(diff --git a/docs/source/_data/export_support.json b/docs/source/_data/export_support.jsonindex 80b65978c..45e552908 100644--- a/docs/source/_data/export_support.json+++ b/docs/source/_data/export_support.json@@ -20792,15 +20792,15 @@"where": ""},{- "compile": "n/a",- "compile_detail": "does not run eagerly with the probed inputs: EOFError <- ModuleNotFoundError: No module named 'segmentation_models_pytorch'",- "export": "n/a",- "export_detail": "does not run eagerly with the probed inputs: EOFError <- ModuleNotFoundError: No module named 'segmentation_models_pytorch'",- "graph_breaks": 0,+ "compile": "ok-breaks",+ "compile_detail": "2 graph breaks",+ "export": "ok",+ "export_detail": "",+ "graph_breaks": 2,"name": "models.segmentation.SegmentationModelsBuilder.build",- "note": "segmentation_models_pytorch not installed -> ImportError expected; even with it installed the builder instantiates abstract SemanticSegmentation (no from_config, no __init__) -> TypeError (kornia bug)",- "onnx": "n/a",- "onnx_detail": "does not run eagerly with the probed inputs: EOFError <- ModuleNotFoundError: No module named 'segmentation_models_pytorch'",+ "note": "builder wraps a user-built network (a 1x1 conv + softmax stand-in here; kornia does not import segmentation_models_pytorch) behind the BgrToRgb/rescale/Normalize preprocessing an smp encoder declares; re-measured on torch 2.14.0 for #4301, the rest of the snapshot is torch 2.9.1",+ "onnx": "ok",+ "onnx_detail": "","operator": "SegmentationModelsBuilder.build","package": "kornia.models","ref": "kornia.models.segmentation.segmentation_models.SegmentationModelsBuilder.build",@@ -20809,15 +20809,15 @@"where": ""},{- "compile": "n/a",- "compile_detail": "does not run eagerly with the probed inputs: TypeError : Can't instantiate abstract class SemanticSegmentation with abstract method from_config",- "export": "n/a",- "export_detail": "does not run eagerly with the probed inputs: TypeError : Can't instantiate abstract class SemanticSegmentation with abstract method from_config",+ "compile": "ok",+ "compile_detail": "",+ "export": "ok",+ "export_detail": "","graph_breaks": 0,"name": "models.segmentation.SemanticSegmentation",- "note": "KORNIA BUG: abstract class (ModelBase.from_config not implemented) -> cannot be instantiated",- "onnx": "n/a",- "onnx_detail": "does not run eagerly with the probed inputs: TypeError : Can't instantiate abstract class SemanticSegmentation with abstract method from_config",+ "note": "container with identity model/pre/post: the graph is the input; re-measured on torch 2.14.0 for #4301, the rest of the snapshot is torch 2.9.1",+ "onnx": "ok",+ "onnx_detail": "","operator": "SemanticSegmentation","package": "kornia.models","ref": "",@@ -22321,23 +22321,6 @@"variant": "","where": ""},- {- "compile": "n/a",- "compile_detail": "`boxmot` not installed; stateful tracker",- "export": "n/a",- "export_detail": "`boxmot` not installed; stateful tracker",- "graph_breaks": 0,- "name": "contrib.BoxMotTracker",- "note": "",- "onnx": "n/a",- "onnx_detail": "`boxmot` not installed; stateful tracker",- "operator": "BoxMotTracker",- "package": "kornia.contrib",- "ref": "kornia.contrib.boxmot_tracker.BoxMotTracker",- "section": "wrappers",- "variant": "",- "where": ""- },{"compile": "n/a","compile_detail": "stateful tracker (GFTTAffNetHardNet + LoFTR + RANSAC) returning (H, bool); RANSAC and LoFTR coarse matching are data-dependent \u2014 blocker recorded",diff --git a/docs/source/api.rst b/docs/source/api.rstindex 765b9e2ec..bcbde0a05 100644--- a/docs/source/api.rst+++ b/docs/source/api.rst@@ -64,7 +64,7 @@ Models:widths: 28 72* - :doc:`kornia.models <models>`- - Builders for the pretrained detection, edge detection, segmentation and tracking models.+ - Builders for the pretrained detection, edge detection and segmentation models.* - :doc:`kornia.contrib <contrib>`- Experimental operators and model wrappers: face detection, object detection, visual prompting, image stitching, KMeans.* - :doc:`kornia.tracking <tracking>`diff --git a/docs/source/conf.py b/docs/source/conf.pyindex a81759da6..6af311254 100644--- a/docs/source/conf.py+++ b/docs/source/conf.py@@ -527,8 +527,10 @@ intersphinx_mapping = {"torch": ("https://pytorch.org/docs/stable/", None),}-# mock these modules and won't try to actually import them-autodoc_mock_imports = ["boxmot", "segmentation_models_pytorch"]+# Optional third-party modules that autodoc must not try to import. Empty: the packages the documented+# API still reaches lazily (diffusers, onnx, onnxruntime) go through kornia.core.external.LazyLoader,+# which returns a placeholder under Sphinx (see the note there), so nothing needs mocking.+autodoc_mock_imports: list[str] = []# -- Social / SEO metadata --------------------------------------------------diff --git a/docs/source/get-started/installation.rst b/docs/source/get-started/installation.rstindex 2db19143f..a64a40c91 100644--- a/docs/source/get-started/installation.rst+++ b/docs/source/get-started/installation.rst@@ -47,6 +47,45 @@ Once the installation has finished, check that you can import the package:Pretrained models (RT-DETR, LoFTR, DISK, SAM, ...) download their checkpoints on first use, so noextra installation step is needed for them.+Optional extras+---------------++A few Kornia features wrap third-party packages that are not installed with the base wheel. They are+declared as `extras <https://packaging.python.org/en/latest/specifications/dependency-specifiers/#extras>`_,+so you only pay for the ones you use. If one of the extras below is missing, the corresponding Kornia+object tells you which extra to install: by default it offers to install the package for you on the+terminal (``kornia.config.kornia_config.lazyloader.installation_mode``, ``"ask"``; set it to ``"auto"``+to install without asking or ``"raise"`` to never install), and in ``"raise"`` mode, or when the offer+is declined, it raises an ``ImportError`` naming the extra. Pillow is the exception: no feature+extra covers it -- only the contributor ``dev`` and ``docs`` environments install it -- so its+message only asks you to install the package+(`kornia#4261 <https://github.com/kornia/kornia/issues/4261>`_ tracks which extra should carry it).++.. list-table::+ :header-rows: 1+ :widths: 15 55 30++ * - Extra+ - What it enables+ - Install command+ * - ``onnx``+ - :doc:`kornia.onnx </onnx>`, ONNX export of Kornia modules, and :class:`~kornia.feature.OnnxLightGlue`+ - ``pip install "kornia[onnx]"``+ * - ``sd``+ - ``kornia.filters.StableDiffusionDissolving``+ - ``pip install "kornia[sd]"``+ * - ``dev``+ - Contributor environment: the test and lint toolchain (includes ``kornia[onnx]``)+ - ``pip install -e ".[dev]"``+ * - ``docs``+ - Documentation toolchain, on top of ``dev``+ - ``pip install -e ".[dev,docs]"``++Independently of the extras, the ``visualize`` and ``save`` helpers of the model wrappers need+`pillow <https://pypi.org/project/pillow/>`_ for ``output_type="pil"``. No feature extra installs+it, so unless you are in a ``dev`` or ``docs`` environment, install it directly with+``pip install pillow``.+Next steps----------diff --git a/docs/source/get-started/introduction.rst b/docs/source/get-started/introduction.rstindex 6667df465..06f1b28ec 100644--- a/docs/source/get-started/introduction.rst+++ b/docs/source/get-started/introduction.rst@@ -69,7 +69,7 @@ At a granular level, Kornia is a library that consists of the following componen* - :doc:`kornia.metrics </metrics>`- metrics for classification, segmentation, detection, image quality and pose* - :doc:`kornia.models </models>`- - pretrained model builders for detection, edge detection, segmentation and tracking+ - pretrained model builders for detection, edge detection and segmentation* - :doc:`kornia.morphology </morphology>`- a module to perform morphological operations* - :doc:`kornia.onnx </onnx>`diff --git a/docs/source/get-started/multi-framework-support.rst b/docs/source/get-started/multi-framework-support.rstindex eadf0cee2..4f289dfa1 100644--- a/docs/source/get-started/multi-framework-support.rst+++ b/docs/source/get-started/multi-framework-support.rst@@ -26,8 +26,9 @@ show.``dill``, ``unittest.mock``, β¦) and hit an object it could not hash.* Even from a differently named checkout, ``to_tensorflow()`` segfaulted during transpilationwhenever ``transformers`` was installed in the same environment β which it was by default for- kornia contributors, since both packages shipped in the same ``dev`` extra. The crash happened- inside Ivy's Hugging Face integration lookup, which imports ``triton`` as a side effect.+ kornia contributors, since both packages shipped in the same ``dev`` extra (no longer the case:+ ``transformers`` moved to the optional ``sd`` extra). The crash happened inside Ivy's Hugging Face+ integration lookup, which imports ``triton`` as a side effect.* With ``transformers`` absent and the environment's ``ruff`` executable on ``PATH`` (Ivy shellsout to it to format generated code), ``to_tensorflow()`` did transpile and run``rgb_to_grayscale`` correctly.diff --git a/docs/source/get-started/onnx.rst b/docs/source/get-started/onnx.rstindex 3aa5d0f31..029edac93 100644--- a/docs/source/get-started/onnx.rst+++ b/docs/source/get-started/onnx.rst@@ -27,7 +27,7 @@ Quickstart.. code-block:: bash- pip install onnx onnxruntime+ pip install "kornia[onnx]"2. **Port your own kornia module**diff --git a/docs/source/models.rst b/docs/source/models.rstindex 830e39d0b..638d6b838 100644--- a/docs/source/models.rst+++ b/docs/source/models.rst@@ -2,13 +2,13 @@ kornia.models=============.. meta::- :description: The Kornia models overview provides detailed information about key built-in models for computer vision tasks, including real-time object detection (RT-DETR), edge detection (DexiNed), segmentation (UNet, DeepLabV3), and multi-object tracking (BoxMotTracker). It offers comprehensive documentation on each model, including methods, parameters, and example usage to streamline the integration of these models into computer vision workflows.+ :description: The Kornia models overview provides detailed information about key built-in models for computer vision tasks, including real-time object detection (RT-DETR), edge detection (DexiNed) and semantic segmentation (a wrapper for segmentation_models_pytorch networks). It offers comprehensive documentation on each model, including methods, parameters, and example usage to streamline the integration of these models into computer vision workflows.-Builders for Kornia's ready-to-use models (object detection, edge detection, semantic segmentation, multi-object tracking and Kimi-VL).+Builders for Kornia's ready-to-use models (object detection, edge detection, semantic segmentation and Kimi-VL).Each builder returns a configured model with pretrained weights. For the papers behind the models, see the :doc:`Models </models/index>` section.Pretrained weights are downloaded on first use, and the model builders return a regular ``nn.Module`` that accepts a-batched ``(B, 3, H, W)`` float image in ``[0, 1]`` (the tracker below wraps a detector in a plain Python class instead). :func:`kornia.io.get_sample_images` provides a couple of sample images for quick experiments.+batched ``(B, 3, H, W)`` float image in ``[0, 1]``. :func:`kornia.io.get_sample_images` provides a couple of sample images for quick experiments... _RTDETRDetectorBuilder:@@ -110,20 +110,26 @@ Copyright 2018-2022 BasicSR Authors); no extra package is required to use it.SegmentationModelsBuilder--------------------------The `SegmentationModelsBuilder` class offers a flexible API for building and running segmentation models from the-optional `segmentation_models_pytorch <https://github.com/qubvel-org/segmentation_models.pytorch>`_ package-(``pip install segmentation_models_pytorch``). It supports a variety of architectures such as UNet, FPN, DeepLabV3 and-others, with ImageNet-pretrained encoders.+The `SegmentationModelsBuilder` class wraps a segmentation network you have already built -- typically one from+`segmentation_models_pytorch <https://github.com/qubvel-org/segmentation_models.pytorch>`_ (smp), but any+``nn.Module`` mapping ``(B, 3, H, W)`` to ``(B, C, H, W)`` works -- in a+:class:`~kornia.models.segmentation.SemanticSegmentation` container, prepending the ONNX-friendly preprocessing+(BGR-to-RGB, range rescaling, mean/std normalization) that the encoder's pretrained weights expect. Kornia does not+import smp; you build the network and fetch its preprocessing parameters yourself.**Key Methods:**-- `build`: Constructs a segmentation model for the chosen architecture, encoder and number of classes.+- `build`: Wraps a constructed segmentation network and its encoder's preprocessing parameters.+- `get_preprocessing_pipeline`: Turns a preprocessing-parameter dictionary into an+ :class:`~kornia.augmentation.container.ImageSequential`.**Main parameters of** `build`:-- `model_name`: (str) Name of the segmentation architecture to use, e.g., `"Unet"`, `"DeepLabV3"`.-- `encoder_name`: (str) Name of the encoder backbone, e.g., `"resnet34"`.-- `classes`: (int) The number of output classes for segmentation.+- `model`: (nn.Module) The segmentation network.+- `preproc_params`: (dict | None) The encoder's preprocessing parameters, in the shape returned by+ ``smp.encoders.get_preprocessing_params(encoder_name)``: ``input_space``, ``input_range``, ``mean`` and ``std``.+ ``None`` means the input is fed to the network unchanged.+- `name`: (str) The name of the wrapped model, used by ``save``... autoclass:: kornia.models.segmentation.segmentation_models.SegmentationModelsBuilder:members:@@ -132,17 +138,27 @@ others, with ImageNet-pretrained encoders... rubric:: Example- Here's an example of how to use `SegmentationModelsBuilder` for binary segmentation:+ Here's an example of how to use `SegmentationModelsBuilder` with an smp UNet for two-class segmentation:.. code-block:: pythonimport kornia- from kornia.models.segmentation.segmentation_models import SegmentationModelsBuilder+ import segmentation_models_pytorch as smp+ from kornia.models.segmentation import SegmentationModelsBuilder++ net = smp.Unet(encoder_name="resnet34", encoder_weights="imagenet", classes=2, activation="softmax2d")+ params = smp.encoders.get_preprocessing_params("resnet34")+ model = SegmentationModelsBuilder.build(net, params, name="Unet_resnet34")input_tensor = kornia.io.get_sample_images()[0][None]- model = SegmentationModelsBuilder.build(model_name="Unet", encoder_name="resnet34", classes=1)segmented_output = model(input_tensor)- print(segmented_output.shape)+ print(segmented_output.shape) # (1, 2, H, W)++ The softmax head is what :meth:`~kornia.models.segmentation.SemanticSegmentation.visualize` needs: it+ colours each pixel by its most probable class and raises on raw logits.++.. autoclass:: kornia.models.segmentation.SemanticSegmentation+ :members: forward, visualize.. _KimiVLBuilder:@@ -172,46 +188,6 @@ loading currently supports only the converted Kimi-VL-A3B-Instruct vision encodemodel = KimiVLBuilder.from_pretrained_hf().eval()-.. _BoxMotTracker:--BoxMotTracker----------------The `BoxMotTracker` class is used for multi-object tracking in video streams. It combines a Kornia object detector with-a tracker from the optional `boxmot <https://github.com/mikel-brostrom/boxmot>`_ package (``pip install boxmot``) to-track bounding boxes across frames.--**Key Methods:**--- `__init__`: Initializes the multi-object tracker from a detector and a tracker model name.-- `update`: Updates the tracker with a new image frame.-- `visualize`: Draws the tracked boxes (and optionally their trajectories) on a frame.--**Main parameters:**--- `detector`: (ObjectDetector | str) The object detector instance, or the name of an RT-DETR model to build, e.g. `"rtdetr_r18vd"`.-- `tracker_model_name`: (str) The boxmot tracker to use, e.g. `"DeepOCSORT"`.--.. autoclass:: kornia.contrib.boxmot_tracker.BoxMotTracker- :members:- :undoc-members:- :show-inheritance:-- .. rubric:: Example-- The following example demonstrates how to track objects across multiple frames using `BoxMotTracker`:-- .. code-block:: python-- import kornia- from kornia.contrib.boxmot_tracker import BoxMotTracker-- image = kornia.io.get_sample_images()[0][None]- model = BoxMotTracker()- for i in range(4):- model.update(image) # Update the tracker with new frames- tracked = model.visualize(image) # Draw the tracked boxes on the frame-----.. note::diff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.pyindex 83d0b0b4b..7571da41d 100644--- a/kornia/contrib/__init__.py+++ b/kornia/contrib/__init__.py@@ -22,7 +22,6 @@ This subpackage provides community-contributed and experimental features.from kornia.models.tiny_vit import TinyViT-from .boxmot_tracker import BoxMotTrackerfrom .connected_components import connected_componentsfrom .diamond_square import diamond_squarefrom .distance_transform import DistanceTransform, distance_transform@@ -43,7 +42,6 @@ from .object_detection import ObjectDetector, RTDETRDetectorBuilderfrom .super_resolution import RRDBNetBuilder, SmallSRBuilder, SuperResolution__all__ = [- "BoxMotTracker","CombineTensorPatches","DistanceTransform","EdgeDetector",diff --git a/kornia/contrib/boxmot_tracker.py b/kornia/contrib/boxmot_tracker.pydeleted file mode 100644index 9db8b71aa..000000000--- a/kornia/contrib/boxmot_tracker.py+++ /dev/null@@ -1,182 +0,0 @@-# 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.-#--from __future__ import annotations--import datetime-import logging-import os-from pathlib import Path-from typing import Any, Optional, Union--import torch--from kornia.config import kornia_config-from kornia.contrib.object_detection import ObjectDetector, RTDETRDetectorBuilder-from kornia.core.external import boxmot-from kornia.core.external import numpy as np-from kornia.image.utils import tensor_to_image-from kornia.io import write_image--__all__ = ["BoxMotTracker"]--_logger = logging.getLogger(__name__)---class BoxMotTracker:- """BoxMotTracker is a module that wraps a detector and a tracker model.-- This module uses BoxMot library for tracking.-- Args:- detector: The detector model.- tracker_model_name: The name of the tracker model. Valid options are:- - "BoTSORT"- - "DeepOCSORT"- - "OCSORT"- - "HybridSORT"- - "ByteTrack"- - "StrongSORT"- - "ImprAssoc"- tracker_model_weights: Path to the model weights for ReID (Re-Identification).- device: Union[str, torch.device, None] on which to run the model (e.g., 'cpu' or 'cuda').- fp16: Whether to use half-precision (fp16) for faster inference on compatible devices.- per_class: Whether to perform per-class tracking.- track_high_thresh: High threshold for detection confidence.- Detections above this threshold are used in the first association round.- track_low_thresh: Low threshold for detection confidence.- Detections below this threshold are ignored.- new_track_thresh: Threshold for creating a new track.- Detections above this threshold will be considered as potential new tracks.- track_buffer: Number of frames to keep a track alive after it was last detected.- match_thresh: Threshold for the matching step in data association.- proximity_thresh: Threshold for IoU (Intersection over Union) distance in first-round association.- appearance_thresh: Threshold for appearance embedding distance in the ReID module.- cmc_method: Method for correcting camera motion. Options include "sof" (simple optical flow).- frame_rate: Frame rate of the video being processed. Used to scale the track buffer size.- fuse_first_associate: Whether to fuse appearance and motion information during the first association step.- with_reid: Whether to use ReID (Re-Identification) features for association.-- Note:- To use this tracker, load image tensors (shape: ``(1, C, H, W)``) and call ``model.update(image)``- for at least 4 frames before calling ``model.save(image)``.-- .. note::- At least 4 frames are needed to initialize the tracking position.-- """-- name: str = "boxmot_tracker"-- def __init__(- self,- detector: Union[ObjectDetector, str] = "rtdetr_r18vd",- tracker_model_name: str = "DeepOCSORT",- tracker_model_weights: str = "osnet_x0_25_msmt17.pt",- device: str = "cpu",- fp16: bool = False,- **kwargs: Any,- ) -> None:- super().__init__()- if isinstance(detector, str):- if detector.startswith("rtdetr"):- detector = RTDETRDetectorBuilder.build(model_name=detector)- else:- raise ValueError(- f"Detector `{detector}` not available. You may pass an ObjectDetector instance instead."- )- self.detector = detector- os.makedirs(f"{kornia_config.hub_models_dir}/boxmot", exist_ok=True)- self.tracker = getattr(boxmot, tracker_model_name)(- model_weights=Path(os.path.join(f"{kornia_config.hub_models_dir}/boxmot", tracker_model_weights)),- device=device,- fp16=fp16,- **kwargs,- )-- def update(self, image: torch.Tensor) -> None:- """Update the tracker with a new image.-- Args:- image: The input image.-- """- if not (image.ndim == 4 and image.shape[0] == 1) and not image.ndim == 3:- raise ValueError(f"Input torch.Tensor must be of shape (1, 3, H, W) or (3, H, W). Got {image.shape}")-- if image.ndim == 3:- image = image.unsqueeze(0)-- detections_raw: Union[torch.Tensor, list[torch.Tensor]] = self.detector(image)-- detections = detections_raw[0].cpu().numpy() # Batch size is 1-- detections = np.array( # type: ignore- [- detections[:, 2],- detections[:, 3],- detections[:, 2] + detections[:, 4],- detections[:, 3] + detections[:, 5],- detections[:, 1],- detections[:, 0],- ]- ).T-- if detections.shape[0] == 0:- # empty N X (x, y, x, y, conf, cls)- detections = np.empty((0, 6)) # type: ignore-- frame_raw = (tensor_to_image(image) * 255).astype(np.uint8)- # --> M X (x, y, x, y, id, conf, cls, ind)- return self.tracker.update(detections, frame_raw)-- def visualize(self, image: torch.Tensor, show_trajectories: bool = True) -> torch.Tensor:- """Visualize the results of the tracker.-- Args:- image: The input image.- show_trajectories: Whether to show the trajectories.-- Returns:- The image with the results of the tracker.-- """- frame_raw = (tensor_to_image(image) * 255).astype(np.uint8)- self.tracker.plot_results(frame_raw, show_trajectories=show_trajectories)-- return torch.tensor(frame_raw).permute(2, 0, 1)-- def save(self, image: torch.Tensor, show_trajectories: bool = True, directory: Optional[str] = None) -> None:- """Save the model to ONNX format.-- Args:- image: The input image.- show_trajectories: Whether to visualize trajectories.- directory: Where to save the file(s).-- """- if directory is None:- name = f"{self.name}_{datetime.datetime.now(tz=datetime.UTC).strftime('%Y%m%d%H%M%S')!s}"- directory = os.path.join("kornia_outputs", name)- output = self.visualize(image, show_trajectories=show_trajectories)-- os.makedirs(directory, exist_ok=True)- write_image(- os.path.join(directory, f"{str(0).zfill(6)}.jpg"),- output.byte(),- )- _logger.info(f"Outputs are saved in {directory}")diff --git a/kornia/core/external.py b/kornia/core/external.pyindex c90fd1bc5..70e094f58 100644--- a/kornia/core/external.py+++ b/kornia/core/external.py@@ -37,12 +37,13 @@ class LazyLoader:Attributes:module_name: The name of the module to be lazily loaded.module: The actual module object, initialized to None and loaded upon first access.+ extra: The name of the kornia optional-dependency extra that provides the module, if any."""auto_install: bool = False- def __init__(self, module_name: str, dev_dependency: bool = False) -> None:+ def __init__(self, module_name: str, dev_dependency: bool = False, extra: Optional[str] = None) -> None:"""Initialize the LazyLoader with the name of the module.Args:@@ -50,11 +51,21 @@ class LazyLoader:dev_dependency: If the dependency is required in the dev environment.If True, the module will be loaded in the dev environment.If False, the module will not be loaded in the dev environment.+ extra: The name of the kornia optional-dependency extra that installs the module, e.g. ``"onnx"``.+ When set, the "not installed" messages tell the user to run ``pip install "kornia[<extra>]"``."""self.module_name = module_nameself.module: Optional[ModuleType] = Noneself.dev_dependency = dev_dependency+ self.extra = extra++ @property+ def _install_hint(self) -> str:+ """Return the trailing sentence of the "not installed" messages."""+ if self.extra is not None:+ return f'Install it with: pip install "kornia[{self.extra}]".'+ return "Please install it to use this functionality."def _install_package(self, module_name: str) -> None:logger.info(f"Installing `{module_name}` ...")@@ -87,6 +98,7 @@ class LazyLoader:to_ask = Trueif_install = input(f"Optional dependency '{self.module_name}' is not installed. "+ f"{self._install_hint} ""You may silent this prompt by `kornia_config.lazyloader.installation_mode = 'auto'`. ""Do you wish to install the dependency? [Y]es, [N]o, [A]ll.")@@ -102,16 +114,14 @@ class LazyLoader:to_ask = Falseelif if_install.lower() == "n" or if_install.lower() == "no":raise ImportError(- f"Optional dependency '{self.module_name}' is not installed. "- f"Please install it to use this functionality."+ f"Optional dependency '{self.module_name}' is not installed. {self._install_hint}") from eelse:if_install = input("Invalid input. Please enter 'Y', 'N', or 'A'.")elif kornia_config.lazyloader.installation_mode == InstallationMode.RAISE:raise ImportError(- f"Optional dependency '{self.module_name}' is not installed. "- f"Please install it to use this functionality."+ f"Optional dependency '{self.module_name}' is not installed. {self._install_hint}") from eself.module = importlib.import_module(self.module_name)@@ -151,9 +161,6 @@ class LazyLoader:# installation of external modules.numpy = LazyLoader("numpy", dev_dependency=True)PILImage = LazyLoader("PIL.Image", dev_dependency=True)-onnx = LazyLoader("onnx", dev_dependency=True)-diffusers = LazyLoader("diffusers")-transformers = LazyLoader("transformers")-onnxruntime = LazyLoader("onnxruntime")-boxmot = LazyLoader("boxmot")-segmentation_models_pytorch = LazyLoader("segmentation_models_pytorch")+onnx = LazyLoader("onnx", dev_dependency=True, extra="onnx")+diffusers = LazyLoader("diffusers", extra="sd")+onnxruntime = LazyLoader("onnxruntime", extra="onnx")diff --git a/kornia/feature/lightglue_onnx/lightglue.py b/kornia/feature/lightglue_onnx/lightglue.pyindex abd5d1b72..d7dc0352a 100644--- a/kornia/feature/lightglue_onnx/lightglue.py+++ b/kornia/feature/lightglue_onnx/lightglue.py@@ -58,7 +58,9 @@ class OnnxLightGlue:required_data_keys: ClassVar[list[str]] = ["image0", "image1"]def __init__(self, weights: str | None = None, device: Union[str, torch.device, None] = "cpu") -> None:- KORNIA_CHECK(importlib.util.find_spec("onnxruntime") is not None, "onnxruntime is not installed.")+ # An ImportError that names the extra, like the LazyLoader handles raise, rather than a bare check.+ if importlib.util.find_spec("onnxruntime") is None:+ raise ImportError('onnxruntime is not installed. Install it with: pip install "kornia[onnx]".')KORNIA_CHECK(importlib.util.find_spec("numpy") is not None, "numpy is not installed.")device = torch.device(device) # type: ignorediff --git a/kornia/models/segmentation/base.py b/kornia/models/segmentation/base.pyindex 988635f8c..4e60a6a5e 100644--- a/kornia/models/segmentation/base.py+++ b/kornia/models/segmentation/base.py@@ -17,9 +17,10 @@from __future__ import annotations-from typing import ClassVar, Optional, Union+from typing import Any, ClassVar, Optional, Unionimport torch+from torch import nnimport korniafrom kornia.core.external import PILImage as Image@@ -31,12 +32,66 @@ __all__ = ["SemanticSegmentation"]class SemanticSegmentation(ModelBase):"""Semantic Segmentation is a module that wraps a semantic segmentation model.- This module uses SegmentationModel library for semantic segmentation.+ It runs ``pre_processor``, ``model`` and ``post_processor`` in turn on a batch or a list of images.+ :class:`~kornia.models.segmentation.SegmentationModelsBuilder` builds one around a+ ``segmentation_models_pytorch`` network and its encoder's preprocessing.++ Args:+ model: The segmentation network, mapping a ``(B, 3, H, W)`` batch to ``(B, C, H, W)`` predictions.+ :meth:`visualize` expects per-pixel class probabilities (a softmax head); raw logits raise.+ pre_processor: Pre-processing module applied to the input images.+ post_processor: Post-processing module applied to the network output.+ name: Optional name, used by :meth:`save` for file names.+"""ONNX_DEFAULT_INPUTSHAPE: ClassVar[list[int]] = [-1, 3, -1, -1]ONNX_DEFAULT_OUTPUTSHAPE: ClassVar[list[int]] = [-1, -1, -1, -1]+ name: str = "segmentation"++ def __init__(+ self,+ model: nn.Module,+ pre_processor: nn.Module,+ post_processor: nn.Module,+ name: Optional[str] = None,+ ) -> None:+ """Initialize SemanticSegmentation.++ Args:+ model: The segmentation network.+ pre_processor: Pre-processing module applied to the input images.+ post_processor: Post-processing module applied to the network output.+ name: Optional name, used by :meth:`save` for file names.++ """+ super().__init__()+ self.model = model.eval()+ self.pre_processor = pre_processor+ self.post_processor = post_processor+ if name is not None:+ self.name = name++ @staticmethod+ def from_config(config: Any) -> SemanticSegmentation:+ """Build SemanticSegmentation from config.++ This is a placeholder to satisfy the abstract method requirement.+ Use :meth:`SegmentationModelsBuilder.build` or instantiate SemanticSegmentation directly.++ Args:+ config: Configuration object (not used, kept for interface compatibility).++ Returns:+ SemanticSegmentation instance.++ """+ raise NotImplementedError(+ "SemanticSegmentation.from_config() is not implemented. "+ "Use SegmentationModelsBuilder.build() or instantiate SemanticSegmentation directly."+ )+@torch.inference_mode()def forward(self, images: Union[torch.Tensor, list[torch.Tensor]]) -> Union[torch.Tensor, list[torch.Tensor]]:"""Forward pass of the semantic segmentation model.@@ -117,13 +172,23 @@ class SemanticSegmentation(ModelBase):else:raise ValueError(f"Semantic mask must be of shape (C, H, W) or (B, C, H, W), got {semantic_mask.shape}.")- if torch.allclose(- semantic_mask.sum(dim=channel_dim), torch.tensor(1, dtype=semantic_mask.dtype, device=semantic_mask.device)- ):+ # A softmax head sums to one per pixel up to rounding. Allow ``C * eps`` of the mask's dtype: a+ # half-precision sum of ``C`` probabilities is off by about that much, far more than allclose's+ # float32-sized default tolerance, which rejected every float16 and bfloat16 model.+ is_probabilities = False+ if semantic_mask.is_floating_point():+ tol = semantic_mask.shape[channel_dim] * torch.finfo(semantic_mask.dtype).eps+ one = torch.tensor(1, dtype=semantic_mask.dtype, device=semantic_mask.device)+ is_probabilities = torch.allclose(semantic_mask.sum(dim=channel_dim), one, rtol=tol, atol=tol)+ if is_probabilities:+ device, dtype = semantic_mask.device, semantic_mask.dtype# Softmax is used, thus, muliclass segmentationsemantic_mask = semantic_mask.argmax(dim=channel_dim, keepdim=True)- # Create a colormap for each pixel based on the class with the highest probability- output = colors[semantic_mask.squeeze(channel_dim)]+ # Create a colormap for each pixel based on the class with the highest probability. The colormap is+ # generated on the CPU in float32 (a seeded CPU generator keeps it reproducible), so it has to+ # follow the mask's device and dtype before the gather: indexing a CPU tensor with CUDA or MPS+ # indices raises, and the visualization keeps the model's dtype.+ output = colors.to(device=device, dtype=dtype)[semantic_mask.squeeze(channel_dim)]if semantic_mask.dim() == 3:output = output.permute(2, 0, 1)elif semantic_mask.dim() == 4:diff --git a/kornia/models/segmentation/segmentation_models.py b/kornia/models/segmentation/segmentation_models.pyindex d30c655a6..85d550e09 100644--- a/kornia/models/segmentation/segmentation_models.py+++ b/kornia/models/segmentation/segmentation_models.py@@ -23,68 +23,70 @@ import torchfrom torch import nnimport kornia-from kornia.core.external import segmentation_models_pytorch as smp+from kornia.core.check import KORNIA_CHECKfrom .base import SemanticSegmentation__all__ = ["SegmentationModelsBuilder"]+_PREPROC_KEYS = ("input_space", "input_range", "mean", "std")-class SegmentationModelsBuilder:- """Provide a factory to build various semantic segmentation models.- This builder simplifies the creation of models like UNet or DeepLabV3- by providing a unified interface for configuration and weight loading.+class SegmentationModelsBuilder:+ """Wrap a segmentation network and its encoder's preprocessing in a :class:`SemanticSegmentation`.++ The builder is written for networks from `segmentation_models_pytorch+ <https://github.com/qubvel-org/segmentation_models.pytorch>`_ (smp), whose encoders ship the+ preprocessing parameters their pretrained weights expect, but any ``nn.Module`` mapping a+ ``(B, 3, H, W)`` image batch to a ``(B, C, H, W)`` prediction works. Kornia does not import smp:+ you build the network and fetch its preprocessing parameters, and the builder supplies the+ ONNX-friendly preprocessing pipeline and the container. Give the network a softmax head+ (``activation="softmax2d"`` in smp) if you want :meth:`SemanticSegmentation.visualize`: it+ expects per-pixel class probabilities and raises on raw logits.++ Example:+ >>> import segmentation_models_pytorch as smp # doctest: +SKIP+ >>> from kornia.models.segmentation import SegmentationModelsBuilder+ >>> net = smp.Unet(+ ... encoder_name="resnet34", encoder_weights="imagenet", classes=2, activation="softmax2d"+ ... ) # doctest: +SKIP+ >>> params = smp.encoders.get_preprocessing_params("resnet34") # doctest: +SKIP+ >>> model = SegmentationModelsBuilder.build(net, params, name="Unet_resnet34") # doctest: +SKIP+ >>> model(torch.rand(1, 3, 64, 64)).shape # doctest: +SKIP+ torch.Size([1, 2, 64, 64])"""@staticmethoddef build(- model_name: str = "Unet",- encoder_name: str = "resnet34",- encoder_weights: Optional[str] = "imagenet",- in_channels: int = 3,- classes: int = 1,- activation: str = "softmax",- **kwargs: Any,+ model: nn.Module,+ preproc_params: Optional[dict[str, Any]] = None,+ name: str = "segmentation_model",) -> SemanticSegmentation:- """SegmentationModel is a module that wraps a segmentation model.-- This module uses SegmentationModel library for segmentation.+ """Wrap a constructed segmentation network in a :class:`SemanticSegmentation`.Args:- model_name: Name of the model to use. Valid options are:- "Unet", "UnetPlusPlus", "MAnet", "LinkNet", "FPN", "PSPNet", "PAN", "DeepLabV3", "DeepLabV3Plus".- encoder_name: Name of the encoder to use.- encoder_depth: Depth of the encoder.- encoder_weights: Weights of the encoder.- decoder_channels: Number of channels in the decoder.- in_channels: Number of channels in the input.- classes: Number of classes to predict.- activation: Type of activation layer.- **kwargs: Additional arguments to pass to the model. Detailed arguments can be found at:- https://github.com/qubvel-org/segmentation_models.pytorch/tree/main/segmentation_models_pytorch/decoders+ model: The segmentation network, e.g. ``smp.Unet(...)``. It is put in ``eval`` mode.+ preproc_params: The preprocessing parameters of the network's encoder, in the shape+ returned by ``smp.encoders.get_preprocessing_params(encoder_name)``: the keys+ ``input_space`` (``"RGB"`` or ``"BGR"``), ``input_range`` (``[0, 1]`` or ``[0, 255]``),+ ``mean`` and ``std`` (per-channel lists, or ``None`` for no normalization). See+ :meth:`get_preprocessing_pipeline`. ``None`` feeds the input to the network unchanged.+ name: Name of the wrapped model; :meth:`SemanticSegmentation.save` uses it for file names.- Note:- Only encoder weights are available.- Pretrained weights for the whole model are not available.+ Returns:+ The container running preprocessing, the network and an identity post-processor."""- preproc_params = smp.encoders.get_preprocessing_params(encoder_name) # type: ignore- preprocessor = SegmentationModelsBuilder.get_preprocessing_pipeline(preproc_params)- segmentation_model = getattr(smp, model_name)(- encoder_name=encoder_name,- encoder_weights=encoder_weights,- in_channels=in_channels,- classes=classes,- activation=activation,- **kwargs,- )+ if preproc_params is None:+ preprocessor: nn.Module = nn.Identity()+ else:+ preprocessor = SegmentationModelsBuilder.get_preprocessing_pipeline(preproc_params)return SemanticSegmentation(- model=segmentation_model,+ model=model,pre_processor=preprocessor,post_processor=nn.Identity(),- name=f"{model_name}_{encoder_name}",+ name=name,)@staticmethod@@ -92,14 +94,32 @@ class SegmentationModelsBuilder:"""Build the preprocessing pipeline expected by a segmentation model.Args:- preproc_params: Dictionary from the segmentation-model metadata.- It must describe the input color space, value range, mean, and- standard deviation used by the pretrained encoder.+ preproc_params: Dictionary from the segmentation-model metadata, e.g.+ ``smp.encoders.get_preprocessing_params(encoder_name)``. It must carry the keys+ ``input_space`` (``"RGB"`` or ``"BGR"``: the color order the network was trained on,+ so a ``"BGR"`` network gets its RGB input flipped), ``input_range`` (``[0, 1]`` or+ ``[0, 255]``: the range the ``mean``/``std`` are expressed in, so ``[0, 255]``+ multiplies the ``[0, 1]`` input by 255 first), and ``mean`` and ``std`` (per-channel+ lists, or ``None`` for no normalization).Returns::class:`~kornia.augmentation.container.ImageSequential` containingONNX-friendly color conversion, rescaling, and normalization steps.++ Note:+ Set ``pipeline.disable_features = True`` before exporting the returned+ pipeline to ONNX. This disables convenience input/output conversion and+ output caching, whose tensor attribute mutation is rejected by some+ versions of ``torch.export``.++ Raises:+ BaseError: If one of the four keys is missing (a :func:`~kornia.core.check.KORNIA_CHECK`).+ ValueError: If ``input_space`` or ``input_range`` is not one of the supported values.+"""+ for key in _PREPROC_KEYS:+ KORNIA_CHECK(key in preproc_params, f"preproc_params is missing the key '{key}'")+# Ensure the color space transformation is ONNX-friendlyproc_sequence: list[nn.Module] = []input_space = preproc_params["input_space"]@@ -110,10 +130,13 @@ class SegmentationModelsBuilder:else:raise ValueError(f"Unsupported input space: {input_space}")- # Normalize input range if needed+ # Rescale the [0, 1] input to [0, 255] if the network expects it. Multiply by 255, which every+ # dtype stores exactly, rather than divide by the reciprocal: bfloat16 rounds 1/255 to 0.0039368,+ # a ~254.0 multiplier that maps 0.5 to 127.0 instead of 127.5. `Rescale` holds the factor as a+ # 0-d tensor and exports to ONNX from any device.input_range = preproc_params["input_range"]if input_range[1] == 255:- proc_sequence.append(kornia.enhance.Normalize(mean=0.0, std=1 / 255.0))+ proc_sequence.append(kornia.enhance.Rescale(255.0))elif input_range[1] == 1:passelse:diff --git a/pyproject.toml b/pyproject.tomlindex 393c2c10b..c74390922 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -39,16 +39,12 @@ Issues = "https://github.com/kornia/kornia/issues"[project.optional-dependencies]dev = ["coverage",- "diffusers",- "onnx",- "onnxruntime",- "onnxscript",+ "kornia[onnx]","pillow","pre-commit","pytest","pytest-timeout","setuptools", # torch.compile / triton on py3.11 + torch 2.5.1, which does not declare it there- "transformers<5.11",]docs = ["pydata-sphinx-theme>=0.21,<0.22", # _static/css/pydata.css and js/custom.js target theme internals@@ -68,6 +64,8 @@ docs = ["sphinxcontrib-gtagjs","sphinxcontrib-youtube",]+onnx = ["onnx", "onnxruntime", "onnxscript"]+sd = ["diffusers", "transformers"][build-system]requires = ["hatchling"]diff --git a/tests/api_surface_removals.json b/tests/api_surface_removals.jsonindex 0967ef424..6971a1e28 100644--- a/tests/api_surface_removals.json+++ b/tests/api_surface_removals.json@@ -1 +1,8 @@-{}+{+ "kornia.contrib": [+ "BoxMotTracker"+ ],+ "kornia.contrib.boxmot_tracker": [+ "BoxMotTracker"+ ]+}diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex 5d446fa10..4b0e47216 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -5421,6 +5421,11 @@ class TestRandomJPEG(BaseTester):class TestRandomDissolving(BaseTester):torch.manual_seed(0) # for random reproductibility+ @pytest.fixture(autouse=True)+ def _needs_diffusers(self):+ # `diffusers` left the `dev` extra; skip rather than hit the LazyLoader prompt under --runslow.+ pytest.importorskip("diffusers", reason='`diffusers` is not installed: pip install "kornia[sd]"')+def test_batch_proc(self, device, dtype):images = torch.rand(4, 3, 16, 16)aug = RandomDissolving(p=1.0, version="1.5", cache_dir="weights/")diff --git a/tests/core/test_external.py b/tests/core/test_external.pynew file mode 100644index 000000000..8c0ceaf51--- /dev/null+++ b/tests/core/test_external.py@@ -0,0 +1,66 @@+# 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++from kornia.config import InstallationMode, kornia_config+from kornia.core.external import LazyLoader+++class TestLazyLoaderExtra:+ """Check that a missing optional dependency points at the extra that installs it."""++ def test_missing_dependency_names_the_extra(self):+ previous_mode = kornia_config.lazyloader.installation_mode+ kornia_config.lazyloader.installation_mode = InstallationMode.RAISE+ try:+ loader = LazyLoader("definitely_not_a_module_xyz", extra="sd")+ with pytest.raises(ImportError) as excinfo:+ loader.__getattr__("x")+ finally:+ kornia_config.lazyloader.installation_mode = previous_mode++ message = str(excinfo.value)+ assert "Optional dependency 'definitely_not_a_module_xyz' is not installed" in message+ assert 'pip install "kornia[sd]"' in message++ def test_missing_dependency_without_extra_keeps_generic_message(self):+ previous_mode = kornia_config.lazyloader.installation_mode+ kornia_config.lazyloader.installation_mode = InstallationMode.RAISE+ try:+ loader = LazyLoader("definitely_not_a_module_xyz")+ with pytest.raises(ImportError) as excinfo:+ loader.__getattr__("x")+ finally:+ kornia_config.lazyloader.installation_mode = previous_mode++ message = str(excinfo.value)+ assert "Please install it to use this functionality." in message+ assert "kornia[" not in message++ @pytest.mark.parametrize(+ ("name", "extra"),+ [+ ("onnx", "onnx"),+ ("onnxruntime", "onnx"),+ ("diffusers", "sd"),+ ],+ )+ def test_declared_loaders_carry_their_extra(self, name, extra):+ from kornia.core import external++ assert getattr(external, name).extra == extradiff --git a/tests/feature/test_lightglue_onnx.py b/tests/feature/test_lightglue_onnx.pyindex 06adf4c21..83c2c0548 100644--- a/tests/feature/test_lightglue_onnx.py+++ b/tests/feature/test_lightglue_onnx.py@@ -30,6 +30,21 @@ except ImportError:ort = None+def test_missing_onnxruntime_names_the_extra(monkeypatch):+ # Without onnxruntime the constructor must fail the way the LazyLoader handles do: an ImportError that+ # says `pip install "kornia[onnx]"`, which the installation page promises.+ import importlib.util++ real_find_spec = importlib.util.find_spec++ def hide_onnxruntime(name, *args, **kwargs):+ return None if name == "onnxruntime" else real_find_spec(name, *args, **kwargs)++ monkeypatch.setattr(importlib.util, "find_spec", hide_onnxruntime)+ with pytest.raises(ImportError, match=r"kornia\[onnx\]"):+ OnnxLightGlue()++@pytest.mark.skipif(ort is None, reason="OnnxLightGlue requires onnxruntime-gpu")@pytest.mark.skipif(torch_version_le(1, 9, 1), reason="Needs dlpack")class TestOnnxLightGlue:diff --git a/tests/filters/test_dissolving.py b/tests/filters/test_dissolving.pyindex 252d31275..425df0267 100644--- a/tests/filters/test_dissolving.py+++ b/tests/filters/test_dissolving.py@@ -23,6 +23,10 @@ from kornia.filters.dissolving import StableDiffusionDissolvingfrom testing.base import BaseTester+# `StableDiffusionDissolving` lazily imports `diffusers`, which ships in the `kornia[sd]` extra and+# is therefore absent from the default dev environment.+pytest.importorskip("diffusers", reason='`diffusers` is not installed. Install it with: pip install "kornia[sd]"')+WEIGHTS_CACHE_DIR = "weights/"diff --git a/tests/models/test_segmentation_models.py b/tests/models/test_segmentation_models.pynew file mode 100644index 000000000..2eb0f1032--- /dev/null+++ b/tests/models/test_segmentation_models.py@@ -0,0 +1,206 @@+# 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 torch import nn++from kornia.models.segmentation import SegmentationModelsBuilder, SemanticSegmentation++from testing.base import BaseTester++# The dict shape `smp.encoders.get_preprocessing_params("resnet34")` returns.+IMAGENET_PARAMS = {+ "input_space": "RGB",+ "input_range": [0, 1],+ "mean": [0.485, 0.456, 0.406],+ "std": [0.229, 0.224, 0.225],+}+++def _stand_in_network(classes: int = 2) -> nn.Module:+ """A tiny (B, 3, H, W) -> (B, classes, H, W) network standing in for an smp model."""+ return nn.Sequential(nn.Conv2d(3, classes, kernel_size=1), nn.Softmax(dim=1))+++class TestSegmentationModelsBuilder(BaseTester):+ """`build` wraps a user-built network; kornia imports no segmentation package for it."""++ def test_smoke(self, device, dtype):+ net = _stand_in_network()+ model = SegmentationModelsBuilder.build(net, IMAGENET_PARAMS, name="stand_in")+ assert isinstance(model, SemanticSegmentation)+ assert model.name == "stand_in"+ assert model.model is net+ assert not model.model.training+ assert isinstance(model.post_processor, nn.Identity)++ model = model.to(device, dtype)+ images = torch.rand(2, 3, 8, 12, device=device, dtype=dtype)+ out = model(images)+ assert isinstance(out, torch.Tensor)+ assert out.shape == (2, 2, 8, 12)+ assert out.device == images.device and out.dtype == dtype+ assert torch.isfinite(out).all()+ # The softmax head normalizes over the class axis, so the output is not a degenerate map.+ self.assert_close(out.sum(dim=1), torch.ones(2, 8, 12, device=device, dtype=dtype))++ def test_list_input(self, device, dtype):+ model = SegmentationModelsBuilder.build(_stand_in_network(), IMAGENET_PARAMS).to(device, dtype)+ images = [torch.rand(3, 8, 12, device=device, dtype=dtype), torch.rand(3, 6, 6, device=device, dtype=dtype)]+ out = model(images)+ assert isinstance(out, list) and len(out) == 2+ assert out[0].shape == (2, 8, 12) and out[1].shape == (2, 6, 6)+ self.assert_close(out[0], model(images[0][None])[0])++ def test_default_name(self):+ assert SegmentationModelsBuilder.build(_stand_in_network()).name == "segmentation_model"++ def test_none_params_is_identity_preprocessing(self, device, dtype):+ model = SegmentationModelsBuilder.build(_stand_in_network(), preproc_params=None).to(device, dtype)+ assert isinstance(model.pre_processor, nn.Identity)+ images = torch.rand(1, 3, 5, 7, device=device, dtype=dtype)+ self.assert_close(model(images), model.model(images))++ def test_preprocessing_bgr_255(self, device, dtype):+ mean = [0.485, 0.456, 0.406]+ std = [0.229, 0.224, 0.225]+ params = {"input_space": "BGR", "input_range": [0, 255], "mean": mean, "std": std}+ pipeline = SegmentationModelsBuilder.get_preprocessing_pipeline(params).to(device, dtype)++ x = torch.rand(2, 3, 5, 7, device=device, dtype=dtype)+ out = pipeline(x)++ # By hand, in float64: flip the channels, rescale [0, 1] -> [0, 255], then (x - mean) / std per channel.+ # The reference lives on the CPU because MPS has no float64; the comparison brings `out` over to it.+ mean_t = torch.tensor(mean, dtype=torch.float64).view(1, 3, 1, 1)+ std_t = torch.tensor(std, dtype=torch.float64).view(1, 3, 1, 1)+ x64 = x.cpu().to(torch.float64)+ expected = (x64.flip(1) * 255.0 - mean_t) / std_t+ out64 = out.cpu().to(torch.float64)++ assert out.shape == x.shape and out.dtype == dtype and out.device == x.device+ # The pipeline chains three rounding ops in the working dtype at magnitudes up to ~1100, so the+ # accumulated error reaches ~2 eps (measured over 50 draws: 1.9 float32, 1.3 float16, 1.4 bfloat16)+ # while BaseTester's half-precision defaults are rtol ~1 eps and fail here. The pipeline builds its+ # mean/std constants as float32 tensors (float64 ones would change the ONNX graph's output dtype),+ # so a float64 input is only float32-accurate (measured 1.3 float32 eps); floor the tolerance there.+ # Pin the exact math within 8 eps of the coarser of the two.+ tol = 8 * max(torch.finfo(dtype).eps, torch.finfo(torch.float32).eps)+ self.assert_close(out64, expected, rtol=tol, atol=tol)+ # The flip is load-bearing: the un-flipped normalization is a different tensor.+ assert not torch.allclose(out64, (x64 * 255.0 - mean_t) / std_t, rtol=tol, atol=tol)++ def test_preprocessing_255_rescale_is_exact(self, device, dtype):+ # The [0, 1] -> [0, 255] step multiplies by 255, which every dtype stores exactly. A division by+ # the reciprocal is not: bfloat16 stores 1/255 as 0.0039368 and maps 0.5 to 127.0 (127.5 is+ # representable in every dtype here, so equality is the right check).+ params = {"input_space": "RGB", "input_range": [0, 255], "mean": None, "std": None}+ pipeline = SegmentationModelsBuilder.get_preprocessing_pipeline(params).to(device, dtype)+ x = torch.tensor([0.0, 0.5, 1.0], device=device, dtype=dtype).view(1, 3, 1, 1).expand(1, 3, 2, 2)+ expected = torch.tensor([0.0, 127.5, 255.0], device=device, dtype=dtype).view(1, 3, 1, 1).expand(1, 3, 2, 2)+ out = pipeline(x)+ assert out.dtype == dtype and out.device == x.device+ assert torch.equal(out, expected)++ def test_preprocessing_rgb_unit_range(self, device, dtype):+ pipeline = SegmentationModelsBuilder.get_preprocessing_pipeline(IMAGENET_PARAMS).to(device, dtype)+ x = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)+ mean_t = torch.tensor(IMAGENET_PARAMS["mean"], device=device, dtype=dtype).view(1, 3, 1, 1)+ std_t = torch.tensor(IMAGENET_PARAMS["std"], device=device, dtype=dtype).view(1, 3, 1, 1)+ self.assert_close(pipeline(x), (x - mean_t) / std_t)++ def test_preprocessing_no_mean_std_is_identity(self, device, dtype):+ params = {"input_space": "RGB", "input_range": [0, 1], "mean": None, "std": None}+ pipeline = SegmentationModelsBuilder.get_preprocessing_pipeline(params).to(device, dtype)+ x = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)+ self.assert_close(pipeline(x), x)++ @pytest.mark.parametrize("missing", ["input_space", "input_range", "mean", "std"])+ def test_exception_missing_key(self, missing):+ params = {k: v for k, v in IMAGENET_PARAMS.items() if k != missing}+ # Match the KORNIA_CHECK message, not just the key: a bare `KeyError(key)` would match the key too.+ with pytest.raises(Exception, match=f"preproc_params is missing the key '{missing}'"):+ SegmentationModelsBuilder.get_preprocessing_pipeline(params)++ def test_exception_unsupported_input_space(self):+ params = {**IMAGENET_PARAMS, "input_space": "HSV"}+ with pytest.raises(ValueError, match="Unsupported input space: HSV"):+ SegmentationModelsBuilder.get_preprocessing_pipeline(params)++ def test_exception_unsupported_input_range(self):+ params = {**IMAGENET_PARAMS, "input_range": [0, 65535]}+ with pytest.raises(ValueError, match="Unsupported input range"):+ SegmentationModelsBuilder.get_preprocessing_pipeline(params)++ def test_exception_missing_key_with_build(self):+ params = {k: v for k, v in IMAGENET_PARAMS.items() if k != "std"}+ with pytest.raises(Exception, match="preproc_params is missing the key 'std'"):+ SegmentationModelsBuilder.build(_stand_in_network(), params)+++class TestSemanticSegmentation(BaseTester):+ def test_from_config_not_implemented(self):+ with pytest.raises(NotImplementedError, match=r"SegmentationModelsBuilder\.build"):+ SemanticSegmentation.from_config(None)++ def test_visualize(self, device, dtype):+ model = SegmentationModelsBuilder.build(_stand_in_network(3), IMAGENET_PARAMS).to(device, dtype)+ images = torch.rand(2, 3, 6, 6, device=device, dtype=dtype)+ vis = model.visualize(images)+ assert vis.shape == (2, 3, 6, 6)+ # The colormap is drawn on the CPU in float32; the gather has to happen on the mask's device (a CUDA+ # or MPS mask indexing a CPU colormap raised before) and the result keeps the model's device and dtype.+ # The softmax probe tolerates a half-precision sum of probabilities, which allclose's default did not.+ assert vis.device == images.device+ assert vis.dtype == dtype+ assert torch.isfinite(vis).all()+ # Same through the per-image list path, which draws a colormap per mask.+ vis_list = model.visualize([images[0], images[1]])+ assert isinstance(vis_list, list) and len(vis_list) == 2+ assert vis_list[0].shape == (3, 6, 6) and vis_list[0].device == images.device+ self.assert_close(vis_list[0], vis[0])++ def test_visualize_rejects_logits(self, device, dtype):+ # The probe's tolerance scales with the dtype, but a raw-logit head (no softmax) must still be refused.+ logits_net = nn.Conv2d(3, 3, kernel_size=1)+ with torch.no_grad():+ logits_net.weight.mul_(4.0)+ model = SegmentationModelsBuilder.build(logits_net, IMAGENET_PARAMS).to(device, dtype)+ with pytest.raises(ValueError, match="softmax"):+ model.visualize(torch.rand(1, 3, 6, 6, device=device, dtype=dtype))++ 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")+ ort = pytest.importorskip("onnxruntime")+ pytest.importorskip("onnxscript")+ if device.type != "cpu":+ # `Normalize` keeps mean/std as plain tensor attributes that `.to(device)` does not move, so+ # exporting an accelerator-resident pipeline fails on a device mismatch (pre-existing).+ pytest.skip("export of a non-CPU pipeline is blocked by Normalize's tensor attributes")+ params = {**IMAGENET_PARAMS, "input_space": "BGR", "input_range": [0, 255]}+ pipeline = SegmentationModelsBuilder.get_preprocessing_pipeline(params).to(device).eval()+ # Export tensor operations without the convenience I/O cache: torch.export in PyTorch 2.9+ # rejects the `_output_image` tensor attribute created by ImageSequential.__call__.+ pipeline.disable_features = True+ x = torch.rand(1, 3, 6, 6, device=device)+ program = torch.onnx.export(pipeline, (x,), dynamo=True, opset_version=18, verbose=False)+ assert program is not None+ session = ort.InferenceSession(program.model_proto.SerializeToString(), providers=["CPUExecutionProvider"])+ (out,) = session.run(None, {session.get_inputs()[0].name: x.cpu().numpy()})+ self.assert_close(torch.from_numpy(out), pipeline(x).cpu(), rtol=1e-5, atol=1e-5)diff --git a/uv.lock b/uv.lockindex 4fabd2e6c..d4f2c08b0 100644--- a/uv.lock+++ b/uv.lock@@ -815,7 +815,6 @@ dependencies = [[package.optional-dependencies]dev = [{ name = "coverage" },- { name = "diffusers" },{ name = "onnx" },{ name = "onnxruntime" },{ name = "onnxscript" },@@ -824,7 +823,6 @@ dev = [{ name = "pytest" },{ name = "pytest-timeout" },{ name = "setuptools" },- { name = "transformers" },]docs = [{ name = "matplotlib" },@@ -841,18 +839,30 @@ docs = [{ name = "sphinxcontrib-gtagjs" },{ name = "sphinxcontrib-youtube" },]+onnx = [+ { name = "onnx" },+ { name = "onnxruntime" },+ { name = "onnxscript" },+]+sd = [+ { name = "diffusers" },+ { name = "transformers" },+][package.metadata]requires-dist = [{ name = "coverage", marker = "extra == 'dev'" },- { name = "diffusers", marker = "extra == 'dev'" },+ { name = "diffusers", marker = "extra == 'sd'" },{ name = "kornia-rs", specifier = ">=0.1.9" },{ name = "matplotlib", marker = "extra == 'docs'" },{ name = "numpy", specifier = ">=1.21" },{ name = "onnx", marker = "extra == 'dev'" },{ name = "onnx", marker = "extra == 'docs'" },+ { name = "onnx", marker = "extra == 'onnx'" },{ name = "onnxruntime", marker = "extra == 'dev'" },+ { name = "onnxruntime", marker = "extra == 'onnx'" },{ name = "onnxscript", marker = "extra == 'dev'" },+ { name = "onnxscript", marker = "extra == 'onnx'" },{ name = "pillow", marker = "extra == 'dev'" },{ name = "pillow", marker = "extra == 'docs'" },{ name = "pre-commit", marker = "extra == 'dev'" },@@ -870,9 +880,9 @@ requires-dist = [{ name = "sphinxcontrib-gtagjs", marker = "extra == 'docs'" },{ name = "sphinxcontrib-youtube", marker = "extra == 'docs'" },{ name = "torch", specifier = ">=2.5.1" },- { name = "transformers", marker = "extra == 'dev'", specifier = "<5.11" },+ { name = "transformers", marker = "extra == 'sd'" },]-provides-extras = ["dev", "docs"]+provides-extras = ["dev", "docs", "onnx", "sd"][[package]]name = "kornia-rs"