Repository navigation
MNT refactoring in routing _MetadataRequester - #31534
Conversation
| def __repr__(self): | ||
| return "..." |
There was a problem hiding this comment.
since repr is now used in error messages, putting ... here for simplicity. These lists are otherwise pretty ugly and large to print.
| with pytest.raises( | ||
| AttributeError, match="'MetadataRequest' object has no attribute 'other_method'" | ||
| ): | ||
| TestDefaultsBadMethodName().get_metadata_routing() |
There was a problem hiding this comment.
Checking whether __metadata_request__method_name actually has a valid method_name doesn't exist anymore now. I don't think it's crucial to have. As a result, the test for the check is also removed.
| try: | ||
| requests = cls._get_default_requests() | ||
| for method in SIMPLE_METHODS: | ||
| method_metadata_args = cls._get_metadata_args_and_aliases(method) |
There was a problem hiding this comment.
instead of building the whole default request object, we now only check for parameters which are to be included here in __init_subclass__, which is what we actually need. The actual MetadataRequest object is now only created when needed.
Co-authored-by: Omar Salman <[email protected]>
StefanieSenger
left a comment
There was a problem hiding this comment.
Thanks for walking me through these changes, @adrinjalali!
I have now looked it all through and have some comments that I hope will help with internal documentation of the new functionality.
My thought on design is: Could the value for owner become a string early on when owner=self gets passed to the MetadataRequest and MethodMetadataRequest object? We could check right there if we deal with a scorer and in this case manually create a string that serves the purpose of the visualisation in #31535. This would be simpler, I believe.
This PR is adding a lot of complexity to allow owner to be either a string or an instance in order to access the instances' _routing_repr and if there is another way, than this would be pretty cool.
| @classmethod | ||
| def _build_request_for_signature(cls, router, method): | ||
| def _get_metadata_args_and_aliases(cls, method: str): | ||
| """Get the metadata arguments for a method.""" |
There was a problem hiding this comment.
| """Get the metadata arguments for a method.""" | |
| """Get the metadata request values for a method. | |
| Returns a dict with the names of the metadata to be requested for `method` | |
| and the corresponding request values (which can be among {True, False, | |
| None} or a str for an alias). This method first populates the dict with a | |
| `None` request value for every metadata present in `method`s signature and | |
| may then overwrite these request values with request value from a | |
| `__metadata_request__{method}` class attribute. | |
| """ |
Maybe like this?
(Clarify what "metadata arguments" is and explain hierarchy of request values for the signatures versus the __metadata_request__{method}.)
There was a problem hiding this comment.
I've tried to clarify the docstring, how does it look now?
There was a problem hiding this comment.
Yes, that's much clearer. I like the new method name and the docstring. Only leaving a suggestion for some minor improvements in the other comment.
| for base_class in reversed(inspect.getmro(cls)): | ||
| for attr, value in vars(base_class).items(): | ||
| # we don't check for equivalence since python prefixes attrs | ||
| # starting with __ with the `_ClassName`. | ||
| if substr not in attr: | ||
| continue | ||
| for prop, alias in value.items(): | ||
| # Here we add request values specified via those class attributes | ||
| # to the `MetadataRequest` object. Adding a request which already | ||
| # exists will override the previous one. Since we go through the | ||
| # MRO in reverse order, the one specified by the lowest most classes | ||
| # in the inheritance tree are the ones which take effect. | ||
| if prop not in params and alias == UNUSED: | ||
| raise ValueError( | ||
| f"Trying to remove parameter {prop} with UNUSED which" | ||
| " doesn't exist." | ||
| ) |
There was a problem hiding this comment.
Here, I wonder if it is required to loop over the whole mro, because as I understand we only need to check if the attribute is existing on the class that is the closest to the current cls.
So, getattr(cls, f"__metadata_request__{method}") (or similar) and then compare if substr is a part of it isn't enough? Isn't getattr() doing all the work for us by going through the mro while prioritising child classes?
Edit: I have tried this out in this comment.
| # need to go through the MRO since this is a class attribute and | ||
| # ``vars`` doesn't report the parent class attributes. We go through | ||
| # the reverse of the MRO so that child classes have precedence over | ||
| # their parents. | ||
| substr = f"__metadata_request__{method}" | ||
| for base_class in reversed(inspect.getmro(cls)): | ||
| for attr, value in vars(base_class).items(): | ||
| # we don't check for equivalence since python prefixes attrs | ||
| # starting with __ with the `_ClassName`. | ||
| if substr not in attr: | ||
| continue | ||
| for prop, alias in value.items(): | ||
| # Here we add request values specified via those class attributes | ||
| # to the `MetadataRequest` object. Adding a request which already | ||
| # exists will override the previous one. Since we go through the | ||
| # MRO in reverse order, the one specified by the lowest most classes | ||
| # in the inheritance tree are the ones which take effect. | ||
| if prop not in params and alias == UNUSED: | ||
| raise ValueError( | ||
| f"Trying to remove parameter {prop} with UNUSED which" | ||
| " doesn't exist." | ||
| ) | ||
|
|
||
| params[prop] = alias |
There was a problem hiding this comment.
I have tried this below and it fails in test_splitter_get_metadata_routing, and in test_metadata_routed_to_group_splitter (both for the same reason) because while getattr() can access the parent's attributes, the name mangeling makes it a bit hard to know what the attributes' name is and then it is not found. That is not unsolvable though, please let me know what you think, @adrinjalali:
| # need to go through the MRO since this is a class attribute and | |
| # ``vars`` doesn't report the parent class attributes. We go through | |
| # the reverse of the MRO so that child classes have precedence over | |
| # their parents. | |
| substr = f"__metadata_request__{method}" | |
| for base_class in reversed(inspect.getmro(cls)): | |
| for attr, value in vars(base_class).items(): | |
| # we don't check for equivalence since python prefixes attrs | |
| # starting with __ with the `_ClassName`. | |
| if substr not in attr: | |
| continue | |
| for prop, alias in value.items(): | |
| # Here we add request values specified via those class attributes | |
| # to the `MetadataRequest` object. Adding a request which already | |
| # exists will override the previous one. Since we go through the | |
| # MRO in reverse order, the one specified by the lowest most classes | |
| # in the inheritance tree are the ones which take effect. | |
| if prop not in params and alias == UNUSED: | |
| raise ValueError( | |
| f"Trying to remove parameter {prop} with UNUSED which" | |
| " doesn't exist." | |
| ) | |
| params[prop] = alias | |
| # update dict of metadata request values with info from | |
| # `__metadata_request__{method}` class attributes, if these exist | |
| try: | |
| values = getattr(cls, f"_{cls.__name__}__metadata_request__{method}") | |
| for prop, alias in values.items(): | |
| if prop not in params and alias == UNUSED: | |
| raise ValueError( | |
| f"Trying to remove parameter {prop} with UNUSED which" | |
| " doesn't exist." | |
| ) | |
| params[prop] = alias | |
| except AttributeError: | |
| pass |
I am thinking of two possible solutions:
- Here in this method we could have a good guess of what the attribute's name is by using the mro without walking down it.
- Or, since we don't have so many splitters that accept groups, and we could also define the class attribute (
__metadata_request__split = {"groups": True}) on them directly instead of viaGroupsConsumerMixin.
That would (hopefully) make all the tests pass and also simplify the code?
There was a problem hiding this comment.
We still need to go through the MRO, or else we'd require the __metadata_request__{method} attributes to include everything from their parents as well. Consider the followng:
class A(BaseEstimator):
__metadata_request__fit = {"sample_weight": True}
def fit(self, X, y, sample_weight=None):
pass
class B(A):
__metadata_request__fit = {"sensitive_attribute": True}
def fit(self, X, y, sample_weight=None, sensitive_attribute=None):
passIf we want to avoid going through the MRO, then we'd have to force the user to have this code:
class A(BaseEstimator):
__metadata_request__fit = {"sample_weight": True}
def fit(self, X, y, sample_weight=None):
pass
class B(A):
__metadata_request__fit = {"sample_weight": True, "sensitive_attribute": True}
def fit(self, X, y, sample_weight=None, sensitive_attribute=None):
passwhich is not ideal.
I think going through the MRO is quite okay here. It's certainly an advanced python feature, but I rather have a more complicated implementation on our side, rather than complicating user / developer side of things.
There was a problem hiding this comment.
Oh yes, I can see that and I agree it is more important to be simple for users and third party developers than here.
I guess to avoid going through the mro, we could also do some acrobatics with __setattr__ (or maybe not, because for this to work, the code needs to run... 🤔 and it couldn't be done at class level? ) but I am not sure this would result in simpler code.
There was a problem hiding this comment.
More a high level / philosophical question, that is not well thought through and also cannot be easily answered:
This module loops so often over similar things, that I wonder if there could be a does-it-all helper function that catches all kinds of information - needed or not - and can be run when needed (or even eagerly?). This is all fast and in my basic understanding performance is not something we need to worry about here.
I wonder if that would simplify maintaining the code in this module.
There was a problem hiding this comment.
Another thought on a possible refactoring:
__metadata_request__{method} could be a method instead of a set of attributes and then we could use inheritance and super() on it and would not rely on going through the mro for the routing.
It could maybe even be part of the __sklearn_tags__()?
There was a problem hiding this comment.
It can't be a part of __sklearn_tags__ since that's an instance method, and here we require class attributes or a classmethod. However, yes, it could potentially be a classmethod, and then the MRO pass wouldn't be required.
StefanieSenger
left a comment
There was a problem hiding this comment.
Thanks for the adjustments, @adrinjalali!
I have left a few minor suggestions and a few comments.
On the higher level, my impression is that if owner had to always be an instance (obj), and we would retrieve its string with instance.__class__.__name__ early on where needed, that would simplify the code. Do you think that's a good idea?
| @classmethod | ||
| def _build_request_for_signature(cls, router, method): | ||
| def _get_metadata_args_and_aliases(cls, method: str): | ||
| """Get the metadata arguments for a method.""" |
There was a problem hiding this comment.
Yes, that's much clearer. I like the new method name and the docstring. Only leaving a suggestion for some minor improvements in the other comment.
| # need to go through the MRO since this is a class attribute and | ||
| # ``vars`` doesn't report the parent class attributes. We go through | ||
| # the reverse of the MRO so that child classes have precedence over | ||
| # their parents. | ||
| substr = f"__metadata_request__{method}" | ||
| for base_class in reversed(inspect.getmro(cls)): | ||
| for attr, value in vars(base_class).items(): | ||
| # we don't check for equivalence since python prefixes attrs | ||
| # starting with __ with the `_ClassName`. | ||
| if substr not in attr: | ||
| continue | ||
| for prop, alias in value.items(): | ||
| # Here we add request values specified via those class attributes | ||
| # to the `MetadataRequest` object. Adding a request which already | ||
| # exists will override the previous one. Since we go through the | ||
| # MRO in reverse order, the one specified by the lowest most classes | ||
| # in the inheritance tree are the ones which take effect. | ||
| if prop not in params and alias == UNUSED: | ||
| raise ValueError( | ||
| f"Trying to remove parameter {prop} with UNUSED which" | ||
| " doesn't exist." | ||
| ) | ||
|
|
||
| params[prop] = alias |
There was a problem hiding this comment.
Oh yes, I can see that and I agree it is more important to be simple for users and third party developers than here.
I guess to avoid going through the mro, we could also do some acrobatics with __setattr__ (or maybe not, because for this to work, the code needs to run... 🤔 and it couldn't be done at class level? ) but I am not sure this would result in simpler code.
| # need to go through the MRO since this is a class attribute and | ||
| # ``vars`` doesn't report the parent class attributes. We go through | ||
| # the reverse of the MRO so that child classes have precedence over | ||
| # their parents. | ||
| substr = f"__metadata_request__{method}" | ||
| for base_class in reversed(inspect.getmro(cls)): | ||
| for attr, value in vars(base_class).items(): | ||
| # we don't check for equivalence since python prefixes attrs | ||
| # starting with __ with the `_ClassName`. | ||
| if substr not in attr: | ||
| continue | ||
| for prop, alias in value.items(): | ||
| # Here we add request values specified via those class attributes | ||
| # to the `MetadataRequest` object. Adding a request which already | ||
| # exists will override the previous one. Since we go through the | ||
| # MRO in reverse order, the one specified by the lowest most classes | ||
| # in the inheritance tree are the ones which take effect. | ||
| if prop not in params and alias == UNUSED: | ||
| raise ValueError( | ||
| f"Trying to remove parameter {prop} with UNUSED which" | ||
| " doesn't exist." | ||
| ) | ||
|
|
||
| params[prop] = alias |
There was a problem hiding this comment.
More a high level / philosophical question, that is not well thought through and also cannot be easily answered:
This module loops so often over similar things, that I wonder if there could be a does-it-all helper function that catches all kinds of information - needed or not - and can be run when needed (or even eagerly?). This is all fast and in my basic understanding performance is not something we need to worry about here.
I wonder if that would simplify maintaining the code in this module.
|
Concerning the CI failure, see #31722. |
Co-authored-by: Stefanie Senger <[email protected]>
Co-authored-by: Stefanie Senger <[email protected]>
StefanieSenger
left a comment
There was a problem hiding this comment.
I went through this PR again and have one suggestion that would lead to some de-nesting and simplification: I think we can entirely remove _get_default_requests and _build_request_for_signature that only is called by the former.
A question: Can you explain whether _routing_repr is different from __repr__ or if it could only be different / is different in theory? I don't see that it is in fact different, but had assumed you had plans to build on it for #31535. I would tend to not make a destinction and just use the __repr__ especially if there is no concrete plan yet.
The rest looks all fine to me.
For the future, I wonder if we could work on only allowing instances as obj and owner, not strings, which we only use in the tests and in splitters like cross_validate. That reduces more complexity.
| This method combines the information present in ``__metadata_request__*`` | ||
| class attributes, as well as determining request keys from method | ||
| signatures. |
There was a problem hiding this comment.
I wonder if we still need _get_default_requests and _build_request_for_signature when we now have _get_class_level_metadata_request_values, which is doing the same.
_get_default_requests is now only used in two places (1._get_metadata_request and 2. _PassthroughScorer, where it is getting removed from via #31898). In the else branch in _get_metadata_request, it might not be needed. I will have to try that to be sure.
There was a problem hiding this comment.
There was a problem hiding this comment.
Ooh that's genius! Awesome!
We have this code: def _routing_repr(obj):
try:
return obj._routing_repr()
except AttributeError:
if isinstance(obj, str):
return obj
else:
return type(obj).__name__We can't use |
|
@OmarManzoor wanna have another look, since this has changed quite a bit since you reviewed? |
OmarManzoor
left a comment
There was a problem hiding this comment.
@adrinjalali some of the changes are confusing as they seem to be the same as those that we merged with the other PR.
OmarManzoor
left a comment
There was a problem hiding this comment.
Minor comments.
LGTM. Thanks @adrinjalali and @StefanieSenger!
Co-authored-by: Omar Salman <[email protected]>
|
@adrinjalali I didn't realize auto merge was already enabled and merged main. |
Co-authored-by: Omar Salman <[email protected]> Co-authored-by: Stefanie Senger <[email protected]>
The goal of this refactoring is to have the actual instance as the
ownerinMetadataRequestobject, which is needed for the work in visualising the routing (PR coming).As a consequence, the
reprof the owners is used now in error messages instead, so the tests are fixed.Depends on: #31898