Skip to content

PERF Cache inspect.signature for callback hook evaluation - #34099

Merged
thomasjpfan merged 2 commits into
scikit-learn:mainfrom
jeremiedbb:cache-hook-signature
May 26, 2026
Merged

thomasjpfan merged 2 commits into
scikit-learn:mainfrom
jeremiedbb:cache-hook-signature

Conversation

@jeremiedbb

Copy link
Copy Markdown
Member

Fixes #33587

inspect.signature is not free. It's the first source of overhead from the hook call.
The overhead from the hook call is not a lot in itself (a few micro seconds), compared to the computations happening during fit it's usually very small, but maybe it's not negligible for estimators with very fast iterations. Also this optimization is pretty easy and divides the overhead by 4 so why not.

benchmark script:

import time
import numpy as np
import sklearn.callback.tests._utils as _cb_utils
from sklearn.callback.tests._utils import MaxIterEstimator, RecordingCallback

# to avoid the overhead of calling sleep (even for 0s)
_cb_utils.time.sleep = lambda _: None

times = []
for _ in range(20):
    est = MaxIterEstimator(max_iter=1000).set_callbacks(RecordingCallback())
    t0 = time.perf_counter()
    est.fit()
    times.append(time.perf_counter() - t0)

times = np.array(times) * 1000
print(f"{times.mean():.2f} ± {times.std():.2f} ms")

Results:

  • main: 39.54 ± 11.10 ms
  • this PR: 13.10 ± 10.66 ms

I removed any form of stuff happening if fit so it's just the callback overhead + evaluation: ~10ms for 1000 iterations
(it's very noisy, probably due to the listener, but not sure, the speed-up is there and visible anyway)

@jeremiedbb jeremiedbb added Quick Review For PRs that are quick to review Callbacks labels May 23, 2026
Comment thread sklearn/callback/_callback_context.py Outdated
VALID_HOOK_PARAMS_OUT = ["X", "y", "metadata", "fitted_estimator"]


_cached_signature = functools.lru_cache(maxsize=None)(inspect.signature)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maxsize=None means that the cache lives as long as long as the process. What do you think of having the cache be a attribute of CallbackContext and the sharing it with the subcontexts?

    @classmethod
    def _from_estimator(...):
        new_ctx._cached_signature = functools.lru_cache(maxsize=None)(inspect.signature)

    @classmethod
    def _from_parent(...):
        new_ctx._cached_signature = parent_context._cached_signature

    def _merge_with(...):
        # A little werid since we are not "merging" the caches.
        self._cached_signature = other_context._cached_signature

This way the cache lives as long as the root context.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually i think it's perfectly fine to leave max_size to the default value (128). I don't know why I put None...
We check 2 hooks per callback so it means we can cache up to 64 callbacks which should be more than enough, and there's no risk to arbitrarily grow the cache.

We could even set max_size to 64 or even 32. In particular, the performance impact should be very low in most cases (only visible for very very fast iterations), so a cache miss from time to time is not a big issue at all.

@StefanieSenger StefanieSenger left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you, @jeremiedbb.

I also think we wouldn't need more than 128 entries in the cache, and that would already be a very nested pipeline.

@thomasjpfan
thomasjpfan merged commit 6cc033a into scikit-learn:main May 26, 2026
33 checks passed
@jeremiedbb jeremiedbb mentioned this pull request Jun 1, 2026
16 tasks done
prady0t pushed a commit to prady0t/scikit-learn that referenced this pull request Sep 2, 2026
@jeremiedbb
jeremiedbb deleted the cache-hook-signature branch September 3, 2026 15:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Callbacks Quick Review For PRs that are quick to review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Callbacks] PERF Cache the signature of hooks in call_on_fit_task_*

3 participants