Skip to content

PERF Cache inspect.signature in GPR kernels - #33067

Merged
jeremiedbb merged 6 commits into
scikit-learn:mainfrom
sterliakov:perf/st-gpr-kernel-signature-cache
Apr 3, 2026
Merged

jeremiedbb merged 6 commits into
scikit-learn:mainfrom
sterliakov:perf/st-gpr-kernel-signature-cache

Conversation

@sterliakov

@sterliakov sterliakov commented Jan 13, 2026 •

Copy link
Copy Markdown
Contributor

Reference Issues/PRs

None

What does this implement/fix? Explain your changes.

inspect.signature is known to be very slow, it is not the best function for a hot path. It was identified as a performance bottleneck in our real workload. Since the method signature cannot change while maintaining method's identity, it becomes a perfect target for caching. Cache size of 32 should be sufficient to cover all currently existing kernels at once (and the memory footprint is about zero).

AI usage disclosure

I used AI assistance for: never

  • Code generation (e.g., when writing an implementation or fixing a bug)
  • Test/benchmark generation
  • Documentation (including examples)
  • Research and understanding

Any other comments?

Initially I identified this with cProfile in our real workload, and then confirmed with a tiny benchmark:

from functools import lru_cache
import sys
import time

import numpy as np
from sklearn.gaussian_process import GaussianProcessRegressor, kernels

cached_signature = lru_cache(maxsize=32)(kernels.signature)

patched = False
match sys.argv:
    case [_, 'patched']:
        # just monkeypatch it in sklearn
        kernels.signature = cached_signature
        patched = True 

# sample code from GPR docs: 
# https://scikit-learn.org/stable/auto_examples/gaussian_process/plot_gpr_noisy_targets.html
x = np.linspace(start=0, stop=10, num=1000).reshape(-1, 1)
y = np.squeeze(x * np.sin(x))
rng = np.random.RandomState(1)
training_indices = rng.choice(np.arange(y.size), size=6, replace=False)
x, y = x[training_indices], y[training_indices]

kernel = 1 * kernels.RBF(length_scale=1.0, length_scale_bounds=(1e-2, 1e2))

timings = []
for _ in range(50):
    start = time.time()
    gpr = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=10, random_state=42)
    gpr.fit(x, y)
    timings.append(time.time() - start)

mean = np.mean(timings) * 1000
std = np.std(timings) * 1000

print(f"Pathed: {patched}, time: {mean:.0f} ms +- {std:.0f} ms per iteration")

Output:

$ python b.py  
Pathed: False, time: 131 ms +- 13 ms per iteration
$ python b.py  patched
Pathed: True, time: 102 ms +- 10 ms per iteration

@sterliakov

Copy link
Copy Markdown
Contributor Author

Similar optimization can be applied to sklearn.base.BaseEstimator._get_param_names (and that will probably have even bigger impact) - would it make sense to do this in the same PR?

@Mohataseem89

Copy link
Copy Markdown

caching inspect.signature in this hot path makes a lot of sense, and the benchmark clearly shows a meaningful speedup

keeping this PR focused on GPR kernels seems reasonable. a similar change for BaseEstimator._get_param_names could probably be handled in a separate PR to keep review scope small and make performance impacts easier to evaluate independently

@sterliakov sterliakov changed the title perf: Cache inspect.signature in GPR kernels PERF Cache inspect.signature in GPR kernels Jan 25, 2026
@ogrisel

ogrisel commented Jan 28, 2026

Copy link
Copy Markdown
Member

So there is a 30% overhead on a dataset with a single feature and 1000 points. However, I suspect that the benefits would be much less for more features or data points.

@sterliakov

sterliakov commented Jan 28, 2026 •

Copy link
Copy Markdown
Contributor Author

@ogrisel in a real workload I measured 140 seconds of training time spent in inspect.signature - that's out of a ~12 min training job using GridSearchCV (36 combinations IIRC). This is not a cProfile overhead, continuous probing with py-spy gave the same probabilistic "Monte Carlo" estimate of ~20% time spent there without cProfile.

