Repository navigation
fix(model): warn when checkpoint and model arguments differ - #3846
varunikarai wants to merge 11 commits into
Conversation
…different arguments Signed-off-by: Varunika Rai <itsvarunikarai@gmail.com>
Signed-off-by: Varunika Rai <itsvarunikarai@gmail.com>
ashwinvaidya17
left a comment
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
When do you expect a Runtime, Type, or a Value error, and is returning True safe?
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
Thanks! Just two minor comments and we are good to merge
There was a problem hiding this comment.
🟡 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>

📝 Description
Engine.export(..., ckpt_path=...)rebuilds the model from the hyperparameters saved in the checkpoint, butEngine.predict/test/validatewithckpt_pathonly load the weights into the instance that is passed in. Constructor arguments kept as plain attributes, such as PatchCore'snum_neighbors, then silently keep the instance's values, and scores no longer match the thresholds and normalization statistics saved in the checkpoint. This explains the checkpoint vs ONNX/OpenVINO difference in [Bug] PatchCore ONNX and OpenVINO pred_score mismatch with ckpt inference (anomalib 2.6.0, clean Docker environment) #3726 / How to match PatchCore ONNX inference score with ckpt inference score? #3644: trained withnum_neighbors=2, predicted with a defaultPatchcore(...), which uses 9.AnomalibModule.on_load_checkpointwhen the checkpoint's saved hyperparameters differ from the model's, naming each argument with both values and pointing toload_from_checkpoint. It does not change which values the model uses.Root cause
anomalib/src/anomalib/engine/engine.py
Line 912 in dc087d5
anomalib/src/anomalib/engine/engine.py
Line 745 in dc087d5
What this PR does
on_load_checkpointcalls 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 callssuper().Pathandstr, compare as equal. Values that cannot be compared, such as tensors, are skipped.pre_trainedis skipped (_HYPERPARAMETERS_REPLACED_BY_WEIGHTS) because the checkpoint replaces those weights anyway. Subclasses can extend the set.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_loadfails onmainand passes with this change. The other new tests check that matching arguments,load_from_checkpoint, list vs tuple, missing hyperparameters andpre_traineddo not warn.prek runon the changed files passes (ruff, ruff-format, mypy, bandit).num_neighbors=2): a defaultPatchcore()withckpt_pathscores every defect 1.0000, whilenum_neighbors=2withckpt_pathandload_from_checkpointgive identical scores (0.4865 to 0.6313). The warning fires only for the default instance.Not in this PR
predict/testrestore the saved arguments the wayexportdoes. That changes behaviour, so I asked in [Bug] PatchCore ONNX and OpenVINO pred_score mismatch with ckpt inference (anomalib 2.6.0, clean Docker environment) #3726 which approach you prefer, and I'm happy to change this PR if you'd rather go that way.✨ Changes
Select what type of change your PR is:
✅ Checklist
Before you submit your pull request, please make sure you have completed the following steps:
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.