From 86cc1e182245681aca65761121a9942376564894 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Mon, 7 Sep 2026 00:04:21 +0000 Subject: [PATCH] refactor(import): defer scipy.special out of `import autofit` via a lazy TransformedMessage support MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `TransformedMessage.__init__` computed the physical-space support eagerly, and for `phi_transform` the inverse is `scipy.special.ndtri` — so the five module-level literals in `autofit/messages/normal.py` (`UniformNormalMessage` and friends) pulled `scipy.special` into every `import autofit`: 25 nodes, ~0.18 s cumulative, for a value almost no process reads (census O2 of the ci-timing-fast-tests epic, PyAutoHeart timings/unit_import_census_2026-09.md). `_support` is now a `functools.cached_property` of the same name: computed on first access, cached in `__dict__` under the key the eager code wrote, so default pickling and old pickles carrying a `_support` state entry are unchanged. Every reader audited (composed_transform itself, beta.py, two tests); `_support_kwargs` / `_parameter_support` / `check_support` untouched; the identifier hasher never saw the key. Measured: `-X importtime` scipy.special 177-180 ms → absent; `import autofit` 0.436 → 0.227 s (best of 3, fresh processes). Identifiers byte-identical before/after for UniformPrior, LogUniformPrior, Model(Gaussian) and a Collection. Suite 2454 passed, 2 skipped; ten new tests pin the clean import, the unchanged supports, the pickle round trip and the identifiers. Refs PyAutoLabs/PyAutoFit#1565 Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01WYcmRnZf3cbC5Wth9bCkEg --- autofit/messages/composed_transform.py | 21 ++- .../messages/test_lazy_transformed_support.py | 134 ++++++++++++++++++ 2 files changed, 153 insertions(+), 2 deletions(-) create mode 100644 test_autofit/messages/test_lazy_transformed_support.py diff --git a/autofit/messages/composed_transform.py b/autofit/messages/composed_transform.py index 63a2cf58d..493a71d7b 100644 --- a/autofit/messages/composed_transform.py +++ b/autofit/messages/composed_transform.py @@ -134,10 +134,27 @@ def __init__( self.lower_limit = lower_limit self.upper_limit = upper_limit - x0, x1 = zip(*base_message._support) + @functools.cached_property + def _support(self) -> Tuple[Tuple[float, float], ...]: + """ + The transformed message's support in *physical* space: the base + message's support pushed through ``_inverse_transform``. + + Computed lazily and cached in ``__dict__`` under this same name (a + ``cached_property`` is a non-data descriptor, so the cached value + shadows it thereafter). Deferred because ``phi_transform``'s inverse + is ``scipy.special.ndtri``: computing this eagerly in ``__init__`` + made the module-level ``UniformNormalMessage`` literal in + ``autofit.messages.normal`` pull ``scipy.special`` — ~0.18s — into + every ``import autofit``, for a value almost no process reads + (census O2). Old pickles that carry a + ``_support`` entry in their state restore it into ``__dict__`` + unchanged, which is exactly where the cache lives. + """ + x0, x1 = zip(*self.base_message._support) z0 = self._inverse_transform(np.array(x0)) z1 = self._inverse_transform(np.array(x1)) - self._support = tuple(zip(z0, z1)) + return tuple(zip(z0, z1)) log_normalisation = AbstractMessage.log_normalisation diff --git a/test_autofit/messages/test_lazy_transformed_support.py b/test_autofit/messages/test_lazy_transformed_support.py new file mode 100644 index 000000000..9dab29049 --- /dev/null +++ b/test_autofit/messages/test_lazy_transformed_support.py @@ -0,0 +1,134 @@ +""" +Census O2: ``import autofit`` must not pay for ``scipy.special``. + +``autofit/messages/normal.py`` builds five module-level ``TransformedMessage`` +literals (``UniformNormalMessage`` and friends). ``TransformedMessage`` used to +compute its physical-space support eagerly in ``__init__``, and the inverse of +``phi_transform`` is ``scipy.special.ndtri`` — so every process that touched +``autofit`` at all imported ``scipy.special`` (~0.18s) to fill in a value almost +none of them ever read. The support is now a ``functools.cached_property``. + +These tests pin the two halves of that: the import stays clean, and the value +(and its pickling) is unchanged. +""" +import pickle +import subprocess +import sys + +import numpy as np +import pytest + +import autofit as af +from autofit.messages.composed_transform import TransformedMessage +from autofit.mapper.identifier import Identifier +from autofit.messages.normal import ( + Log10NormalMessage, + Log10UniformNormalMessage, + LogNormalMessage, + MultiLogitNormalMessage, + NormalMessage, + UniformNormalMessage, +) +from autofit.messages.transform import phi_transform + + +def _in_fresh_process(module: str) -> bool: + """Whether ``module`` is in ``sys.modules`` after a bare ``import autofit``.""" + result = subprocess.run( + [ + sys.executable, + "-c", + f"import autofit, sys; print({module!r} in sys.modules)", + ], + capture_output=True, + text=True, + check=True, + ) + return result.stdout.strip() == "True" + + +def test__importing_autofit_does_not_import_scipy_special(): + assert _in_fresh_process("scipy.special") is False + + +def test__importing_autofit_does_not_import_scipy_stats(): + assert _in_fresh_process("scipy.stats") is False + + +def test__module_level_messages_still_import_and_report_their_support(): + assert UniformNormalMessage._support == ((0.0, 1.0),) + assert Log10UniformNormalMessage._support == ((1.0, 10.0),) + assert LogNormalMessage._support == ((0.0, np.inf),) + assert Log10NormalMessage._support == ((0.0, np.inf),) + + (lower, upper), = MultiLogitNormalMessage._support + assert lower == 0.0 + assert np.isnan(upper) + + +def test__support_is_only_computed_on_first_access_and_then_cached(): + message = TransformedMessage(NormalMessage(0, 1), phi_transform) + + assert "_support" not in message.__dict__ + + support = message._support + + assert message.__dict__["_support"] is support + assert message._support is support + + +def test__pickle_round_trip_preserves_the_support(): + eager = TransformedMessage(NormalMessage(0, 1), phi_transform)._support + + # Un-accessed: the cache is not in the pickled state at all. + fresh = TransformedMessage(NormalMessage(0, 1), phi_transform) + assert pickle.loads(pickle.dumps(fresh))._support == eager + + # Accessed: the cached value rides along in ``__dict__`` as it always did. + assert UniformNormalMessage._support == eager + assert pickle.loads(pickle.dumps(UniformNormalMessage))._support == eager + + +@pytest.mark.parametrize( + "prior, support", + [ + (af.UniformPrior(lower_limit=0.0, upper_limit=1.0), ((0.0, 1.0),)), + (af.LogUniformPrior(lower_limit=1e-3, upper_limit=1.0), ((1e-3, 1.0),)), + ], +) +def test__prior_support_and_limits_survive_a_pickle_round_trip(prior, support): + assert prior._support == support + + loaded = pickle.loads(pickle.dumps(prior)) + + assert loaded._support == support + assert loaded.lower_limit == prior.lower_limit + assert loaded.upper_limit == prior.upper_limit + + +@pytest.mark.parametrize( + "prior, identifier", + [ + ( + af.UniformPrior(lower_limit=0.0, upper_limit=1.0), + "6e85def0116bfefb6478e9f707324a7f", + ), + ( + af.LogUniformPrior(lower_limit=1e-3, upper_limit=1.0), + "84cb3563e638e34128f31008e556880d", + ), + ], +) +def test__identifiers_are_byte_identical_to_the_eager_implementation(prior, identifier): + # Measured on ``main`` before the support was made lazy: an identifier names + # an output directory, so a change here silently orphans every existing run. + assert str(Identifier(prior)) == identifier + + +def test__identifier_does_not_depend_on_whether_the_support_was_accessed(): + accessed = af.UniformPrior(lower_limit=0.0, upper_limit=1.0) + assert accessed._support + + untouched = af.UniformPrior(lower_limit=0.0, upper_limit=1.0) + + assert str(Identifier(accessed)) == str(Identifier(untouched))