Skip to content

ENH Make callbacks metadata routers - #34137

Merged
jeremiedbb merged 128 commits into
scikit-learn:mainfrom
FrancoisPgm:callback_metadatarouting
Nov 30, 2026
Merged

jeremiedbb merged 128 commits into
scikit-learn:mainfrom
FrancoisPgm:callback_metadatarouting

Conversation

@FrancoisPgm

@FrancoisPgm FrancoisPgm commented May 27, 2026 •

Copy link
Copy Markdown
Member

Reference Issues/PRs

Potential fix for #34068

What does this implement/fix? Explain your changes.

This makes callbacks and callback-compatible estimators metadata routers. FitCallback is now a base class that inherits from _MetadataRequester, so a callback can request metadata with set_on_fit_task_begin_request and set_on_fit_task_end_request. The routed values are passed to the hook as keyword arguments. Each requested name must be a keyword-only parameter of the hook.

The main usecase for the routing at the moment is routing metadata to ScoringMonitor scorers, including sample_weight, and routing X_val / y_val so a scorer can run on validation data. ScoringMonitor now uses two scorers, scoring_train and scoring_val. Train and validation scores are stored separately on ScoringMonitorLog (train_scores / val_scores, and the corresponding *_as_pandas properties). Validation scoring requires metadata routing.
An estimator that is not a metadata router can still be used with callbacks, but with limited functionalities.

When using folds on X, in _fit_and_score, callback parameters that are sample aligned with X are sliced with the training indices. X_val and y_val are always left unsliced since they cannot correspond to the same samples as X.

Routing when metadata routing is enabled

Metadata is processed twice before a hook sees it. ScoringMonitor adds a third processing, from the hook down to its scorers.

  1. Estimator → callback list. The estimator now holds callbacks in a MultiCallback object rather than a list. When it calls process_routing, fit gets mapped to on_fit_task_begin and on_fit_task_end, producing a bunch of the form : routed_params = {"callback": {"on_fit_task_begin": ..., "on_fit_task_end":...}} that is shared by every callback. The estimator then calls call_on_fit_task_* with metadata=routed_params.callback.on_fit_task_*.

  2. Callback list → one callback. call_on_fit_task_* calls process_routing again, on the MultiCallback. Its children are callback_0, callback_1, and so on, in set_callbacks order. So it produces a bunch of the form : metadata = {"callback_0": {"on_fit_task_*": ...}, "callback_1": {"on_fit_task_*": ...}}.
    Then _call_hooks reads metadata["callback_i"][hook_name] and passes those keys to callback i.

  3. ScoringMonitor → scorers. ScoringMonitor.get_metadata_routing requests X_val and y_val on on_fit_task_end when a validation scorer is set, and routes the remaining score parameters to scorer_train.score and scorer_val.score.

Routing when metadata routing is disabled

Only sample_weight is forwarded, and only to hooks for which the callback overrides _accept_sample_weight to return True. The same two bunchs are built by hand:

  1. _get_manual_callback_params builds the first mapping to each hook, if any callback accepts sample_weight on that hook.

  2. _get_manual_routing_params turns that mapping into callback_i entries for the callbacks that accept it. _call_hooks then uses the same keys as in the routing-enabled path.

Any other comments?

Here's a typical example use case that this PR enables:

import numpy as np
import sklearn
from sklearn.callback import ScoringMonitor
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import get_scorer, make_scorer
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

sklearn.set_config(enable_metadata_routing=True)

X, y = make_classification()
amount = np.random.randint(0, 20, size=X.shape[0])

X_train, X_val, y_train, y_val, amount_train, amount_val = train_test_split(X, y, amount)

# custom metric with sample aligned additional parameter
def business_metric(y_true, y_pred, amount):
    mask_true_positive = (y_true == 1) & (y_pred == 1)
    mask_true_negative = (y_true == 0) & (y_pred == 0)
    mask_false_positive = (y_true == 0) & (y_pred == 1)
    mask_false_negative = (y_true == 1) & (y_pred == 0)
    fraudulent_refuse = mask_true_positive.sum() * 50
    fraudulent_accept = -amount[mask_false_negative].sum()
    legitimate_refuse = mask_false_positive.sum() * -5
    legitimate_accept = (amount[mask_true_negative] * 0.02).sum()
    return fraudulent_refuse + fraudulent_accept + legitimate_refuse + legitimate_accept

# actually allows different scorers for train vs val if ever wanted
scorer_train = make_scorer(business_metric).set_score_request(amount="amount_train")
scorer_val = make_scorer(business_metric).set_score_request(amount="amount_val")

cb = ScoringMonitor(scoring_train=scorer_train, scoring_val=scorer_val)

pipe = Pipeline(
    [
        ("scale", StandardScaler()),
        ("lr", LogisticRegression(max_iter=1000).set_callbacks(cb))
    ],
    transform_input=["X_val"]
)

gs = GridSearchCV(pipe, param_grid={"lr__C": [0.01, 0.1, 1, 10, 100]})
gs.fit(X_train, y_train, X_val=X_val, y_val=y_val, amount_train=amount_train, amount_val=amount_val)

print(cb.get_logs().val_scores_as_pandas)

          task_id_path parent_task_id_path      estimator_name   task_name  task_id  sequential_subtasks    score
