Repository navigation
PERF Cache inspect.signature for callback hook evaluation - #34099
Conversation
| VALID_HOOK_PARAMS_OUT = ["X", "y", "metadata", "fitted_estimator"] | ||
|
|
||
|
|
||
| _cached_signature = functools.lru_cache(maxsize=None)(inspect.signature) |
There was a problem hiding this comment.
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_signatureThis way the cache lives as long as the root context.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
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:
Results:
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)