π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix: finish optional dependency cleanup (#4464)
victorwon2001d7954532ac0b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e8db3a354..2478b1728 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+* Optional-dependency extra `kornia[image]` installs Pillow for PIL-backed image input/output,+ display helpers and `kornia.io.sample`; missing-Pillow errors now name the extra to install, and the unused+ `DinoVisionTransformer.forward_features_list` list path has been removed. (#4464)* Documented the shared 2D contract of `kornia.augmentation` β the `(B, C, H, W)` float working layoutand `keepdim`, `p` / `p_batch` / `same_on_batch`, where random parameters are drawn and how `torch.manual_seed`and `params=` replay them, what a module serializes, and what `AugmentationSequential` does with each data keydiff --git a/docs/source/get-started/installation.rst b/docs/source/get-started/installation.rstindex a64a40c91..9844df309 100644--- a/docs/source/get-started/installation.rst+++ b/docs/source/get-started/installation.rst@@ -56,10 +56,7 @@ so you only pay for the ones you use. If one of the extras below is missing, theobject tells you which extra to install: by default it offers to install the package for you on theterminal (``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).+is declined, it raises an ``ImportError`` naming the extra... list-table:::header-rows: 1@@ -68,6 +65,9 @@ message only asks you to install the package* - Extra- What it enables- Install command+ * - ``image``+ - Pillow-backed PIL input/output and display helpers, plus remote image decoding in :func:`kornia.io.get_sample_images`+ - ``pip install "kornia[image]"``* - ``onnx``- :doc:`kornia.onnx </onnx>`, ONNX export of Kornia modules, and :class:`~kornia.feature.OnnxLightGlue`- ``pip install "kornia[onnx]"``@@ -81,11 +81,6 @@ message only asks you to install the package- 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/kornia/core/external.py b/kornia/core/external.pyindex 55ec89460..6e7793f8d 100644--- a/kornia/core/external.py+++ b/kornia/core/external.py@@ -160,7 +160,7 @@ class LazyLoader:# may set the module name to `autodoc_mock_imports` in conf.py to avoid undesired# installation of external modules.numpy = LazyLoader("numpy", dev_dependency=True)-PILImage = LazyLoader("PIL.Image", dev_dependency=True)+PILImage = LazyLoader("PIL.Image", dev_dependency=True, extra="image")onnx = LazyLoader("onnx", dev_dependency=True, extra="onnx")diffusers = LazyLoader("diffusers", extra="sd")onnxruntime = LazyLoader("onnxruntime", extra="onnx")diff --git a/kornia/feature/dedode/transformer/dinov2.py b/kornia/feature/dedode/transformer/dinov2.pyindex 3c045c578..186f70f01 100644--- a/kornia/feature/dedode/transformer/dinov2.py+++ b/kornia/feature/dedode/transformer/dinov2.py@@ -261,47 +261,16 @@ class DinoVisionTransformer(nn.Module):return x- def forward_features_list(self, x_list, masks_list):- """Compute transformer features for a list of image tensors.-- Args:- x_list: List of input image tensors, each with shape :math:`(B, C, H, W)`.- masks_list: List of optional boolean mask tensors matching each image in ``x_list``.-- Returns:- List of intermediate feature dictionaries, one per input image tensor.- """- x = [self.prepare_tokens_with_masks(x, masks) for x, masks in zip(x_list, masks_list)]- for blk in self.blocks:- x = blk(x)-- all_x = x- output = []- for x, masks in zip(all_x, masks_list):- x_norm = self.norm(x)- output.append(- {- "x_norm_clstoken": x_norm[:, 0],- "x_norm_patchtokens": x_norm[:, 1:],- "x_prenorm": x,- "masks": masks,- }- )- return output-def forward_features(self, x, masks=None):"""Compute transformer features for one image tensor.Args:- x: Input image tensor with shape :math:`(B, C, H, W)`, or list of tensors.+ x: Input image tensor with shape :math:`(B, C, H, W)`.masks: Optional boolean mask tensor with shape :math:`(B, N)` or ``None``.Returns:Feature dictionary with keys ``x_norm_clstoken``, ``x_norm_patchtokens``, ``x_prenorm``, and ``masks``."""- if isinstance(x, list):- return self.forward_features_list(x, masks)-x = self.prepare_tokens_with_masks(x, masks)for blk in self.blocks:diff --git a/pyproject.toml b/pyproject.tomlindex 33fcc8c4f..162ace620 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -64,6 +64,7 @@ docs = ["sphinxcontrib-gtagjs","sphinxcontrib-youtube",]+image = ["pillow"]onnx = ["onnx", "onnxruntime", "onnxscript"]sd = ["diffusers", "transformers"]diff --git a/tests/core/test_external.py b/tests/core/test_external.pyindex 8c0ceaf51..6995fce59 100644--- a/tests/core/test_external.py+++ b/tests/core/test_external.py@@ -55,6 +55,7 @@ class TestLazyLoaderExtra:@pytest.mark.parametrize(("name", "extra"),[+ ("PILImage", "image"),("onnx", "onnx"),("onnxruntime", "onnx"),("diffusers", "sd"),diff --git a/tests/feature/test_dedode.py b/tests/feature/test_dedode.pyindex af3e37f80..143714201 100644--- a/tests/feature/test_dedode.py+++ b/tests/feature/test_dedode.py@@ -22,6 +22,7 @@ import torchfrom kornia.feature.dedode import DeDoDefrom kornia.feature.dedode.decoder import ConvRefiner+from kornia.feature.dedode.transformer.dinov2 import DinoVisionTransformerfrom kornia.feature.dedode.transformer.layers import MemEffAttention, NestedTensorBlockfrom testing.base import BaseTester@@ -75,6 +76,29 @@ class TestNestedTensorBlock(BaseTester):block([x])+class TestDinoVisionTransformer(BaseTester):+ def test_forward_features_tensor(self, device, dtype):+ model = DinoVisionTransformer(+ img_size=8,+ patch_size=4,+ embed_dim=8,+ depth=1,+ num_heads=2,+ mlp_ratio=2,+ block_chunks=0,+ ).to(device, dtype)+ x = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)+ masks = torch.zeros(2, 4, device=device, dtype=torch.bool)++ features = model.forward_features(x, masks)++ assert set(features) == {"x_norm_clstoken", "x_norm_patchtokens", "x_prenorm", "masks"}+ assert features["x_norm_clstoken"].shape == (2, 8)+ assert features["x_norm_patchtokens"].shape == (2, 4, 8)+ assert features["x_prenorm"].shape == (2, 5, 8)+ assert features["masks"] is masks++@pytest.mark.skip(reason="DeDoDe is ummaintained")class TestDeDoDe:@pytest.mark.slowdiff --git a/tests/test_declared_imports.py b/tests/test_declared_imports.pyindex 721d76dbd..7b09a55f7 100644--- a/tests/test_declared_imports.py+++ b/tests/test_declared_imports.py@@ -41,10 +41,9 @@ takes to develop kornia, and something a user runs must not need them.The allowed set is *derived* from ``pyproject.toml`` and from the ``LazyLoader`` registry ratherthan hardcoded: adding a dependency in the usual place is all it takes to satisfy these tests.The literals are the handful of distribution names whose import name differs-(:data:`DIST_TO_IMPORT`), :data:`CONTRIBUTOR_EXTRAS`, :data:`IMPLICIT_ALLOWED`, the tolerated-orphans in :data:`LAZY_LOADERS_WITHOUT_DECLARED_DEP` (each with a reason, and checked for-staleness) and the :data:`AUDIT_EAGER_IMPORTS` canaries. The ``LazyLoader`` registry means the-module-level instances in ``kornia.core.external``; a loader constructed anywhere else is not seen.+(:data:`DIST_TO_IMPORT`), :data:`CONTRIBUTOR_EXTRAS`, :data:`IMPLICIT_ALLOWED` and the+:data:`AUDIT_EAGER_IMPORTS` canaries. The ``LazyLoader`` registry means the module-level instances+in ``kornia.core.external``; a loader constructed anywhere else is not seen.Deliberately no ``packaging`` import: it is not a kornia dependency, and this file must pass on abare ``pip install -e ".[dev]"``.@@ -86,17 +85,6 @@ IMPLICIT_ALLOWED: frozenset[str] = frozenset()# on them, so they do not make a package "declared". Every other extra is user-facing and does.CONTRIBUTOR_EXTRAS = frozenset({"dev", "docs"})-# ``LazyLoader`` modules that no user-facing dependency installs, mapped to the reason they are-# tolerated. Every entry is a package a user can hit at runtime with no documented way to install-# it, so each one is a bug waiting on a decision rather than a design.-LAZY_LOADERS_WITHOUT_DECLARED_DEP: dict[str, str] = {- "PIL.Image": (- "pillow is declared only in the dev/docs extras; ImageModule output_type='pil' and "- "kornia.io.sample need it at runtime; which user-facing extra should carry it is an open "- "decision (#4261)"- ),-}-# Packages the kornia#4259 audit found ``import kornia`` loading eagerly. None is declared any more, so# test 1 forbids importing them from ``kornia/``; the import probe still watches for them as a canary# for a transitive load, next to every package a user-facing extra or a ``LazyLoader`` provides.@@ -237,20 +225,12 @@ def test_every_lazy_loader_module_is_installable():declared = _declared_import_names() | IMPLICIT_ALLOWEDorphans = {name: top for name, top in _lazy_loader_modules().items() if top not in declared}- unexpected = sorted(set(orphans) - set(LAZY_LOADERS_WITHOUT_DECLARED_DEP))- assert not unexpected, (+ assert not orphans, ("kornia.core.external declares LazyLoader(s) whose module no runtime dependency and no ""user-facing optional-dependency extra installs, so users have no documented way to get ""them: "- + ", ".join(f"{name} -> {orphans[name]}" for name in unexpected)- + ". Add the package to a user-facing optional-dependencies extra (and pass extra= to the "- "LazyLoader), or record it in LAZY_LOADERS_WITHOUT_DECLARED_DEP with a reason."- )-- stale = sorted(set(LAZY_LOADERS_WITHOUT_DECLARED_DEP) - set(orphans))- assert not stale, (- "LAZY_LOADERS_WITHOUT_DECLARED_DEP lists LazyLoader(s) that are now declared (or gone); "- "drop the entries: " + ", ".join(stale)+ + ", ".join(f"{name} -> {top}" for name, top in sorted(orphans.items()))+ + ". Add the package to a user-facing optional-dependencies extra and pass extra= to the LazyLoader.")diff --git a/uv.lock b/uv.lockindex 1030f14e4..fbb94b326 100644--- a/uv.lock+++ b/uv.lock@@ -839,6 +839,9 @@ docs = [{ name = "sphinxcontrib-gtagjs" },{ name = "sphinxcontrib-youtube" },]+image = [+ { name = "pillow" },+]onnx = [{ name = "onnx" },{ name = "onnxruntime" },@@ -865,6 +868,7 @@ requires-dist = [{ name = "onnxscript", marker = "extra == 'onnx'" },{ name = "pillow", marker = "extra == 'dev'" },{ name = "pillow", marker = "extra == 'docs'" },+ { name = "pillow", marker = "extra == 'image'" },{ name = "pre-commit", marker = "extra == 'dev'" },{ name = "pydata-sphinx-theme", marker = "extra == 'docs'", specifier = ">=0.21,<0.22" },{ name = "pytest", marker = "extra == 'dev'" },@@ -882,7 +886,7 @@ requires-dist = [{ name = "torch", specifier = ">=2.5.1" },{ name = "transformers", marker = "extra == 'sd'" },]-provides-extras = ["dev", "docs", "onnx", "sd"]+provides-extras = ["dev", "docs", "image", "onnx", "sd"][[package]]name = "kornia-rs"