Skip to content

fix(model): warn when checkpoint and model arguments differ - #3846

Open
varunikarai wants to merge 11 commits into
open-edge-platform:mainfrom
varunikarai:fix/model/warn-on-checkpoint-hparam-mismatch
Open

varunikarai wants to merge 11 commits into
open-edge-platform:mainfrom
varunikarai:fix/model/warn-on-checkpoint-hparam-mismatch

Conversation

@varunikarai

Copy link
Copy Markdown
Contributor

📝 Description

Root cause

What this PR does

  • on_load_checkpoint calls a new _warn_on_hyperparameter_mismatch, so every load path (fit resume, validate, test, predict, load_from_checkpoint) and every model is covered, including MH-PatchCore, which calls super().
  • Only arguments present in both the checkpoint and the model are compared. Lists and tuples, and Path and str, compare as equal. Values that cannot be compared, such as tensors, are skipped.
  • pre_trained is skipped (_HYPERPARAMETERS_REPLACED_BY_WEIGHTS) because the checkpoint replaces those weights anyway. Subclasses can extend the set.
  • Example: Patchcore was created with arguments that differ from the checkpoint: num_neighbors=9 (checkpoint: 2). The model runs with the current values. ...

How I tested

  • tests/unit/engine/test_checkpoint_io.py: 23 passed, 6 of them new. test_hyperparameter_mismatch_is_logged_on_load fails on main and passes with this change. The other new tests check that matching arguments, load_from_checkpoint, list vs tuple, missing hyperparameters and pre_trained do not warn.
  • prek run on the changed files passes (ruff, ruff-format, mypy, bandit).
  • Reproduction on synthetic images (PatchCore resnet18, trained with num_neighbors=2): a default Patchcore() with ckpt_path scores every defect 1.0000, while num_neighbors=2 with ckpt_path and load_from_checkpoint give identical scores (0.4865 to 0.6313). The warning fires only for the default instance.

Not in this PR

✨ Changes

Select what type of change your PR is:

  • 🚀 New feature (non-breaking change which adds functionality)
  • 🐞 Bug fix (non-breaking change which fixes an issue)
  • 🔄 Refactor (non-breaking change which refactors the code base)
  • ⚡ Performance improvements
  • 🎨 Style changes (code style/formatting)
  • 🧪 Tests (adding/modifying tests)
  • 📚 Documentation update
  • 📦 Build system changes
  • 🚧 CI/CD configuration
  • 🔧 Chore (general maintenance)
  • 🔒 Security update
  • 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)

✅ Checklist

Before you submit your pull request, please make sure you have completed the following steps:

  • 📚 I have made the necessary updates to the documentation (if applicable). Docstrings updated; no docs page covers this.
  • 🧪 I have written tests that support my changes and prove that my fix is effective or my feature works (if applicable).
  • 🏷️ My PR title follows conventional commit format.

For more information about code review checklists, see the Code Review Checklist.

AI disclosure

AI assistance used: An AI assistant helped trace the root cause and write the change and the tests.
Human validation performed: I reviewed the diff, ran the tests, the pre-commit hooks and the reproduction on my machine, and can explain each change.

…different arguments

Signed-off-by: Varunika Rai <itsvarunikarai@gmail.com>
Signed-off-by: Varunika Rai <itsvarunikarai@gmail.com>

@ashwinvaidya17 ashwinvaidya17 left a comment

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.

Thanks for the PR. Showing warnings when the loaded checkpoint differs is a good idea. I do have some comments though.

logger = logging.getLogger(__name__)


def _comparable_hyperparameter(value: object) -> object:

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.

If the intent of this function is to convert paths to strings for comparison, shouldn't it be named something that reflects that specifically? comparable_hyperparameter might not be clear enough. And maybe a better placement for this function might be utils/path.py
It is essentially paths_to_strings. Maybe we can just re-use or update that function to fit both use cases?

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.

Good point, thanks! I dropped _comparable_hyperparameter and now reuse paths_to_strings from utils/path.py directly (8a18541), so there's no new path helper. The only helper left is _lists_to_tuples, which covers a separate case: config files give lists where code passes tuples (e.g. PatchCore's layers), so [1, 2] vs (1, 2) would otherwise trigger a false warning.

# ``==`` on tensors and arrays is elementwise; ``bool()`` raises for them.
matches = bool(_comparable_hyperparameter(saved) == _comparable_hyperparameter(current))
except (RuntimeError, TypeError, 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.

…onstant

Signed-off-by: Varunika Rai <itsvarunikarai@gmail.com>
…uments

Signed-off-by: Varunika Rai <itsvarunikarai@gmail.com>
…aise

Signed-off-by: Varunika Rai <itsvarunikarai@gmail.com>
Signed-off-by: Varunika Rai <itsvarunikarai@gmail.com>

@ashwinvaidya17 ashwinvaidya17 left a comment

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.

Thanks! Just two minor comments and we are good to merge

Copilot AI left a comment

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.

🟡 Changes recommended

Mismatch warnings can expose saved and current API credentials in logs.

1 open issue
What changed in this PR

Adds checkpoint argument mismatch warnings to help explain differences between checkpoint inference and exported models, without changing runtime arguments.

Changes:

  • Compares saved and current hyperparameters, normalizing equivalent values.
  • Adds regression tests for warning and suppression cases.
  • Records the fix in the changelog.
File Description
tests/​unit/​engine/​test_checkpoint_io.py Tests mismatch warnings and comparison behavior.
src/​anomalib/​models/​components/​base/​anomalib_module.py Adds hyperparameter comparison and checkpoint-load warnings.
CHANGELOG.md Documents the warning behavior.

Review effort: Balanced

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"}
…cstring

Signed-off-by: Varunika Rai <itsvarunikarai@gmail.com>
Signed-off-by: Varunika Rai <itsvarunikarai@gmail.com>
Signed-off-by: Varunika Rai <itsvarunikarai@gmail.com>
@varunikarai

Copy link
Copy Markdown
Contributor Author

Thanks! I've addressed both and Copilot's note:

  1. The docstring paragraph is now removed - Commit 760dc8e
  2. The api_key is never printed now, and a dummy-key test has been added - Commit 596acae
  3. The warnings are shorter now with names only - Commit b11d2e6

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants