Skip to content
Open
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Fixed
- Multi-output surrogate compatibility check in `Surrogate.fit` now correctly uses the
number of required models instead of the number of transform outputs
- Surrogates now report modeled quantities with no complete measurements instead of
attempting a fit
- `SearchSpace.transform` now correctly retains encoded columns for zero-row dataframes

## [0.15.2] - 2026-11-13
### Fixed
- `BotorchRecommender` recommendation for discrete and hybrid search spaces no longer
Expand Down
20 changes: 10 additions & 10 deletions baybe/searchspace/discrete.py
Original file line number Diff line number Diff line change
Expand Up @@ -712,25 +712,25 @@ def transform(
df, self.parameters, allow_missing=allow_missing, allow_extra=allow_extra
)

# If the transformed values are not required, return an empty dataframe
if self.empty_encoding or len(df) < 1:
# Preserve the input index when no parameter encodings are needed.
if self.empty_encoding or not parameters:
return pd.DataFrame(index=df.index)

# Transform the parameters
dfs = []
for param in parameters:
comp_df = param.transform(df[param.name])
dfs.append(comp_df)
comp_rep = pd.concat(dfs, axis=1) if dfs else pd.DataFrame()
# Even zero-row inputs retain the encoded columns of the supplied parameters.
comp_rep = pd.concat([p.transform(df[p.name]) for p in parameters], axis=1)

# If the computational representation has already been built (with potentially
# removing some columns, e.g. due to decorrelation or dropping constant ones),
# any subsequent transformation should yield the same columns.
# keep its column order and reductions.
try:
return comp_rep[self.comp_rep.columns]
columns = self.comp_rep.columns
except AttributeError:
return comp_rep

if allow_missing:
columns = columns.intersection(comp_rep.columns, sort=False)
return comp_rep[columns]

def get_parameters_by_name(
self, names: Sequence[str]
) -> tuple[DiscreteParameter, ...]:
Expand Down
54 changes: 37 additions & 17 deletions baybe/surrogates/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,18 @@
from joblib.hashing import hash
from typing_extensions import override

from baybe.exceptions import IncompatibleSurrogateError, ModelNotTrainedError
from baybe.exceptions import (
IncompatibleSurrogateError,
IncompleteMeasurementsError,
ModelNotTrainedError,
)
from baybe.objectives.base import Objective
from baybe.parameters.base import Parameter
from baybe.searchspace import SearchSpace
from baybe.serialization.mixin import SerialMixin
from baybe.utils.basic import classproperty
from baybe.utils.conversion import to_string
from baybe.utils.dataframe import handle_missing_values, to_tensor
from baybe.utils.dataframe import to_tensor
from baybe.utils.scaling import ColumnTransformer

if TYPE_CHECKING:
Expand All @@ -36,6 +40,23 @@
"""Type alias for requestable statistics (a float yields the corresponding quantile)."""


def _validate_training_data(df: pd.DataFrame, name: str, /) -> None:
"""Ensure a modeled quantity has a non-empty set of training data.

Args:
df: The training data for the modeled quantity.
name: The name of the modeled quantity.

Raises:
IncompleteMeasurementsError: If the modeled quantity has no training data.
"""
if df.empty:
raise IncompleteMeasurementsError(
"Each modeled quantity requires at least one complete measurement. "
f"No complete measurements are available for '{name}'."

@Scienfitz Scienfitz Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for DesirabilityObjective(pre_transform=True) this would say "there is not compelte measurement avaialble for desirability" which imo is not optimal. The specific target names should be emtnioned

)


class _NoTransform(Enum):
"""Sentinel class."""

Expand Down Expand Up @@ -403,23 +424,20 @@ def fit(
NotImplementedError: When using a continuous search space and a non-GP
model.
"""
# TODO: consider adding a validation step for `measurements`

# Validate multi-target compatibility
if objective.is_multi_output and not self.supports_multi_output:
if objective._is_multi_model:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we specify in the docstring of this class that this is a Surrogate for single outputs? The docstring reads very general which is confusing.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And it is also extra weird that there still is the support_multi_output attribute that a child could simply set to True, even though this is not possible. Or am I misunderstanding something here?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is fishy

supports_multi_output declares a property of the surrogate class. Dropping and not self.supports_multi_output means fit now ignores that property, while _autoreplicate still relies on it. A surrogate declaring multi-output support would not be wrapped and would then always be rejected here. That no current surrogate sets the flag doesn't make the check correct.

Overall this PR makes way more incisions than I'd expect, the gut feelings ays the fix to this issue should be much simpler and not touch so many things...

raise IncompatibleSurrogateError(
f"You attempted to train a single-output surrogate in a "
f"{len(objective.targets)}-target multi-output context. Either use "
f"a proper multi-output surrogate or consider explicitly "
f"replicating the current surrogate model using its "
f"'.{self.replicate.__name__}' method."
f"You attempted to train a single-output surrogate for an objective "
f"requiring {objective._n_models} modeled quantities. Either use a "
f"CompositeSurrogate or explicitly replicate the current surrogate "
f"model using its '.{self.replicate.__name__}' method."
)

# When the context is unchanged, no retraining is necessary
measurements_hash = hash(measurements)
if (
searchspace == self._searchspace
and objective == self._objective
and hash(measurements) == self._measurements_hash
and measurements_hash == self._measurements_hash
):
return

Expand All @@ -431,14 +449,16 @@ def fit(
f"support transfer learning."
)

# Block partial measurements
handle_missing_values(measurements, [t.name for t in objective.targets])
# Block incomplete measurements
quantity_name = objective._modeled_quantity_names[0]
training_data = objective.handle_missing_values(measurements)[quantity_name]
_validate_training_data(training_data, quantity_name)

# Remember the training context
self._searchspace = searchspace
self._objective = objective
self._measurements = measurements
self._measurements_hash = hash(measurements)
self._measurements_hash = measurements_hash

# Create context-specific transformations
self._input_scaler = self._make_input_scaler(searchspace)
Expand All @@ -451,9 +471,9 @@ def fit(
# values, enabling predictions with input from the pre-transformed domain
# (this allows us to control precisely on which level the model is placed)
# * The main transformation is part of the computational backpropagation graph
pre_transformed = objective._pre_transform(measurements, allow_extra=True)
pre_transformed = objective._pre_transform(training_data, allow_extra=True)
train_x_comp_rep, train_y_tensor = to_tensor(
searchspace.transform(measurements, allow_extra=True), pre_transformed
searchspace.transform(training_data, allow_extra=True), pre_transformed
)
train_x = self._input_scaler.transform(train_x_comp_rep)
train_y = (
Expand Down
12 changes: 9 additions & 3 deletions baybe/surrogates/composite.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@
from baybe.serialization import converter
from baybe.serialization.core import _TYPE_FIELD, add_type
from baybe.serialization.mixin import SerialMixin
from baybe.surrogates.base import PosteriorStatistic, SurrogateProtocol
from baybe.surrogates.base import (
PosteriorStatistic,
SurrogateProtocol,
_validate_training_data,
)
from baybe.surrogates.gaussian_process.core import GaussianProcessSurrogate
from baybe.utils.basic import is_all_instance

Expand Down Expand Up @@ -105,9 +109,11 @@ def fit(
objective: Objective,
measurements: pd.DataFrame,
) -> None:
# See base class.
training_data = objective.handle_missing_values(measurements)
for name, data in training_data.items():
_validate_training_data(data, name)

for name, data in objective.handle_missing_values(measurements).items():
for name, data in training_data.items():
pre_transformed = objective._pre_transform(
data[[t.name for t in objective.targets]]
)
Expand Down
20 changes: 20 additions & 0 deletions tests/test_searchspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,26 @@ def test_empty_parameter_bounds():
pd.testing.assert_frame_equal(searchspace_continuous.comp_rep_bounds, expected)


@pytest.mark.parametrize("allow_missing", [False, True])
def test_empty_transform_preserves_computational_columns(allow_missing):
"""A zero-row input keeps the encoded columns of its supplied parameters."""
searchspace = SearchSpace.from_product(
[
CategoricalParameter("material", values=["A", "B"]),
NumericalDiscreteParameter("speed", values=[1.0, 2.0]),
NumericalContinuousParameter("temperature", bounds=(20.0, 100.0)),
]
)
data = pd.DataFrame({"material": ["A"], "speed": [1.0], "temperature": [30.0]})
expected = searchspace.transform(data).iloc[:0]
if allow_missing:
data = data.drop(columns="speed")
expected = expected.drop(columns="speed")

result = searchspace.transform(data.iloc[:0], allow_missing=allow_missing)
assert_frame_equal(result, expected)


def test_discrete_searchspace_creation_from_dataframe():
"""A purely discrete search space is created from an example dataframe."""
num_specified = NumericalDiscreteParameter(name="num_specified", values=[1, 2, 3])
Expand Down
86 changes: 85 additions & 1 deletion tests/test_surrogate.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
import pytest
from pytest import param

from baybe.exceptions import IncompatibleSurrogateError
from baybe.exceptions import (
IncompatibleSurrogateError,
IncompleteMeasurementsError,
)
from baybe.objectives.base import Objective
from baybe.objectives.desirability import DesirabilityObjective
from baybe.objectives.pareto import ParetoObjective
Expand Down Expand Up @@ -107,6 +110,87 @@ def test_composite_surrogates(surrogate):
)


@pytest.mark.parametrize(
"objective",
[
param(
SingleTargetObjective(NumericalTarget("unmeasured_target")),
id="single",
),
param(
DesirabilityObjective(
[
NumericalTarget("measured_target"),
NumericalTarget("unmeasured_target"),
],
scalarizer="MEAN",
require_normalization=False,
),
id="desirability",
),
param(
DesirabilityObjective(
[
NumericalTarget("measured_target"),
NumericalTarget("unmeasured_target"),
],
scalarizer="MEAN",
require_normalization=False,
as_pre_transformation=True,
),
id="desirability-pre",
),
param(
ParetoObjective(
[
NumericalTarget("measured_target"),
NumericalTarget("unmeasured_target"),
]
),
id="pareto",
),
],
)
def test_surrogate_requires_observations_for_each_modeled_quantity(
objective: Objective,
):
"""Each modeled quantity must have at least one complete measurement."""
searchspace = NumericalDiscreteParameter("p", [0, 1]).to_searchspace()
measurements = pd.DataFrame({"p": [0, 1, 0]})
measurements["measured_target"] = [1.0, 2.0, 3.0]
measurements["unmeasured_target"] = float("nan")

surrogate = GaussianProcessSurrogate()
replicate = objective._n_models > 1
model = surrogate.replicate() if replicate else surrogate
if not replicate:
measurements = measurements.iloc[:0]
with patch.object(GaussianProcessSurrogate, "_fit") as fit:
with pytest.raises(
IncompleteMeasurementsError, match="No complete measurements"
):
model.fit(searchspace, objective, measurements)
fit.assert_not_called()


def test_surrogate_rejects_objectives_with_multiple_modeled_quantities():
"""A single-output surrogate cannot model multiple quantities on its own."""
objective = DesirabilityObjective(
[NumericalTarget("t1"), NumericalTarget("t2")],
scalarizer="MEAN",
require_normalization=False,
)
assert objective.is_multi_output is False
assert objective._is_multi_model is True

searchspace = NumericalDiscreteParameter("p", [0, 1]).to_searchspace()
measurements = pd.DataFrame({"p": [0, 1], "t1": [0.1, 0.2], "t2": [0.2, 0.3]})
with patch.object(GaussianProcessSurrogate, "_fit") as fit:
with pytest.raises(IncompatibleSurrogateError, match="single-output"):
GaussianProcessSurrogate().fit(searchspace, objective, measurements)
fit.assert_not_called()
Comment on lines +188 to +191

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This reads a bit weird as you literally call a function called fit and then have fit.assert_not_called. Can we maybe rename the fit to internal_fit or similar?



@pytest.mark.parametrize(
"model_cls, params",
[
Expand Down