Skip to content

FEAT (alt3) allow setting auto routed strategy on objects - #31413

Merged
adrinjalali merged 52 commits into
scikit-learn:mainfrom
adrinjalali:default_routing3
Sep 22, 2026
Merged

adrinjalali merged 52 commits into
scikit-learn:mainfrom
adrinjalali:default_routing3

Conversation

@adrinjalali

Copy link
Copy Markdown
Member

This alternative allows the case for DefaultRoutingClassifier4 in the following script. I think I prefer this alternative to the other ones.

import pytest
import numpy as np
import sklearn
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_classification

sklearn.set_config(enable_metadata_routing=True, metadata_request_policy="auto")


class BaseMyClassifier(ClassifierMixin, BaseEstimator):
    __metadata_request__fit = {"sample_weight": True}

    def fit(self, X, y, sample_weight=None):
        self.classes_ = np.array([0, 1])
        print(sample_weight)
        return self

    def predict(self, X, groups=None):
        print(groups)
        return np.ones(len(X))


class DefaultRoutingClassifier1(BaseMyClassifier):
    def get_metadata_routing(self, **auto_requests):
        # Each instance can configure metadata which should be requested by default if
        # `set_config(metadata_request_policy="auto")` is set. These request values are
        # passed to the parent's `get_metadata_routing` method.
        return super().get_metadata_routing(predict="groups")


class DefaultRoutingClassifier2(BaseMyClassifier):
    def get_metadata_routing(self):
        return super().get_metadata_routing_with_auto_requests(predict="groups")


class DefaultRoutingClassifier3(BaseMyClassifier):
    def __sklearn_get_auto_requests__(self):
        return {"predict": ["groups"]}


class DefaultRoutingClassifier4(BaseMyClassifier):
    def get_metadata_routing(self):
        requests = super().get_metadata_routing()
        requests.predict.add_auto_request("groups")
        return requests


X, y = make_classification()

print("case 1")
pipeline = Pipeline(
    [
        (
            "scaler",
            StandardScaler()
            .set_fit_request(sample_weight=False)
            .set_partial_fit_request(sample_weight=True),
        ),
        (
            "classifier",
            DefaultRoutingClassifier4().set_predict_request(groups="my_groups"),
        ),
    ]
)
pipeline.fit(X, y, sample_weight=np.ones(len(X)))
pipeline.predict(X, my_groups=np.ones(len(X)) + 1)

print("case 2")
pipeline = Pipeline(
    [
        ("scaler", StandardScaler().set_fit_request(sample_weight=False)),
        ("classifier", DefaultRoutingClassifier4()),
    ]
)
pipeline.fit(X, y, sample_weight=np.ones(len(X)))
pipeline.predict(X, groups=np.ones(len(X)) + 1)

print("case 3")
pipeline = Pipeline(
    [
        ("scaler", StandardScaler().set_fit_request(sample_weight=False)),
        ("classifier", DefaultRoutingClassifier4().set_predict_request(groups=False)),
    ]
)
pipeline.fit(X, y, sample_weight=np.ones(len(X)))
with pytest.raises(TypeError, match="Pipeline.predict got unexpected argument"):
    pipeline.predict(X, groups=np.ones(len(X)) + 1)

cc @StefanieSenger @ogrisel @antoinebaker

@github-actions

github-actions Bot commented May 22, 2025 •

Copy link
Copy Markdown

✔️ Linting Passed

All linting checks passed. Your pull request is in excellent shape! ☀️

Generated for commit: a27cee9. Link to the linter CI: here

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

I have looked through this PR and commented a bit, some questions, some suggestions for improvement.

As I think I have missed this: What is the difference in usage for the users between this PR, and the previous version of defining an auto request strategy (#31401)? Edit from 5 days later: I of cause meant the difference between this PR and what #31401 was supposed to become, not what it is.

Comment thread sklearn/_config.py Resolved
Comment thread sklearn/_config.py Resolved
Comment thread sklearn/utils/_metadata_requests.py Outdated
Comment on lines +573 to +576
def actualize_auto_requests(self):
for method in SIMPLE_METHODS:
getattr(self, method).actualize_auto_requests()
return self

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.

For simplicity, could this be a private method instead?

I don't think many people would really want to use such a low-level method.

I believe making it possible to use get_metadata_routing().{method_name}.add_auto_request() in combination with get_routing_for_object(obj) gives enough room for any fine tuning and inspection and exposing this intermediate step could be confusing and requires too much explaining of when it's useful.

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.

I don't think it matters. We have documented in the example file how people should be using it anyways.

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.

I might be misunderstanding, but I don’t see actualize_auto_requests documented in the example file.

My thought was that when third party developers call add_auto_request() and also use get_routing_for_object() (which internally calls actualize_auto_requests()) there’s no clear external use case for calling this method directly.

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.

I don't see actualize_auto_requests in plot_metadata_routing.py either, or is it documented elsewhere ?

If it's public we should add a docstring I guess.

Comment thread sklearn/utils/_metadata_requests.py Resolved
Comment thread sklearn/utils/_metadata_requests.py Outdated
Comment on lines +869 to +870
elif isinstance(obj, MetadataRouter):
self._self_request = deepcopy(obj._self_request)

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.

Could you please explain this part, @adrinjalali:

        elif isinstance(obj, MetadataRouter):
            self._self_request = deepcopy(obj._self_request)

If a MetadataRouter object is passed to another MetadataRouter object' add_self_request method, the latter overtakes the former's _self_request attribute? In which case would this happen?

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.

it really shouldn't happen. This only happens in our tests and here it covers the edge case if it happens; but I don't think it would.

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.

I guess this why the test case above was removed.

I find a method clearer to understand when there is "only one way" to call it and strict about the argument type. If I understand correctly here obj should be a router (eg meta-estimator) instance, so maybe only implement this case and raise error otherwise ?

@StefanieSenger StefanieSenger Aug 25, 2026 •

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.

I agree, @antoinebaker, but also I don't really understand the impact of this addition.

For now, I have added a TODO comment to remind us to clean this up.
Also, _self_request may be None and I added a condition here to guard against this in d450338.

@StefanieSenger StefanieSenger Aug 25, 2026 •

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.

I have seen this all fails on codecov, so we don't even user it internally and can probably safely remove it, which I did in f0b5c4e.

Comment on lines +474 to +479
# 1. Class-level defaults using `__metadata_request__method` class attributes,
# which set default request values for all instances of a class, and can even
# remove a metadata from the metadata routing machinery if necessary.
# 2. Instance-level defaults via the `add_auto_request` method, which would only
# request the metadata if ``set_config(metadata_request_policy="auto")`` is
# set.

@StefanieSenger StefanieSenger May 23, 2025 •

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.

Let's also document right here that the instance level requests will overwrite the class level requests and can be overwritten by user-set requests.

Comment thread sklearn/utils/_metadata_requests.py Resolved

@adrinjalali adrinjalali left a comment

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.

As I think I have missed this: What is the difference in usage for the users between this PR, and the previous version of defining an auto request strategy (#31401)?

There's no difference for users. The difference is only on how it's implemented.

Comment thread sklearn/utils/_metadata_requests.py Resolved
Comment thread sklearn/utils/_metadata_requests.py Outdated
Comment on lines +573 to +576
def actualize_auto_requests(self):
for method in SIMPLE_METHODS:
getattr(self, method).actualize_auto_requests()
return self

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.

I don't think it matters. We have documented in the example file how people should be using it anyways.

Comment thread sklearn/utils/_metadata_requests.py Outdated
Comment on lines +869 to +870
elif isinstance(obj, MetadataRouter):
self._self_request = deepcopy(obj._self_request)

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.

it really shouldn't happen. This only happens in our tests and here it covers the edge case if it happens; but I don't think it would.

@antoinebaker

Copy link
Copy Markdown
Member

Hello @adrinjalali and @StefanieSenger ! Sorry I think I'm a bit lost ;)

How does this new mechanism allow to solve the original intent of #30887, ie to have a config where scorers and estimators always request sample_weight (if they can) ?

For example, how could we implement a Mixin so that for all sklearn estimators, if the fit method has sample_weight in its signature, and the metadata_request_policy="auto" config is enabled, then it will automatically add sample_weight to the fit request ?

@adrinjalali

Copy link
Copy Markdown
Member Author

For example, how could we implement a Mixin so that for all sklearn estimators, if the fit method has sample_weight in its signature, and the metadata_request_policy="auto" config is enabled, then it will automatically add sample_weight to the fit request ?

The idea is not to have something that automatically requests sample_weight if it's present in the signature. The idea is to have a Mixin which adds an auto request on sample_weight and we'd use that mixin only in places where we want to have it.

Comment thread sklearn/utils/_metadata_requests.py Resolved
Comment thread sklearn/utils/_metadata_requests.py Resolved
Comment thread sklearn/utils/_metadata_requests.py Outdated
Comment on lines +1195 to +1199
if _auto_routing_enabled():
if hasattr(requests, "actualize_auto_requests"):
requests.actualize_auto_requests()
if getattr(requests, "_self_request", None):
requests._self_request.actualize_auto_requests()

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.

I guess here is where all the magic happens :)

The auto requests, defined at the instance level inside obj.get_metadata_routing(), are taken into consideration only when the auto request policy is enabled, and then added to the "default" requests, possibly overriding the class requests. The user can still specify requests afterwards. Did I get this right ?

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.

I believe so. This is at least how I also understood it.

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

Thanks for your clarifications, @adrinjalali.

For example, how could we implement a Mixin so that for all sklearn estimators, if the fit method has sample_weight in its signature, and the metadata_request_policy="auto" config is enabled, then it will automatically add sample_weight to the fit request ?

I was thinking maybe something like combining available_if(_estimator_has("fit")) with inspect.signature(func) to set the class requests in a mixin could work? And maybe use the instance-level requests for a transition period until auto routing would be the default?

@antoinebaker I might be missing some context, but it seems you where asking whether setting class requests via mixins would be possible while auto metadata routing is not the default yet. Is such a roadmap existing, @adrinjalali?

Comment thread sklearn/utils/_metadata_requests.py Resolved
Comment thread sklearn/utils/_metadata_requests.py Outdated
Comment on lines +573 to +576
def actualize_auto_requests(self):
for method in SIMPLE_METHODS:
getattr(self, method).actualize_auto_requests()
return self

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.

I might be misunderstanding, but I don’t see actualize_auto_requests documented in the example file.

My thought was that when third party developers call add_auto_request() and also use get_routing_for_object() (which internally calls actualize_auto_requests()) there’s no clear external use case for calling this method directly.

Comment thread sklearn/utils/_metadata_requests.py Outdated
Comment on lines +1195 to +1199
if _auto_routing_enabled():
if hasattr(requests, "actualize_auto_requests"):
requests.actualize_auto_requests()
if getattr(requests, "_self_request", None):
requests._self_request.actualize_auto_requests()

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.

I believe so. This is at least how I also understood it.

@adrinjalali

Copy link
Copy Markdown
Member Author

I was thinking maybe something like combining available_if(_estimator_has("fit")) with inspect.signature(func) to set the class requests in a mixin could work? And maybe use the instance-level requests for a transition period until auto routing would be the default?

It's certainly possible to inspect during runtime and do the magic, but I'd be opposed to the idea. I rather have the mixin be included only when we want to add the request, instead of checking the signature. If we want to check the signature and request metadata, then we can have a very different approach where metadata is always requested, no matter which metadata. I'm not opposed to that option, but that's a very different approach. I just don't want to special case sample_weight as a metadata in this approach. And as far as I remember from our meeting, we decided not to go down that path.

@antoinebaker

Copy link
Copy Markdown
Member

Thanks for the clarification @adrinjalali and @StefanieSenger, I was confused about the goal of the auto request policy.

The idea is not to have something that automatically requests sample_weight if it's present in the signature. The idea is to have a Mixin which adds an auto request on sample_weight and we'd use that mixin only in places where we want to have it.

If I understand correctly, would you suggest the following plan to tackle #30887 ?

  1. Have a mixin that add the auto request for sample_weight in fit
class AutoRequestSampleWeightFit():
    def get_metadata_routing(self):
        requests = super().get_metadata_routing()
        requests.fit.add_auto_request("sample_weight")
        return requests
  1. Add this mixin to the sklearn estimators that need it (currenlty we think all of them that support sample_weight in fit).

  2. Add a common estimator check that inspect the fit signature and the auto request of sample_weight to make sure that we did not forget anyone.

  3. Do the same for scorers.

  4. From the user perspective in ENH default routing policy for sample weight #30887, having to explicitly request the sample_weight for all consumers or not is a matter of config.

# current policy: need the verbose requests
sklearn.set_config(enable_metadata_routing=True, metadata_request_policy="empty")
scaler.set_fit_request(sample_weight=True)
spline.set_fit_request(sample_weight=True)
logistic.set_fit_request(sample_weight=True)
logistic.set_score_request(sample_weight=True)
pipe.set_score_request(sample_weight=True)
# new policy: no need for requests, `sample_weight` in meta-estimator works out of the box
sklearn.set_config(enable_metadata_routing=True, metadata_request_policy="auto")

@adrinjalali

Copy link
Copy Markdown
Member Author

Yep, that's how I see it @antoinebaker .

@StefanieSenger StefanieSenger moved this from PR waiting for reviews to In progress in Labs Sep 7, 2026

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

I've applied your latest review comments, @antoinebaker. Thanks again.

From my side, this PR is ready to merge, approving.

Let's wait for @adrinjalali's final look at this.

Comment thread sklearn/tests/test_metadata_routing.py Outdated
Comment on lines +1193 to +1203
@pytest.mark.parametrize(
"metadata_request_policy, default_routing",
[
("auto", True),
("class-level", False),
],
)
def test_auto_requests_disabled(metadata_request_policy, default_routing):
"""Check correctness of _auto_requests_enabled."""
with config_context(metadata_request_policy=metadata_request_policy):
assert _auto_requests_enabled() == default_routing

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.

Certainly, good you caught this. :)

Comment thread sklearn/tests/test_metadata_routing.py Outdated
def test_auto_requests_override_class_level_requests():
"""Test that instance-level auto requests override class-level default requests."""

class DefaultRoutingEstimator(BaseEstimator):

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.

I agree.

@lorentzenchr

Copy link
Copy Markdown
Member

This is already over a year old. Let me know if you need a hand to finish review and finally merge.

@StefanieSenger

Copy link
Copy Markdown
Member

This is already over a year old. Let me know if you need a hand to finish review and finally merge.

Thanks @lorentzenchr! This is in its final stages, ready to merge after @adrinjalali had a chance to react on my latest commits.

@StefanieSenger

StefanieSenger commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

I didn't see this before, but in the current implementation, auto-requests aren't really instance-level (even though we document that they are). The requests can be switched on and off on the same instance depending on the config. So they are not instance level like set_*_request, which could be really confusing for users:

from sklearn import config_context
from sklearn.base import BaseEstimator
from sklearn.utils.metadata_routing import get_routing_for_object

class Est(BaseEstimator):
    def fit(self, X, y, prop=None):
        return self

    def get_metadata_routing(self):
        requests = super().get_metadata_routing()
        requests.fit.add_auto_request("prop")
        return requests

est = Est()

with config_context(metadata_request_policy="class-level"):
    print("class-level:", get_routing_for_object(est).fit.requests.get("prop"))
    # class-level: None

