Repository navigation
FIX (SLEP6) descriptor shouldn't override method - #32111
Conversation
Co-authored-by: Omar Salman <[email protected]>
…into slep6/refactor
Co-authored-by: Stefanie Senger <[email protected]>
Co-authored-by: Stefanie Senger <[email protected]>
…learn into slep6/pipeline/score
Co-authored-by: Omar Salman <[email protected]>
Co-authored-by: Omar Salman <[email protected]>
adrinjalali
left a comment
There was a problem hiding this comment.
Thanks for the careful review, @StefanieSenger, and for actually rebuilding to check. Your observation is correct as far as main alone goes: LogisticRegressionCV.set_score_request() looks the same with and without this PR, because LogisticRegressionCV.score itself still declares sample_weight. The visible change for LogisticRegressionCV only materializes once #30859 lands, which is the reason this PR exists.
The chain is:
- In #30859-disussion,
LogisticRegressionCVgets__metadata_request__score = {"sample_weight": metadata_routing.UNUSED}(with aTODO(1.9): remove this when sample_weight is removed from the score signature). - @antoinebaker then noticed that, even with that marker,
LogisticRegressionCV().set_score_requeststill acceptssample_weight. - The reason is in
_MetadataRequester.__init_subclass__: theUNUSEDmarker leavesrequestsempty,main'sif not requests: continueshort-circuits, no descriptor is installed onLogisticRegressionCV, and so it inheritsLogisticRegression'sset_score_requestwhich defeats the marker. - This PR fixes that: when
requestsis empty but the class would inherit aRequestMethodfrom a parent, install an emptyRequestMethodto shadow it.
The same code path also covers the second case — a class that defines set_{method}_request by hand (as _BaseScorer does, and third-party scorers / estimators may do). On main, any subclass whose method exposes metadata would overwrite the explicit definition with a generated descriptor; with this PR the explicit method is detected via inspect.getattr_static and left alone. You're right that, today in-tree, no class other than _BaseScorer defines set_score_request explicitly and no in-tree scorer subclass has a score with metadata, so this branch is mostly there for third-party libraries and forward compatibility.
The reproducer below stitches both into a single script. It works against this branch alone by (a) simulating #30859 with a LogisticRegressionCV subclass that carries the UNUSED marker, and (b) monkey-patching _MetadataRequester.__init_subclass__ back to main's body so you can see the contrast in the same process.
Reproducer (Python)
import inspect
from sklearn import set_config
set_config(enable_metadata_routing=True)
from sklearn.base import BaseEstimator
from sklearn.linear_model import LogisticRegressionCV
from sklearn.utils import metadata_routing
from sklearn.utils._metadata_requests import (
_MetadataRequester, RequestMethod, SIMPLE_METHODS,
)
def run_scenarios(label):
print(f"\n--- {label} ---")
# Case 1: the actual #30859 scenario — UNUSED marker on a subclass whose
# parent's score() accepts sample_weight.
class LR_CV_30859(LogisticRegressionCV):
__metadata_request__score = {
"sample_weight": metadata_routing.UNUSED,
}
print("Case 1 (#30859: LR_CV + __metadata_request__score = UNUSED):")
print(f" parent params: {list(inspect.signature(LogisticRegressionCV.set_score_request).parameters)[1:]}")
print(f" subclass params: {list(inspect.signature(LR_CV_30859.set_score_request).parameters)[1:]}")
# Case 2: a parent defines set_score_request explicitly (third-party / _BaseScorer style).
class P(BaseEstimator):
def set_score_request(self, sample_weight=None, metadata=None):
return self
class C(P):
def score(self, X, y, sample_weight=None):
return 0
print("Case 2 (explicit method on parent):")
print(f" P.set_score_request kind: {type(P.__dict__['set_score_request']).__name__}")
print(f" C.set_score_request kind: "
f"{type(C.__dict__.get('set_score_request')).__name__} (None == inherited)")
# 1) Run with this PR's logic.
run_scenarios("with PR #32111")
# 2) Restore main's pre-fix __init_subclass__ and run again.
def main_init_subclass(cls, **kwargs):
try:
for method in SIMPLE_METHODS:
requests = cls._get_class_level_metadata_request_values(method)
if not requests:
continue
setattr(cls, f"set_{method}_request",
RequestMethod(method, sorted(requests)))
except Exception:
pass
super(_MetadataRequester, cls).__init_subclass__(**kwargs)
_MetadataRequester.__init_subclass__ = classmethod(main_init_subclass)
run_scenarios("with main (pre-fix logic)")Output on this branch:
--- with PR #32111 ---
Case 1 (#30859: LR_CV + __metadata_request__score = UNUSED):
parent params: ['sample_weight']
subclass params: []
Case 2 (explicit method on parent):
P.set_score_request kind: function
C.set_score_request kind: NoneType (None == inherited)
--- with main (pre-fix logic) ---
Case 1 (#30859: LR_CV + __metadata_request__score = UNUSED):
parent params: ['sample_weight']
subclass params: ['sample_weight'] # UNUSED ignored
Case 2 (explicit method on parent):
P.set_score_request kind: function
C.set_score_request kind: RequestMethod # parent's explicit method shadowed
So short version: on plain main, you won't see a LogisticRegressionCV.set_score_request docstring change from this PR: your observation is correct. The change is invisible until #30859's __metadata_request__score = UNUSED ships. The two PRs are paired: this one makes the UNUSED marker actually take effect across inheritance.
| .. [1] https://www.python.org/dev/peps/pep-0487 | ||
| """ | ||
|
|
||
| def is_RequestMethod(obj, name: str): |
There was a problem hiding this comment.
this is inside a function, and not exposed to the user, so doesn't matter what it's called.
| def is_RequestMethod(obj, name: str): | ||
| value = inspect.getattr_static(obj, name) | ||
| return isinstance(value, RequestMethod) |
There was a problem hiding this comment.
getattr_static is very different from going through the MRO, so I don't think they can be merged.
|
|
||
| try: | ||
| for method in SIMPLE_METHODS: | ||
| set_method_name = f"set_{method}_request" |
There was a problem hiding this comment.
it's the method name though, not a method request.
| # metadata with an UNUSED marker, and that the parent class has | ||
| # the method already. In this case, we cannot remove the method | ||
| # since it exists in the parent class, and instead we set it with | ||
| # an empty set of requests. |
There was a problem hiding this comment.
right, updated where the comment goes + added a comment here.
There was a problem hiding this comment.
Thanks for your comments and adjustments, @adrinjalali.
I had another look and I think this is alright, but I've made a suggestion for readability in __init_subclass__ by adding helper functions. Also the comments are a bit off.
Apart from this, it's fine, also the tests and I have approved.
Co-authored-by: Omar Salman <[email protected]> Co-authored-by: Stefanie Senger <[email protected]> Co-authored-by: Omar Salman <[email protected]>
If a class implements a
set_{method}_requestexplicitly (like done in scorers), then the descriptor shouldn't be overriding it.xref: #30859 (comment)
cc @antoinebaker @OmarManzoor
This fixes some existing issues. The added tests should represent where things were failing.