From 633edef01d952ca08cb040910b0b441a4090bf1f Mon Sep 17 00:00:00 2001 From: ChrisW09 <50968720+ChrisW09@users.noreply.github.com> Date: Wed, 21 Oct 2026 16:17:46 +0200 Subject: [PATCH 1/2] fix(models): score the in-memory model without reloading the checkpoint _PredictMixin._score (used by the regressors' score()) loaded the best checkpoint from disk into the task model before predicting. fit() has already restored that checkpoint, so the reload only made score() fail with FileNotFoundError once the checkpoint directory was removed and silently replaced any weights changed after fitting. Score the current model, like predict() and the classifiers' score(). Fixes #503 --- deeptab/models/_mixins/predict.py | 16 ++++--------- tests/integration/test_fit_lifecycle.py | 31 +++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 11 deletions(-) diff --git a/deeptab/models/_mixins/predict.py b/deeptab/models/_mixins/predict.py index 370a1372..0039ba46 100644 --- a/deeptab/models/_mixins/predict.py +++ b/deeptab/models/_mixins/predict.py @@ -135,11 +135,12 @@ def _validate_predict_input(self, X, method="predict"): return validate_input_features(self, X) def _score(self, X, y, embeddings, metric): - """Evaluate *metric* on *X* / *y* using the best-checkpoint weights. + """Evaluate *metric* on *X* / *y* using the estimator's current weights. - Reloads the best model checkpoint before running ``predict`` so that - the score reflects the best validation state rather than the last - epoch's weights. + ``fit()`` already restores the best checkpoint before returning, so the + score reflects the same model that ``predict`` uses. The checkpoint file + is not read again, so scoring neither depends on it still existing nor + discards changes made to the model after fitting. Parameters ---------- @@ -159,13 +160,6 @@ def _score(self, X, y, embeddings, metric): float The metric value computed on the predictions. """ - # Explicitly load the best model state if needed - best_model_path = getattr(self, "_best_model_path", None) - if hasattr(self, "_trainer") and best_model_path: - torch.serialization.add_safe_globals([type(self.config)]) - checkpoint = torch.load(best_model_path, weights_only=False) - self._task_model.load_state_dict(checkpoint["state_dict"]) # type: ignore - predictions = self.predict(X, embeddings) return metric(y, predictions) diff --git a/tests/integration/test_fit_lifecycle.py b/tests/integration/test_fit_lifecycle.py index 94f9db93..95dc5f0e 100644 --- a/tests/integration/test_fit_lifecycle.py +++ b/tests/integration/test_fit_lifecycle.py @@ -62,6 +62,37 @@ def _raise_mid_fit(self, *args, **kwargs): reg.predict(X) +class TestRegressorScoreUsesCurrentModel: + """score() must evaluate the in-memory model, like predict(), without + reloading the training checkpoint from disk.""" + + def test_score_works_after_checkpoint_directory_is_removed(self, tmp_path): + import shutil + + from sklearn.metrics import r2_score + + X, y = _make_reg_data() + checkpoint_dir = tmp_path / "checkpoints" + reg = MLPRegressor().fit(X, y, random_state=RANDOM_STATE, checkpoint_path=str(checkpoint_dir), **FIT_KWARGS) + assert reg._best_model_path + shutil.rmtree(checkpoint_dir) + assert reg.score(X, y) == pytest.approx(r2_score(y, reg.predict(X))) + + def test_score_does_not_replace_current_weights(self): + import torch + from sklearn.metrics import r2_score + + X, y = _make_reg_data() + reg = MLPRegressor().fit(X, y, random_state=RANDOM_STATE, **FIT_KWARGS) + assert reg._task_model is not None + with torch.no_grad(): + for parameter in reg._task_model.parameters(): + parameter.add_(0.5) + predictions = reg.predict(X) + assert reg.score(X, y) == pytest.approx(r2_score(y, predictions)) + np.testing.assert_array_equal(reg.predict(X), predictions) + + class _RecordingCallback(Callback): def __init__(self): self.epoch_ends = 0 From 80c8a45ddf2403ece5ff5167695b74bae700183c Mon Sep 17 00:00:00 2001 From: ChrisW09 <50968720+ChrisW09@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:52:31 +0200 Subject: [PATCH 2/2] docs: describe what _score does now in the predict mixin overview Refs #503 --- deeptab/models/_mixins/predict.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/deeptab/models/_mixins/predict.py b/deeptab/models/_mixins/predict.py index 0039ba46..3146dcec 100644 --- a/deeptab/models/_mixins/predict.py +++ b/deeptab/models/_mixins/predict.py @@ -28,8 +28,8 @@ class _PredictMixin: the input columns match those seen during ``fit``. * ``encode`` — returns dense embedding vectors from the model backbone for a given input DataFrame. - * ``_score`` — internal helper used by ``optimize_hparams`` to evaluate - validation loss with the best checkpoint loaded. + * ``_score`` — internal helper behind the regressors' ``score()``; it + applies a metric to the ``predict`` output of the current model. """ if TYPE_CHECKING: