Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Heuristic:Kornia Kornia Lazy Loading Optional Deps

From Leeroopedia




Knowledge Sources
Domains Infrastructure, Software_Design
Last Updated 2026-02-09 15:00 GMT

Overview

Design pattern using LazyLoader to defer importing optional dependencies until first use, reducing startup time and allowing flexible installation modes.

Description

Kornia has many optional dependencies (numpy, PIL, onnx, onnxruntime, diffusers, transformers, boxmot, etc.) that are only needed for specific features. Rather than importing them eagerly at module load time (which would slow startup and require all deps to be installed), Kornia uses a LazyLoader class that creates lightweight proxy objects. These proxies defer the actual import until an attribute is first accessed. The LazyLoader also provides three installation modes: `ASK` (interactive prompt), `AUTO` (automatic pip install), and `RAISE` (strict error).

Usage

Apply this pattern when adding a new optional dependency to Kornia. Instead of `import some_package`, define `some_package = LazyLoader("some_package")` in `kornia/core/external.py`. Use the `dev_dependency=True` flag if the package is required in the development environment (listed in `[project.optional-dependencies] dev`).

The Insight (Rule of Thumb)

  • Action: Define optional imports as `LazyLoader` instances in `kornia/core/external.py` instead of regular imports.
  • Value: Modules with `dev_dependency=True`: numpy, PIL.Image, onnx. Modules without: diffusers, transformers, onnxruntime, boxmot, etc.
  • Trade-off: First access to a lazy-loaded module incurs the import cost (and potentially a pip install). IDE autocompletion may not work on LazyLoader proxies.

Reasoning

A computer vision library like Kornia touches many domains (ONNX deployment, diffusion models, object tracking, multi-framework support). Requiring all these dependencies at install time would make `pip install kornia` pull dozens of heavy packages. The LazyLoader pattern keeps the core install lightweight (only torch, kornia_rs, packaging) while making extended features available on demand. The three installation modes give users control over whether missing deps are auto-installed, prompted, or treated as errors.

Code Evidence

LazyLoader definitions from `kornia/core/external.py:152-163`:

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")
basicsr = LazyLoader("basicsr")
requests = LazyLoader("requests")
ivy = LazyLoader("ivy")

Installation mode configuration from `kornia/config.py:25-33`:

class InstallationMode(str, Enum):
    """Represent the installation mode for external dependencies."""
    ASK = "ASK"    # Ask the user if to install the dependencies
    AUTO = "AUTO"  # Install the dependencies
    RAISE = "RAISE"  # Raise an error if the dependencies are not installed

Sphinx/doctest detection to skip lazy loading from `kornia/core/external.py:69-78`:

if not self.dev_dependency:
    if "--doctest-modules" in sys.argv:
        logger.info(f"Doctest detected, skipping loading of '{self.module_name}'")
        return
    try:
        if __sphinx_build__:
            logger.info(f"Sphinx detected, skipping loading of '{self.module_name}'")
            return
    except NameError:
        pass

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment