Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).

### Fixed

- 🐞 **model**: Warn when checkpoint and model arguments differ by @varunikarai in https://github.com/open-edge-platform/anomalib/pull/3846

## [v2.8.0] - 2026-11-27

### Added
Expand Down
72 changes: 70 additions & 2 deletions src/anomalib/models/components/base/anomalib_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
from anomalib.metrics.evaluator import Evaluator
from anomalib.post_processing import PostProcessor
from anomalib.pre_processing import PreProcessor
from anomalib.utils.path import paths_to_strings
from anomalib.utils.path import PathValue, paths_to_strings
from anomalib.utils.serialization import anomalib_safe_globals
from anomalib.visualization import ImageVisualizer, Visualizer

Expand All @@ -69,6 +69,50 @@
logger = logging.getLogger(__name__)


def _lists_to_tuples(value: object) -> object:
"""Convert lists nested in a hyperparameter value to tuples.

Configuration files produce lists where Python code usually passes tuples,
for example PatchCore's ``layers``. Both describe the same model, so they
are made equal before comparison.

Args:
value (object): Hyperparameter value from a checkpoint or a live model.

Returns:
object: The value with every list and tuple converted to a tuple.
"""
if isinstance(value, (list, tuple)):
return tuple(_lists_to_tuples(item) for item in value)
if isinstance(value, dict):
return {key: _lists_to_tuples(item) for key, item in value.items()}
return value


def _hyperparameters_match(saved: PathValue, current: PathValue) -> bool:
"""Check whether a saved hyperparameter matches the live model's value.

Paths are compared as strings, as they are stored in checkpoints, and lists
are compared as tuples. Values that cannot be reduced to a single boolean,
such as multi-element tensors, are treated as matching so that no false
warning is raised.

Args:
saved (PathValue): Value stored in the checkpoint.
current (PathValue): Value on the model instance.

Returns:
bool: ``True`` if the values are equivalent or cannot be compared.
"""
try:
# ``==`` on tensors and arrays is elementwise, and ``bool()`` of the result raises
# ``RuntimeError`` for tensors and ``ValueError`` for arrays.
matches = bool(_lists_to_tuples(paths_to_strings(saved)) == _lists_to_tuples(paths_to_strings(current)))
except (RuntimeError, ValueError):
return True

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When do you expect a Runtime, Type, or a Value error, and is returning True safe?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I removed TypeError (637e9d2) and now only catch the two errors that tensor and array comparisons actually raise: RuntimeError when a hyperparameter is a multi-element tensor (== is elementwise and bool() on the result raises), and ValueError for the same case with numpy arrays. Returning True only means no warning is logged for that argument. Checkpoint loading behaves exactly the same, so the worst case is a missed warning, not a wrong model. This is covered by test_values_without_a_single_truth_value_are_treated_as_matching (d933105). Happy to switch to torch.equal / np.array_equal for those types if you'd prefer they get compared too.

return matches


class AnomalibModule(ExportMixin, pl.LightningModule, ABC):
"""Base class for all anomaly detection modules in anomalib.

Expand Down Expand Up @@ -199,14 +243,38 @@ def on_save_checkpoint(self, checkpoint: dict[str, Any]) -> None:
)

def on_load_checkpoint(self, checkpoint: dict[str, Any]) -> None:
"""Restore component configuration from safe plain data."""
"""Restore component configuration and report constructor argument mismatches."""
super().on_load_checkpoint(checkpoint)
self._warn_on_hyperparameter_mismatch(checkpoint.get("hyper_parameters"))
self._restore_component_enabled_flags(checkpoint.get("anomalib_components_enabled"))
for checkpoint_key, component in self._checkpointable_components().items():
config = checkpoint.get(checkpoint_key)
if config is not None and hasattr(component, "load_checkpoint_config"):
component.load_checkpoint_config(config)

def _warn_on_hyperparameter_mismatch(self, saved: dict[str, Any] | None) -> None:
"""Warn when a checkpoint was saved with different constructor arguments.