with config_context(metadata_request_policy="auto"):
    print("auto:", get_routing_for_object(est).fit.requests.get("prop"))
    # auto: True

Now the question is, do we want to

  1. make auto-requests instance-level in which case we need to store them on self._requests or maybe a new self._auto_requests attribute? (advantage: really instance-level, stable)
  2. keep auto-requests config-dependant and document accordingly? (advantage: users can more easily experiment with fitted estimators)

Let's this not be a blocker. Let's merge and figure this out later in a follow-up PR.

@adrinjalali adrinjalali left a comment

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.

Looks pretty good to me, with minor edits.

I like the new config name we came up with @StefanieSenger and going through the PR, it's very consistent with how we formulate the feature in the docs and docstrings.

Comment on lines +504 to +508
# %%
# Note that setting auto-requests on *composite* methods such as `fit_transform` or
# `fit_predict` will not have an effect. Their requests are the union of the underlying
# simple methods (`fit`+`transform`, `fit`+`predict`). Call `add_auto_request` (or
# `set_*_request`) on the simple methods instead.

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.

I don't think this is true now, since we've merged this: https://github.com/scikit-learn/scikit-learn/pull/30869/changes

need to be double checked and verified

Comment thread sklearn/utils/_metadata_requests.py Resolved
return new

def actualize_auto_requests(self):
for method in SIMPLE_METHODS:

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.

So TargetEncoder has:

        router.add(
            # This works, since none of {None, int, iterable} request any metadata
            # and the machinery here would assign an empty MetadataRequest
            # to it.
            splitter=self.cv,
            method_mapping=MethodMapping().add(caller="fit_transform", callee="split"),
        )

which makes me wonder, what to do here!!!

Also note the PR where we fixed the composite methods, and we fixed an issue where requests are also directly set on composite methods

Comment thread sklearn/tests/test_metadata_routing.py Resolved

@adrinjalali adrinjalali left a comment

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.

Thanks for taking this over @StefanieSenger . LGTM.

@adrinjalali
adrinjalali merged commit 33eb036 into scikit-learn:main Sep 22, 2026
37 checks passed
@github-project-automation github-project-automation Bot moved this from PR in progress to Done in Labs Sep 22, 2026
@github-project-automation github-project-automation Bot moved this from To Review to Done in Metadata routing Sep 22, 2026
@adrinjalali
adrinjalali deleted the default_routing3 branch September 22, 2026 13:47
@StefanieSenger

StefanieSenger commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

OMG it is finally merged! 🍾
Great feature, @adrinjalali! 🥇

Also many thanks to @antoinebaker for your reviews.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Metadata Routing all issues related to metadata routing, slep006, sample props module:utils

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

5 participants