I have verified that this patch has significant positive impact on the training time I observe, saving more than 15%. I can try to write a bigger benchmark if you wish. My case is specifically limited to small (under 1K typically) amount of data points and less than 100 features - many inputs are around 20 features x 200 points.

@ogrisel

ogrisel commented Jan 29, 2026

Copy link
Copy Markdown
Member

Thanks for the more detailed real-world impact estimate.

Could you please add a changelog entry of the "efficiency" kind?

https://github.com/scikit-learn/scikit-learn/blob/main/doc/whats_new/upcoming_changes/README.md

Comment thread sklearn/gaussian_process/kernels.py Resolved
@sterliakov

Copy link
Copy Markdown
Contributor Author

Apologies for the delay, I have added a changelog entry and committed your suggested comment. I also retried two training jobs with and without this patch, getting approx. 7% saving on 400 data points (4 folds x 42 candidates) and approx. 18% saving on 70 data points (also 4 folds x 42 candidates) - both in a single noisy sample, but still shows that this is probably worth trying, provided that there are no obvious negative consequences.

@betatim

betatim commented Feb 3, 2026

Copy link
Copy Markdown
Member

This looks like a nice improvement. I do wonder if we need that signature inspection at all, it seems half of the reason it exists is to check that kernels follow a convention for how to specify constructor arguments. Seems like we should be able to check this with a unit test, instead of doing it at runtime? The second half of its job is for knowing what the parameters are, for this we could rely on the same convention as in estimators: all attributes that do not start with a _ or end with a _ are the parameters.

However this might be a bigger change compared to caching the results. What do people think?

I think it would be interesting to see the code for your GridSearchCV case (with generated data). Mostly for reference when people from the future come to this PR trying to understand why this cache was added. Is it possible to add a short snippet or would it be too long/need private data to work?

@sterliakov

Copy link
Copy Markdown
Contributor Author

I do wonder if we need that signature inspection at all, it seems half of the reason it exists is to check that kernels follow a convention for how to specify constructor arguments.

Do you propose to replace this inspection with another dir()? That's possible, but is definitely a breaking change. Estimators also rely on the constructor signature now (and yes, I also see their inspect() calls in cProfile traces), and they could also benefit from similar caching or change of the approach. I'm all in favour of removing costly correctness check and providing an alternative like check_estimator for use in unit tests.

Introspection/reflection is often costly - using dir() to identify kernel hyperparameters, for example, also accounts for a noticeable portion of total run time, because dir(), listcomp and str.startswith aren't free. I saw almost 10% reduction on small datasets after caching HP names, but will need to bench that separately. Parameters still need to be identified sooner or later, but it would be better to compute such things once instead of once per call. (on a side note, I was really surprised to see such runtime introspection where a one-time metaclass application could do)

The original code depends on a multi-layer model wrappers architecture, but I can extract a benchmark from local values in pdb, and I can publish that dataset just fine (I generated it manually for testing). I'll try to free up a few minutes and post it here within a couple of days.

@betatim

betatim commented Feb 3, 2026

Copy link
Copy Markdown
Member

Thanks for the detailed answer. I think based on what you said and the fact that for me it was more speculation than a well thought out plan we should go ahead with this PR as it is. We can investigate alternatives and/or adding more caching for normal estimators in a new issue.

@betatim

betatim commented Feb 17, 2026

Copy link
Copy Markdown
Member

I merged main into this as a way to get the CI jobs to run. Not sure why they got stuck (maybe a victim of a recent GitHub outage?).

@jeremiedbb jeremiedbb 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.

LGTM. Thanks @sterliakov

I agree with Tim that this signature inspection should be done as a common test for kernels instead. Doing it at runtime allows customs kernels still (although the warning message is about scikit-learn kernels). But let's revisit that in a different issue/PR.

@jeremiedbb
jeremiedbb enabled auto-merge (squash) April 3, 2026 16:22
@jeremiedbb
jeremiedbb merged commit 236f5e2 into scikit-learn:main Apr 3, 2026
31 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants