Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
efb0e90
Use full training labels for holdout classification scoring
AryanRG Oct 19, 2026
dd0c080
Align sampled scoring probabilities and cache training labels
AryanRG Oct 19, 2026
93b8931
Preserve custom metric label inference and isolate callback labels
AryanRG Oct 19, 2026
e304645
Handle single-class boosted samples in multiclass log loss
AryanRG Oct 20, 2026
44755c2
Merge branch 'main' into fix-holdout-classification-labels
thinkall Oct 26, 2026
5b3678e
Align public probabilities with the full class set
AryanRG Oct 26, 2026
57e6f84
Align binary sample probabilities and preserve non-finite output
AryanRG Oct 26, 2026
8a7619f
Preserve native class axes for sampled classifiers
AryanRG Oct 27, 2026
5920855
Preserve native class alignment after rejected refits
AryanRG Oct 27, 2026
a36076d
Preserve legacy probability order and clear empty replay labels
AryanRG Oct 27, 2026
aaa3b67
Merge branch 'main' into fix-holdout-classification-labels
thinkall Oct 31, 2026
60cf23f
Merge branch 'main' into fix-holdout-classification-labels
thinkall Nov 2, 2026
7be8106
Merge branch 'main' into fix-holdout-classification-labels
thinkall Nov 6, 2026
f988351
Restore installed preprocessing after rejected refits
AryanRG Nov 6, 2026
30e3c72
Restore the installed task after rejected refits
AryanRG Nov 6, 2026
525aef1
Hold the installed model weakly during refits
AryanRG Nov 6, 2026
f925209
Merge branch 'main' into fix-holdout-classification-labels
thinkall Nov 25, 2026
11bc9b1
Align HistGB probabilities for single-class samples
AryanRG Nov 26, 2026
e4f9a0a
Strengthen HistGB holdout probability regression
AryanRG Nov 29, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 99 additions & 4 deletions flaml/automl/automl.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,24 @@
import random
import sys
import time
import weakref
from concurrent.futures import as_completed
from functools import partial
from functools import partial, wraps
from typing import Callable, List, Optional, Union

import numpy as np

from flaml import tune
from flaml.automl.logger import logger, logger_formatter
from flaml.automl.ml import (
_align_class_probabilities,
huggingface_metric_to_mode,
sklearn_metric_name_set,
spark_metric_name_dict,
train_estimator,
)
from flaml.automl.spark import DataFrame, Series, psDataFrame, psSeries
from flaml.automl.spark.utils import len_labels
from flaml.automl.state import AutoMLState, SearchState
from flaml.automl.task.factory import task_factory

Expand Down Expand Up @@ -92,6 +95,41 @@ def size(learner_classes: dict, config: dict) -> float:
return learner_class.size(config)


def _model_ref(model):
"""Return a callable that yields ``model``, holding it weakly when possible."""
if model is None:
return None
try:
return weakref.ref(model)
except TypeError:
return lambda: model


def _keep_installed_preprocessing(fit):
"""Restore the installed model's task and preprocessing if a fit fails before replacing it."""

@wraps(fit)
def wrapper(self, *args, **kwargs):
# Hold the installed model weakly so search can still free it once it is discarded.
installed = _model_ref(getattr(self, "_trained_estimator", None))
names = ("_transformer", "_label_transformer", "_classes", "_estimator_type")
preprocessing = [getattr(self, name, None) for name in names]
state = getattr(self, "_state", None)
task = getattr(state, "task", None)
try:
return fit(self, *args, **kwargs)
except BaseException:
model = installed() if installed is not None else None
if model is not None and getattr(self, "_trained_estimator", None) is model:
for name, value in zip(names, preprocessing):
setattr(self, name, value)
if state is not None:
state.task = task
raise

return wrapper


# metrics that sklearn only computes for binary targets
BINARY_ONLY_METRICS = ("roc_auc", "roc_auc_weighted", "ap", "f1")

Expand Down Expand Up @@ -803,10 +841,17 @@ def label_transformer(self):

@property
def classes_(self):
"""A numpy array of shape (n_classes,) for class labels."""
"""Class labels from the label transformer or estimator.

For local tabular classification, includes the full training class set,
including for sparse or untransformed inputs.
"""
attr = getattr(self, "_label_transformer", None)
if attr:
return attr.classes_
classes = getattr(self, "_classes", None)
if classes is not None:
return classes
attr = getattr(self, "_trained_estimator", None)
if attr:
return attr.classes_
Expand Down Expand Up @@ -907,15 +952,37 @@ def predict_proba(self, X, **pred_kwargs):
the searched learners, such as per_device_eval_batch_size.

Returns:
A numpy array of shape n * c. c is the # classes. Each element at
(i, j) is the probability for instance i to be in class j.
For local tabular classification, a numpy array of shape n * c,
where c is the number of classes. Each element at
(i, j) is the probability for instance i to be in class `classes_[j]`.
For tabular classification, classes absent from a retained sampled model
receive zero probability, including with sparse inputs or disabled
preprocessing. A single-class LightGBM, XGBoost, or HistGB sample is
normalized over its observed class; non-finite backend rows remain
non-finite. These aligned probabilities can therefore differ from the
raw output of `automl.model.predict_proba(automl.preprocess(X))`.
Requested raw scores, leaf indices and feature contributions are returned
unchanged from the backend instead of being aligned as probabilities.
Spark outputs are returned unchanged in their backend format.
"""
estimator = getattr(self, "_trained_estimator", None)
if estimator is None:
logger.warning("No estimator is trained. Please run fit with enough budget.")
return None
X = self._state.task.preprocess(X, self._transformer)
proba = self._trained_estimator.predict_proba(X, **pred_kwargs)
if isinstance(proba, (psDataFrame, psSeries)):
return proba
# A failed task change can leave the previous classifier installed.
# Keep its retained native class axis aligned until the model is replaced.
if (
self._state.task.name in ("classification", "binary", "multiclass")
or getattr(self, "_classes", None) is not None
) and not any(pred_kwargs.get(option) for option in ("raw_score", "pred_leaf", "pred_contrib")):
# Match the estimator's encoded or native labels to the full class set.
# Raw scores, leaf indices and feature contributions are not probabilities.
labels = np.arange(len(self.classes_)) if self._label_transformer else self.classes_
Comment thread
Copilot marked this conversation as resolved.
Resolved
proba = _align_class_probabilities(proba, estimator, labels)
return proba

def preprocess(
Expand Down Expand Up @@ -1013,6 +1080,7 @@ def get_estimator_from_log(self, log_file_name: str, record_id: int, task: str |
)
return estimator

@_keep_installed_preprocessing
def retrain_from_log(
self,
log_file_name,
Expand Down Expand Up @@ -1227,6 +1295,7 @@ def retrain_from_log(
from .model import BaseEstimator as Estimator

self._trained_estimator = Estimator()
self._classes = None
return training_duration
if not best:
return
Expand Down Expand Up @@ -1276,6 +1345,7 @@ def retrain_from_log(
best_config,
sample_size=sample_size,
)[0]
self._classes = self._state.native_classes
logger.info("retrain from log succeeded")
return training_duration

Expand Down Expand Up @@ -1849,6 +1919,9 @@ def metric_constraints(self) -> list:
return self._metric_constraints

def _prepare_data(self, eval_method, split_ratio, n_splits):
# Reset on every fit, including when the same AutoML changes tasks.
self._state.holdout_labels = None
self._state.native_classes = None
self._state.task.prepare_data(
self._state,
self._X_train_all,
Expand All @@ -1862,8 +1935,27 @@ def _prepare_data(self, eval_method, split_ratio, n_splits):
self._sample_weight_full,
self._allow_label_overlap,
)
native_class_axis = (
self._state.task.name in ("classification", "binary", "multiclass")
and not self._label_transformer
and not isinstance(self._state.y_train_all, psSeries)
)
if (
(eval_method == "holdout" or native_class_axis)
and self._state.task.is_classification()
and not self._state.task.is_token_classification()
and self._state.y_train_all is not None
):
_, labels = len_labels(self._state.y_train_all, return_labels=True)
# Do not retain a live pandas-on-Spark object in serialized state.
labels = labels.to_numpy() if isinstance(labels, psSeries) else labels
if eval_method == "holdout":
self._state.holdout_labels = labels
if native_class_axis:
self._state.native_classes = labels
self.data_size_full = self._state.data_size_full

@_keep_installed_preprocessing
def fit(
self,
X_train=None,
Expand Down Expand Up @@ -3286,6 +3378,9 @@ def _search(self):
self._iter_per_learner_fullsize = {e: 0 for e in self.estimator_list}
self._fullsize_reached = False
self._trained_estimator = None
# Publish the prepared axis only once the previous model is discarded.
# Setup errors before search must not relabel the still-installed model.
self._classes = self._state.native_classes
self._best_estimator = None
self._retrained_config = {}
self._warn_threshold = 10
Expand Down
75 changes: 72 additions & 3 deletions flaml/automl/ml.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,19 @@
# * project root for license information.
import logging
import time
from copy import copy
from typing import Callable, Optional, Tuple, TypeVar, Union

import numpy as np
from sklearn.ensemble import HistGradientBoostingClassifier
from xgboost import XGBClassifier

from flaml.automl.data import group_counts
from flaml.automl.model import BaseEstimator, TransformersEstimator
from flaml.automl.model import BaseEstimator, LGBMClassifier, TransformersEstimator
from flaml.automl.spark import ERROR as SPARK_ERROR
from flaml.automl.spark import DataFrame, Series, psDataFrame, psSeries
from flaml.automl.spark.utils import len_labels
from flaml.automl.task.factory import task_factory
from flaml.automl.task.task import Task
from flaml.automl.time_series import TimeSeriesDataset

Expand Down Expand Up @@ -350,7 +355,11 @@ def compute_estimator(
log_training_metric: Optional[bool] = False,
fit_kwargs: Optional[dict] = None,
free_mem_ratio=0,
y_train_all=None,
training_labels=None,
):
if isinstance(task, str):
task = task_factory(task, X_train, y_train)
if fit_kwargs is None:
fit_kwargs = {}

Expand All @@ -376,6 +385,19 @@ def compute_estimator(
fit_kwargs["y_val"] = y_val

if "holdout" == eval_method:
labels = fit_kwargs.get("label_list") # pass the label list on to compute the evaluation metric
if (
labels is None
and isinstance(eval_metric, str)
and y_train is not None
and task.is_classification()
and not task.is_token_classification()
):
# Match evaluate_model_CV: a trial's sample can omit a class, so use
# the full training targets when choosing labels for its metric.
labels = training_labels
Comment thread
thinkall marked this conversation as resolved.
Resolved
if labels is None:
_, labels = len_labels(y_train if y_train_all is None else y_train_all, return_labels=True)
val_loss, metric_for_logging, train_time, pred_time = get_val_loss(
config_dic,
estimator,
Expand All @@ -387,7 +409,7 @@ def compute_estimator(
groups_val,
eval_metric,
task,
labels=fit_kwargs.get("label_list"), # pass the label list on to compute the evaluation metric
labels=labels,
budget=budget,
log_training_metric=log_training_metric,
fit_kwargs=fit_kwargs,
Expand Down Expand Up @@ -580,6 +602,49 @@ def default_cv_score_agg_func(val_loss_folds, log_metrics_folds):
return metric_to_minimize, metrics_to_log


def _align_class_probabilities(predictions, estimator, labels):
"""Match sampled classifiers' probability columns to the supplied label order."""
if labels is None or isinstance(predictions, (psDataFrame, psSeries)):
return predictions
classes = getattr(estimator, "classes_", None)
probabilities = np.asarray(predictions)
if classes is None or probabilities.ndim != 2:
return predictions
# These binary APIs can emit an implicit second class even for a one-class fit.
# Normalize over the sole observed class before aligning binary or multiclass labels.
if (
len(classes) == 1
and probabilities.shape[1] == 2
and len(np.unique(labels)) > 1
and (
isinstance(getattr(estimator, "model", estimator), (XGBClassifier, HistGradientBoostingClassifier))
or (LGBMClassifier is not None and isinstance(getattr(estimator, "model", estimator), LGBMClassifier))
)
):
# Invalid backend rows must not become confident finite predictions.
probabilities = np.where(
np.isfinite(probabilities).all(axis=1, keepdims=True), np.ones_like(probabilities[:, :1]), np.nan
)
if probabilities.shape[1] != len(classes):
return predictions
labels = np.asarray(labels)
if np.array_equal(classes, labels):
return predictions
positions = {label: index for index, label in enumerate(labels)}
if any(label not in positions for label in classes):
return predictions
aligned = np.zeros((len(probabilities), len(labels)), dtype=probabilities.dtype)
aligned[:, [positions[label] for label in classes]] = probabilities
return aligned


def _align_log_loss_probabilities(predictions, estimator, labels):
"""Align probability columns to sklearn log_loss's sorted label order."""
if labels is None or isinstance(predictions, (psDataFrame, psSeries)):
return predictions
return _align_class_probabilities(predictions, estimator, np.unique(labels))


def _eval_estimator(
config,
estimator,
Expand All @@ -598,6 +663,8 @@ def _eval_estimator(
if isinstance(eval_metric, str):
pred_start = time.time()
val_pred_y = get_y_pred(estimator, X_val, eval_metric, task)
if eval_metric == "log_loss":
val_pred_y = _align_log_loss_probabilities(val_pred_y, estimator, labels)
Comment thread
Copilot marked this conversation as resolved.
Resolved

# TODO: why are integer labels being cast to str in the first place?

Expand Down Expand Up @@ -637,6 +704,8 @@ def _eval_estimator(
# aligned and avoid empty prediction inputs.
X_train_for_metric = X_val.X_train if isinstance(X_val, TimeSeriesDataset) else X_train
train_pred_y = get_y_pred(estimator, X_train_for_metric, eval_metric, task)
if eval_metric == "log_loss":
train_pred_y = _align_log_loss_probabilities(train_pred_y, estimator, labels)
metric_for_logging["train_loss"] = metric_loss_score(
eval_metric,
train_pred_y,
Expand All @@ -650,7 +719,7 @@ def _eval_estimator(
X_val,
y_val,
estimator,
labels,
copy(labels),
X_train,
y_train,
weight_val,
Expand Down
2 changes: 2 additions & 0 deletions flaml/automl/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,8 @@ def _compute_with_config_base(
state.log_training_metric,
this_estimator_kwargs,
state.free_mem_ratio,
y_train_all=state.y_train_all,
training_labels=getattr(state, "holdout_labels", None),
)
if state.retrain_final and not state.model_history:
trained_estimator.cleanup()
Expand Down
Loading
Loading