Args:
saved (dict[str, Any] | None): ``hyper_parameters`` from the
checkpoint, or ``None`` if the checkpoint has none.
"""
if not saved:
return
current = dict(self.hparams)
# ``pre_trained`` only chooses the initial weights, which the checkpoint's
# ``state_dict`` replaces, so a different value is expected.
compared = (saved.keys() & current.keys()) - {"pre_trained"}
# Only names are logged: values can be secrets, such as ``api_key`` in ``VlmAd``.
mismatches = [key for key in sorted(compared) if not _hyperparameters_match(saved[key], current[key])]
if not mismatches:
return
logger.warning(
"%s was created with arguments that differ from the checkpoint: %s",
self.__class__.__name__,
", ".join(mismatches),
)

def _restore_component_enabled_flags(self, flags: dict[str, bool] | None) -> None:
"""Apply plain-boolean enable/disable flags saved with the checkpoint.

Expand Down
139 changes: 138 additions & 1 deletion tests/unit/engine/test_checkpoint_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@

"""Tests for AnomalibCheckpointIO and Engine plugin installation."""

import logging
from enum import Enum
from pathlib import Path
from typing import Any

import numpy as np
import pytest
import torch
from lightning.fabric.plugins.io.torch_io import TorchCheckpointIO
Expand All @@ -18,8 +20,9 @@
from anomalib import LearningType, PrecisionType
from anomalib.engine import Engine
from anomalib.engine.plugins import AnomalibCheckpointIO
from anomalib.models import Padim
from anomalib.models import Padim, Patchcore
from anomalib.models.components.base import AnomalibModule
from anomalib.models.components.base.anomalib_module import _hyperparameters_match
from anomalib.models.image.efficient_ad import EfficientAd
from anomalib.models.image.efficient_ad.torch_model import EfficientAdModelSize
from anomalib.models.image.super_add import SuperADDPostProcessor
Expand Down Expand Up @@ -367,3 +370,137 @@ def __init__(self) -> None:
model.on_save_checkpoint(checkpoint)

assert checkpoint["anomalib_pre_processor_config"] == {"transform": None}


_MODULE_LOGGER = "anomalib.models.components.base.anomalib_module"
_MISMATCH_MESSAGE = "differ from the checkpoint"


def _save_checkpoint(model: AnomalibModule, checkpoint_path: Path) -> Path:
"""Save ``model`` to ``checkpoint_path`` the way the trainer does."""
trainer = Trainer(max_epochs=1, logger=False, barebones=True)
trainer.strategy.connect(model)
trainer.save_checkpoint(checkpoint_path)
return checkpoint_path


