From a19599e582eef4295349b5b09b5c744f9f5f09cd Mon Sep 17 00:00:00 2001 From: Varunika Rai Date: Wed, 14 Oct 2026 16:17:54 +0530 Subject: [PATCH 1/9] fix(model): warn when a checkpoint is loaded into a model built with different arguments Signed-off-by: Varunika Rai --- .../models/components/base/anomalib_module.py | 94 ++++++++++++++- tests/unit/engine/test_checkpoint_io.py | 109 +++++++++++++++++- 2 files changed, 199 insertions(+), 4 deletions(-) diff --git a/src/anomalib/models/components/base/anomalib_module.py b/src/anomalib/models/components/base/anomalib_module.py index e273c14620..633b176e19 100644 --- a/src/anomalib/models/components/base/anomalib_module.py +++ b/src/anomalib/models/components/base/anomalib_module.py @@ -43,8 +43,8 @@ import logging from abc import ABC, abstractmethod from collections.abc import Callable, Sequence -from pathlib import Path -from typing import Any +from pathlib import Path, PurePath +from typing import Any, ClassVar import lightning.pytorch as pl import torch @@ -69,6 +69,49 @@ logger = logging.getLogger(__name__) +def _comparable_hyperparameter(value: object) -> object: + """Normalize a hyperparameter value so equivalent values compare equal. + + Checkpoints store paths as strings, and configuration files produce lists + where Python code usually passes tuples. Neither difference changes what the + model does, so both are normalized before comparison. + + Args: + value (object): Hyperparameter value from a checkpoint or a live model. + + Returns: + object: The value with paths converted to strings and lists to tuples. + """ + if isinstance(value, PurePath): + return str(value) + if isinstance(value, (list, tuple)): + return tuple(_comparable_hyperparameter(item) for item in value) + if isinstance(value, dict): + return {key: _comparable_hyperparameter(item) for key, item in value.items()} + return value + + +def _hyperparameters_match(saved: object, current: object) -> bool: + """Check whether a saved hyperparameter matches the live model's value. + + 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 (object): Value stored in the checkpoint. + current (object): Value on the model instance. + + Returns: + bool: ``True`` if the values are equivalent or cannot be compared. + """ + try: + # ``==`` on tensors and arrays is elementwise; ``bool()`` raises for them. + matches = bool(_comparable_hyperparameter(saved) == _comparable_hyperparameter(current)) + except (RuntimeError, TypeError, ValueError): + return True + return matches + + class AnomalibModule(ExportMixin, pl.LightningModule, ABC): """Base class for all anomaly detection modules in anomalib. @@ -122,6 +165,11 @@ class AnomalibModule(ExportMixin, pl.LightningModule, ABC): ... ) """ + # Constructor arguments that only choose the initial weights. A checkpoint's + # ``state_dict`` replaces those weights, so a different value when loading a + # checkpoint is expected and not reported as a mismatch. + _HYPERPARAMETERS_REPLACED_BY_WEIGHTS: ClassVar[frozenset[str]] = frozenset({"pre_trained"}) + def __init__( self, pre_processor: nn.Module | bool = True, @@ -199,14 +247,54 @@ 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. + + ``load_from_checkpoint`` rebuilds the model from the saved + ``hyper_parameters``. Loading a checkpoint into an existing instance, + for example through ``Engine.predict(model=..., ckpt_path=...)``, only + restores the weights. Arguments kept as plain attributes, such as + ``num_neighbors`` in PatchCore, then keep the instance's values, and the + scores no longer match the thresholds and normalization statistics + stored in the checkpoint. Only arguments present in both the checkpoint + and the model are compared, and arguments listed in + ``_HYPERPARAMETERS_REPLACED_BY_WEIGHTS`` are skipped. + + 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) + compared = (saved.keys() & current.keys()) - self._HYPERPARAMETERS_REPLACED_BY_WEIGHTS + mismatches = [ + f"{key}={current[key]!r} (checkpoint: {saved[key]!r})" + 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. The model runs with the current " + "values. Differences in arguments that only affect training are harmless, but differences in " + "arguments used at inference make scores inconsistent with the thresholds and normalization " + "statistics saved in the checkpoint. Use %s.load_from_checkpoint(...) or create the model with the " + "same arguments.", + self.__class__.__name__, + ", ".join(mismatches), + self.__class__.__name__, + ) + def _restore_component_enabled_flags(self, flags: dict[str, bool] | None) -> None: """Apply plain-boolean enable/disable flags saved with the checkpoint. diff --git a/tests/unit/engine/test_checkpoint_io.py b/tests/unit/engine/test_checkpoint_io.py index 463ba28c09..d943e3f848 100644 --- a/tests/unit/engine/test_checkpoint_io.py +++ b/tests/unit/engine/test_checkpoint_io.py @@ -3,6 +3,7 @@ """Tests for AnomalibCheckpointIO and Engine plugin installation.""" +import logging from enum import Enum from pathlib import Path from typing import Any @@ -18,7 +19,7 @@ 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.image.efficient_ad import EfficientAd from anomalib.models.image.efficient_ad.torch_model import EfficientAdModelSize @@ -367,3 +368,109 @@ 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 "num_neighbors=9 (checkpoint: 2)" 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 From d570bda090111f331c4306a4668dbd9f8d588961 Mon Sep 17 00:00:00 2001 From: Varunika Rai Date: Wed, 14 Oct 2026 18:09:23 +0530 Subject: [PATCH 2/9] docs(changelog): add entry for #3846 Signed-off-by: Varunika Rai --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ce510b09aa..ac8edb69d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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.7.0] - 2026-10-06 ### Added From 4fd598289c20acec936e39d2ce2bb25e230f6b8d Mon Sep 17 00:00:00 2001 From: Varunika Rai Date: Tue, 20 Oct 2026 22:00:37 +0530 Subject: [PATCH 3/9] refactor(model): skip pre_trained inline instead of through a class constant Signed-off-by: Varunika Rai --- .../models/components/base/anomalib_module.py | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/src/anomalib/models/components/base/anomalib_module.py b/src/anomalib/models/components/base/anomalib_module.py index 633b176e19..b3fbc4c4b8 100644 --- a/src/anomalib/models/components/base/anomalib_module.py +++ b/src/anomalib/models/components/base/anomalib_module.py @@ -44,7 +44,7 @@ from abc import ABC, abstractmethod from collections.abc import Callable, Sequence from pathlib import Path, PurePath -from typing import Any, ClassVar +from typing import Any import lightning.pytorch as pl import torch @@ -165,11 +165,6 @@ class AnomalibModule(ExportMixin, pl.LightningModule, ABC): ... ) """ - # Constructor arguments that only choose the initial weights. A checkpoint's - # ``state_dict`` replaces those weights, so a different value when loading a - # checkpoint is expected and not reported as a mismatch. - _HYPERPARAMETERS_REPLACED_BY_WEIGHTS: ClassVar[frozenset[str]] = frozenset({"pre_trained"}) - def __init__( self, pre_processor: nn.Module | bool = True, @@ -266,8 +261,7 @@ def _warn_on_hyperparameter_mismatch(self, saved: dict[str, Any] | None) -> None ``num_neighbors`` in PatchCore, then keep the instance's values, and the scores no longer match the thresholds and normalization statistics stored in the checkpoint. Only arguments present in both the checkpoint - and the model are compared, and arguments listed in - ``_HYPERPARAMETERS_REPLACED_BY_WEIGHTS`` are skipped. + and the model are compared, and ``pre_trained`` is skipped. Args: saved (dict[str, Any] | None): ``hyper_parameters`` from the @@ -276,7 +270,9 @@ def _warn_on_hyperparameter_mismatch(self, saved: dict[str, Any] | None) -> None if not saved: return current = dict(self.hparams) - compared = (saved.keys() & current.keys()) - self._HYPERPARAMETERS_REPLACED_BY_WEIGHTS + # ``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"} mismatches = [ f"{key}={current[key]!r} (checkpoint: {saved[key]!r})" for key in sorted(compared) From 8a18541fbe48d8225b2a36e4e10d94dc34afb642 Mon Sep 17 00:00:00 2001 From: Varunika Rai Date: Tue, 20 Oct 2026 22:01:46 +0530 Subject: [PATCH 4/9] refactor(model): reuse paths_to_strings when comparing checkpoint arguments Signed-off-by: Varunika Rai --- .../models/components/base/anomalib_module.py | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/src/anomalib/models/components/base/anomalib_module.py b/src/anomalib/models/components/base/anomalib_module.py index b3fbc4c4b8..c33e722ec9 100644 --- a/src/anomalib/models/components/base/anomalib_module.py +++ b/src/anomalib/models/components/base/anomalib_module.py @@ -43,7 +43,7 @@ import logging from abc import ABC, abstractmethod from collections.abc import Callable, Sequence -from pathlib import Path, PurePath +from pathlib import Path from typing import Any import lightning.pytorch as pl @@ -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 @@ -69,44 +69,44 @@ logger = logging.getLogger(__name__) -def _comparable_hyperparameter(value: object) -> object: - """Normalize a hyperparameter value so equivalent values compare equal. +def _lists_to_tuples(value: object) -> object: + """Convert lists nested in a hyperparameter value to tuples. - Checkpoints store paths as strings, and configuration files produce lists - where Python code usually passes tuples. Neither difference changes what the - model does, so both are normalized before comparison. + 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 paths converted to strings and lists to tuples. + object: The value with every list and tuple converted to a tuple. """ - if isinstance(value, PurePath): - return str(value) if isinstance(value, (list, tuple)): - return tuple(_comparable_hyperparameter(item) for item in value) + return tuple(_lists_to_tuples(item) for item in value) if isinstance(value, dict): - return {key: _comparable_hyperparameter(item) for key, item in value.items()} + return {key: _lists_to_tuples(item) for key, item in value.items()} return value -def _hyperparameters_match(saved: object, current: object) -> bool: +def _hyperparameters_match(saved: PathValue, current: PathValue) -> bool: """Check whether a saved hyperparameter matches the live model's value. - 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. + 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 (object): Value stored in the checkpoint. - current (object): Value on the model instance. + 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; ``bool()`` raises for them. - matches = bool(_comparable_hyperparameter(saved) == _comparable_hyperparameter(current)) + matches = bool(_lists_to_tuples(paths_to_strings(saved)) == _lists_to_tuples(paths_to_strings(current))) except (RuntimeError, TypeError, ValueError): return True return matches From 637e9d29ea65afec451f0dc19aa579a3d8baf790 Mon Sep 17 00:00:00 2001 From: Varunika Rai Date: Tue, 20 Oct 2026 22:02:28 +0530 Subject: [PATCH 5/9] fix(model): only catch the errors that tensor and array comparisons raise Signed-off-by: Varunika Rai --- src/anomalib/models/components/base/anomalib_module.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/anomalib/models/components/base/anomalib_module.py b/src/anomalib/models/components/base/anomalib_module.py index c33e722ec9..e5ce7c280c 100644 --- a/src/anomalib/models/components/base/anomalib_module.py +++ b/src/anomalib/models/components/base/anomalib_module.py @@ -105,9 +105,10 @@ def _hyperparameters_match(saved: PathValue, current: PathValue) -> bool: bool: ``True`` if the values are equivalent or cannot be compared. """ try: - # ``==`` on tensors and arrays is elementwise; ``bool()`` raises for them. + # ``==`` 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, TypeError, ValueError): + except (RuntimeError, ValueError): return True return matches From d9331055f34e435ab7f0fe6fabc6d8c6c95c0568 Mon Sep 17 00:00:00 2001 From: Varunika Rai Date: Tue, 20 Oct 2026 22:03:14 +0530 Subject: [PATCH 6/9] test(model): cover checkpoint arguments that cannot be compared Signed-off-by: Varunika Rai --- tests/unit/engine/test_checkpoint_io.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/unit/engine/test_checkpoint_io.py b/tests/unit/engine/test_checkpoint_io.py index d943e3f848..1a45a2d5df 100644 --- a/tests/unit/engine/test_checkpoint_io.py +++ b/tests/unit/engine/test_checkpoint_io.py @@ -8,6 +8,7 @@ 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 @@ -21,6 +22,7 @@ from anomalib.engine.plugins import AnomalibCheckpointIO 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 @@ -474,3 +476,19 @@ def test_pre_trained_difference_is_not_logged(tmp_path: Path, caplog: pytest.Log 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) From 760dc8e7aae9f16a42859092b7bc464c3c16ae25 Mon Sep 17 00:00:00 2001 From: Varunika Rai Date: Wed, 21 Oct 2026 20:48:02 +0530 Subject: [PATCH 7/9] docs(model): drop the long explanation from the mismatch warning's docstring Signed-off-by: Varunika Rai --- src/anomalib/models/components/base/anomalib_module.py | 9 --------- 1 file changed, 9 deletions(-) diff --git a/src/anomalib/models/components/base/anomalib_module.py b/src/anomalib/models/components/base/anomalib_module.py index e5ce7c280c..6dd10b87bc 100644 --- a/src/anomalib/models/components/base/anomalib_module.py +++ b/src/anomalib/models/components/base/anomalib_module.py @@ -255,15 +255,6 @@ def on_load_checkpoint(self, checkpoint: dict[str, Any]) -> None: def _warn_on_hyperparameter_mismatch(self, saved: dict[str, Any] | None) -> None: """Warn when a checkpoint was saved with different constructor arguments. - ``load_from_checkpoint`` rebuilds the model from the saved - ``hyper_parameters``. Loading a checkpoint into an existing instance, - for example through ``Engine.predict(model=..., ckpt_path=...)``, only - restores the weights. Arguments kept as plain attributes, such as - ``num_neighbors`` in PatchCore, then keep the instance's values, and the - scores no longer match the thresholds and normalization statistics - stored in the checkpoint. Only arguments present in both the checkpoint - and the model are compared, and ``pre_trained`` is skipped. - Args: saved (dict[str, Any] | None): ``hyper_parameters`` from the checkpoint, or ``None`` if the checkpoint has none. From b11d2e6d46adb0a78437f9a9b5a4b4dcb11352c6 Mon Sep 17 00:00:00 2001 From: Varunika Rai Date: Wed, 21 Oct 2026 20:50:34 +0530 Subject: [PATCH 8/9] fix(model): log only the names of mismatched checkpoint arguments Signed-off-by: Varunika Rai --- .../models/components/base/anomalib_module.py | 14 +++----------- tests/unit/engine/test_checkpoint_io.py | 2 +- 2 files changed, 4 insertions(+), 12 deletions(-) diff --git a/src/anomalib/models/components/base/anomalib_module.py b/src/anomalib/models/components/base/anomalib_module.py index 6dd10b87bc..a6d11b0262 100644 --- a/src/anomalib/models/components/base/anomalib_module.py +++ b/src/anomalib/models/components/base/anomalib_module.py @@ -265,22 +265,14 @@ def _warn_on_hyperparameter_mismatch(self, saved: dict[str, Any] | None) -> None # ``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"} - mismatches = [ - f"{key}={current[key]!r} (checkpoint: {saved[key]!r})" - for key in sorted(compared) - if not _hyperparameters_match(saved[key], current[key]) - ] + # 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. The model runs with the current " - "values. Differences in arguments that only affect training are harmless, but differences in " - "arguments used at inference make scores inconsistent with the thresholds and normalization " - "statistics saved in the checkpoint. Use %s.load_from_checkpoint(...) or create the model with the " - "same arguments.", + "%s was created with arguments that differ from the checkpoint: %s", self.__class__.__name__, ", ".join(mismatches), - self.__class__.__name__, ) def _restore_component_enabled_flags(self, flags: dict[str, bool] | None) -> None: diff --git a/tests/unit/engine/test_checkpoint_io.py b/tests/unit/engine/test_checkpoint_io.py index 1a45a2d5df..d041dca233 100644 --- a/tests/unit/engine/test_checkpoint_io.py +++ b/tests/unit/engine/test_checkpoint_io.py @@ -401,7 +401,7 @@ def test_hyperparameter_mismatch_is_logged_on_load(tmp_path: Path, caplog: pytes with caplog.at_level(logging.WARNING, logger=_MODULE_LOGGER): model.on_load_checkpoint(checkpoint) - assert "num_neighbors=9 (checkpoint: 2)" in caplog.text + assert "differ from the checkpoint: num_neighbors" in caplog.text def test_matching_hyperparameters_are_not_logged(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: From 596acaef605429fb3212efe46d96f351586b07ec Mon Sep 17 00:00:00 2001 From: Varunika Rai Date: Wed, 21 Oct 2026 20:58:24 +0530 Subject: [PATCH 9/9] test(model): check that mismatch warnings do not log argument values Signed-off-by: Varunika Rai --- tests/unit/engine/test_checkpoint_io.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/unit/engine/test_checkpoint_io.py b/tests/unit/engine/test_checkpoint_io.py index d041dca233..143efb7a20 100644 --- a/tests/unit/engine/test_checkpoint_io.py +++ b/tests/unit/engine/test_checkpoint_io.py @@ -492,3 +492,15 @@ def test_values_without_a_single_truth_value_are_treated_as_matching(saved: obje 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