0            (0, 1, 1)              (0, 1)  LogisticRegression         fit        1                 True  1206.60
1         (0, 0, 0, 1)           (0, 0, 0)  LogisticRegression         fit        1                 True   849.94
2         (0, 0, 1, 1)           (0, 0, 1)  LogisticRegression         fit        1                 True  1109.94
3         (0, 0, 2, 1)           (0, 0, 2)  LogisticRegression         fit        1                 True   979.84
4         (0, 0, 3, 1)           (0, 0, 3)  LogisticRegression         fit        1                 True  1106.40
..                 ...                 ...                 ...         ...      ...                  ...      ...
426  (0, 0, 24, 1, 25)       (0, 0, 24, 1)  LogisticRegression  lbfgs-iter       25                 True  1407.28
427  (0, 0, 24, 1, 26)       (0, 0, 24, 1)  LogisticRegression  lbfgs-iter       26                 True  1407.28
428  (0, 0, 24, 1, 27)       (0, 0, 24, 1)  LogisticRegression  lbfgs-iter       27                 True  1407.28
429  (0, 0, 24, 1, 28)       (0, 0, 24, 1)  LogisticRegression  lbfgs-iter       28                 True  1407.28
430  (0, 0, 24, 1, 29)       (0, 0, 24, 1)  LogisticRegression  lbfgs-iter       29                 True  1407.28

[431 rows x 7 columns]

@jeremiedbb jeremiedbb added this to Labs May 28, 2026
@jeremiedbb jeremiedbb moved this to In progress in Labs May 28, 2026


@skip_callback_test_if_wasm
def test_search_callbacks_receive_sample_weight():

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.

This test was added when sample_weight was manually passed to all callbacks (if present in the fit_params). Now sample_weight can be requested by a callback when metadata routing is enabled. But when it is not enabled, the automatic forwarding of sample_weight to the hooks will not work, as the requested params of callback hooks are not present in the hooks' signatures.

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.

EDIT: Actually sample_weight in callbacks should also work with metadata routing disabled, so now the code paths when _routing_enabled() is False forward sample_weight to the callback hooks. So the test mentioned in the previous comment has been reinstated, adapted to the current version. Similar tests for LogisticRegression, StandardScaler and MaxiterEstimator have been added.

@FrancoisPgm
FrancoisPgm marked this pull request as ready for review June 8, 2026 09:11
Comment thread sklearn/callback/_callback_context.py Resolved
Comment thread sklearn/callback/_callback_context.py Resolved
Comment thread sklearn/callback/_callback_context.py Resolved
Comment thread sklearn/callback/tests/_utils.py Resolved
Comment thread sklearn/callback/_scoring_monitor.py Resolved
Comment thread sklearn/callback/_scoring_monitor.py Resolved
Comment thread sklearn/callback/_scoring_monitor.py Resolved
Comment thread sklearn/callback/_scoring_monitor.py Resolved
@github-actions github-actions Bot added the CI:Linter failure The linter CI is failing on this PR label Jun 10, 2026
@github-actions github-actions Bot removed the CI:Linter failure The linter CI is failing on this PR label Jun 10, 2026
@ogrisel

ogrisel commented Jun 12, 2026 •

Copy link
Copy Markdown
Member

The ScoringMonitor example should be minimally be updated as part of this PR to use scoring_train= instead of scoring=. Otherwise it breaks.

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

I did a final pass and pushed a series of new tests, fixes, doc improvements... Almost everything looks good so I'm approving the PR and I think we can merge as is. There's still a major issue that I found during my last round of review that I'll explain below but I think that we can decide to deal with it later.

Routing does not work for auto propagated callbacks: An auto propagated callback requesting some metadata and registered on a meta estimator does not recieve that metadata by the hook calls from the sub-estimator.

The reason is that the whole routing is built statically at the beginning of fit of the meta-estimator. At that time, the sub-estimator doesn't have the propagated callback yet, so the metadata is not routed to it.

The main issue is the fundamental difference between metadata routing that is completely static and callbacks that are dynamic. There are ways to still be able to route the metadata to sub-estimators, no that complicated, but I think it's acceptable to implement that in a follow up PR. Indeed the only callback requesting metadata so far is not auto-propagated.

@FrancoisPgm

Copy link
Copy Markdown
Member Author

@ogrisel @jeremiedbb do you think this can get merged today ? Otherwise it won't be included in the release.

@jeremiedbb
jeremiedbb merged commit 167762c into scikit-learn:main Nov 30, 2026
39 checks passed
@github-project-automation github-project-automation Bot moved this from PR waiting for reviews to Done in Labs Nov 30, 2026
@StefanieSenger

Copy link
Copy Markdown
Member

Great, congratulations everyone! 🎉

csadorf added a commit to NVIDIA/cuml that referenced this pull request Dec 1, 2026
## Summary

Fixes the 10 failures in the nightly-dependency wheel tests.

- Keeps the upstream inference-state check active by recording opaque
GPU objects by identity in its per-attribute diagnostics. The
whole-estimator comparison and production serialization stay unchanged.
scikit-learn/scikit-learn#34729
- Routes extra `LogisticRegression.fit` keywords to scikit-learn for
callback metadata routing and validation. Fits that only use the
existing arguments stay eligible for GPU execution.
- Tests metadata consumption through the public API for both
`MetadataRequest` and `MetadataRouter`, while retaining the exact
request checks on older versions.
scikit-learn/scikit-learn#34137

## Validation

Rebuilt cuML locally and ran `test_core.py` and
`test_estimator_proxy.py` on an RTX PRO 6000: 392 passed on scikit-learn
`1.10.dev0`, and 388 passed on `1.9.1`.

Closes #8976
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.

6 participants