def test_hyperparameter_mismatch_is_logged_on_load(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
"""Loading weights into a model built with other arguments names every mismatch.

This is the ``Engine.predict(model=..., ckpt_path=...)`` path: Lightning loads
the checkpoint into the caller's instance, so ``num_neighbors`` keeps its
default of 9 although the checkpoint was trained with 2.
"""
checkpoint_path = _save_checkpoint(
Patchcore(backbone="resnet18", pre_trained=False, num_neighbors=2),
tmp_path / "patchcore.ckpt",
)
checkpoint = AnomalibCheckpointIO().load_checkpoint(checkpoint_path, weights_only=True)
model = Patchcore(backbone="resnet18", pre_trained=False)

with caplog.at_level(logging.WARNING, logger=_MODULE_LOGGER):
model.on_load_checkpoint(checkpoint)

assert "differ from the checkpoint: num_neighbors" in caplog.text


def test_matching_hyperparameters_are_not_logged(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
"""No warning when the model is created with the checkpoint's arguments."""
checkpoint_path = _save_checkpoint(
Patchcore(backbone="resnet18", pre_trained=False, num_neighbors=2),
tmp_path / "patchcore.ckpt",
)
checkpoint = AnomalibCheckpointIO().load_checkpoint(checkpoint_path, weights_only=True)
model = Patchcore(backbone="resnet18", pre_trained=False, num_neighbors=2)

with caplog.at_level(logging.WARNING, logger=_MODULE_LOGGER):
model.on_load_checkpoint(checkpoint)

assert _MISMATCH_MESSAGE not in caplog.text


def test_load_from_checkpoint_restores_arguments_silently(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
"""``load_from_checkpoint`` rebuilds the model from the saved arguments, so nothing differs."""
checkpoint_path = _save_checkpoint(
Patchcore(backbone="resnet18", pre_trained=False, num_neighbors=2),
tmp_path / "patchcore.ckpt",
)

with caplog.at_level(logging.WARNING, logger=_MODULE_LOGGER):
loaded = Patchcore.load_from_checkpoint(checkpoint_path, weights_only=True)

assert loaded.model.num_neighbors == 2
assert _MISMATCH_MESSAGE not in caplog.text


def test_list_and_tuple_hyperparameters_are_equivalent(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
"""``layers`` passed as a list (as from a config file) matches the saved tuple."""
checkpoint_path = _save_checkpoint(
Patchcore(backbone="resnet18", pre_trained=False, layers=("layer2", "layer3")),
tmp_path / "patchcore.ckpt",
)
checkpoint = AnomalibCheckpointIO().load_checkpoint(checkpoint_path, weights_only=True)
model = Patchcore(backbone="resnet18", pre_trained=False, layers=["layer2", "layer3"])

with caplog.at_level(logging.WARNING, logger=_MODULE_LOGGER):
model.on_load_checkpoint(checkpoint)

assert _MISMATCH_MESSAGE not in caplog.text


def test_checkpoint_without_hyperparameters_is_not_logged(caplog: pytest.LogCaptureFixture) -> None:
"""Checkpoints that carry no ``hyper_parameters`` load without a warning."""
model = Patchcore(backbone="resnet18", pre_trained=False)

with caplog.at_level(logging.WARNING, logger=_MODULE_LOGGER):
model.on_load_checkpoint({"state_dict": {}})

assert _MISMATCH_MESSAGE not in caplog.text


def test_pre_trained_difference_is_not_logged(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
"""``pre_trained`` only picks the initial weights, which the checkpoint replaces.

Building the model with ``pre_trained=False`` before loading a checkpoint is a
common way to skip downloading backbone weights, so it must not be reported.
"""
checkpoint_path = _save_checkpoint(
Patchcore(backbone="resnet18", pre_trained=False),
tmp_path / "patchcore.ckpt",
)
checkpoint = AnomalibCheckpointIO().load_checkpoint(checkpoint_path, weights_only=True)
checkpoint["hyper_parameters"]["pre_trained"] = True # as if trained from ImageNet weights
model = Patchcore(backbone="resnet18", pre_trained=False)

with caplog.at_level(logging.WARNING, logger=_MODULE_LOGGER):
model.on_load_checkpoint(checkpoint)

assert _MISMATCH_MESSAGE not in caplog.text


@pytest.mark.parametrize(
("saved", "current"),
[
pytest.param(torch.tensor([1.0, 2.0]), torch.tensor([3.0, 4.0]), id="tensor"),
pytest.param(np.array([1.0, 2.0]), np.array([3.0, 4.0]), id="array"),
],
)
def test_values_without_a_single_truth_value_are_treated_as_matching(saved: object, current: object) -> None:
"""Multi-element tensors and arrays are skipped rather than reported, even when they differ.

``==`` compares them elementwise, so the result has no single truth value.
No built-in model takes such an argument; this keeps a custom one loadable.
"""
assert _hyperparameters_match(saved, current)


def test_mismatch_warning_does_not_log_argument_values(caplog: pytest.LogCaptureFixture) -> None:
"""Only argument names are logged, so a secret such as ``VlmAd``'s ``api_key`` never reaches the logs."""
model = VlmAd(model=ModelName.GPT_4O_MINI, api_key="current-dummy-key")
saved = {**model.hparams, "api_key": "saved-dummy-key"}

with caplog.at_level(logging.WARNING, logger=_MODULE_LOGGER):
model.on_load_checkpoint({"hyper_parameters": saved})

assert "differ from the checkpoint: api_key" in caplog.text
assert "dummy-key" not in caplog.text