diff --git a/ax/adapter/tests/test_torch_adapter.py b/ax/adapter/tests/test_torch_adapter.py index dbc01252113..f520d166567 100644 --- a/ax/adapter/tests/test_torch_adapter.py +++ b/ax/adapter/tests/test_torch_adapter.py @@ -64,7 +64,10 @@ from ax.utils.testing.mock import mock_botorch_optimize from ax.utils.testing.preference_stubs import get_pbo_experiment from botorch.acquisition import LearnedObjective -from botorch.acquisition.logei import qLogNoisyExpectedImprovement +from botorch.acquisition.logei import ( + qLogNoisyExpectedImprovement, + qLogProbabilityOfFeasibility, +) from botorch.acquisition.preference import ( AnalyticExpectedUtilityOfBestOption, qExpectedUtilityOfBestOption, @@ -1723,6 +1726,55 @@ def test_plbo_with_learned_objective_and_extra_metrics(self) -> None: else: self.assertEqual(acqf_model.num_outputs, 2) + @mock_botorch_optimize + def test_plbo_with_outcome_constraints(self) -> None: + """Use the constraint-only metric for feasibility, not for utility.""" + generator = BoTorchGenerator() + adapter = TorchAdapter( + experiment=self.exp, + data=self.exp.lookup_data(), + generator=generator, + ) + # The fixture's metric1 observations are near 1000. + for bound, expected_acqf in ( + (1100.0, qLogNoisyExpectedImprovement), + (900.0, qLogProbabilityOfFeasibility), + ): + with self.subTest(bound=bound): + config = self.pref_opt_config.clone_with_args( + outcome_constraints=[ + OutcomeConstraint( + expression=f"metric1 <= {bound}", + metric_name_to_signature={ + "metric1": self.exp.get_metric("metric1").signature + }, + ) + ] + ) + gen_run = adapter.gen(n=1, optimization_config=config) + self.assertEqual(len(gen_run.arms), 1) + + acquisition = none_throws(generator._acquisition) + self.assertIsInstance(acquisition.acqf, expected_acqf) + self.assertEqual(acquisition.acqf.model.num_outputs, 3) + self.assertIsNone(acquisition.objective_thresholds) + if isinstance( + acqf := acquisition.acqf, + (qLogNoisyExpectedImprovement, qLogProbabilityOfFeasibility), + ): + constraint_fns = none_throws(acqf._constraints) + else: + self.fail(f"Unexpected acquisition function: {type(acqf)}") + self.assertEqual(len(constraint_fns), 1) + samples = torch.tensor( + [[bound - 1, 0.0, 0.0], [bound + 1, 0.0, 0.0]], + dtype=torch.double, + ) + torch.testing.assert_close( + constraint_fns[0](samples), + torch.tensor([-1.0, 1.0], dtype=torch.double), + ) + @mock_botorch_optimize def test_plbo_validation_fails_with_allowed_and_disallowed_transform(self) -> None: """Validation fails/passes when using disallowed/allowed transforms.""" diff --git a/ax/core/optimization_config.py b/ax/core/optimization_config.py index c54a09fbece..9f5869933ad 100644 --- a/ax/core/optimization_config.py +++ b/ax/core/optimization_config.py @@ -533,7 +533,7 @@ def __init__( preference profile for the experiment. An auxiliary experiment with this name and purpose PE_EXPERIMENT should be attached to the experiment. - outcome_constraints: Constraints on metrics. Not yet supported. + outcome_constraints: Constraints on metrics. expect_relativized_outcomes: Whether the learned objective expects outcomes in relative percentage scale (e.g., -1 means -1% change vs. status quo) after transforms. When True, TorchAdapter validates that a @@ -558,13 +558,6 @@ def __init__( "Use `OptimizationConfig` instead if using a " "single-metric objective." ) - if outcome_constraints: - raise NotImplementedError( - "Outcome constraints are not yet supported in " - "PreferenceOptimizationConfig" - ) - - # Call parent's __init__ with objective_thresholds=None super().__init__( objective=objective, outcome_constraints=outcome_constraints, diff --git a/ax/core/tests/test_optimization_config.py b/ax/core/tests/test_optimization_config.py index 91a27fbb74a..819a0f4923d 100644 --- a/ax/core/tests/test_optimization_config.py +++ b/ax/core/tests/test_optimization_config.py @@ -651,23 +651,35 @@ def test_Init(self) -> None: self.assertEqual(config.objective, self.multi_objective) self.assertEqual(config.outcome_constraints, []) - # Test that outcome_constraints are not supported - with self.assertRaisesRegex( - NotImplementedError, "Outcome constraints are not yet supported" - ): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - PreferenceOptimizationConfig( - objective=self.multi_objective, - preference_profile_name=self.preference_profile_name, - outcome_constraints=[ - OutcomeConstraint( - metric=self.metrics["metric1"], - op=ComparisonOp.LEQ, - bound=0.5, - ) - ], - ) + constraints = [ + OutcomeConstraint( + expression="metric1 <= 0.5", + metric_name_to_signature={"metric1": self.metrics["metric1"].signature}, + ) + ] + constrained = PreferenceOptimizationConfig( + objective=self.multi_objective, + preference_profile_name=self.preference_profile_name, + outcome_constraints=constraints, + ) + self.assertEqual(constrained.outcome_constraints, constraints) + self.assertEqual(constrained.all_constraints, constraints) + self.assertEqual(constrained.objective_thresholds, []) + + cloned = assert_is_instance(constrained.clone(), PreferenceOptimizationConfig) + self.assertEqual(cloned.outcome_constraints, constraints) + self.assertIsNot(cloned.outcome_constraints[0], constraints[0]) + self.assertEqual( + constrained.clone_with_args(outcome_constraints=None).outcome_constraints, + [], + ) + + with self.assertRaisesRegex(ValueError, "Duplicate outcome constraints"): + PreferenceOptimizationConfig( + objective=self.multi_objective, + preference_profile_name=self.preference_profile_name, + outcome_constraints=constraints * 2, + ) def test_Eq(self) -> None: config1 = PreferenceOptimizationConfig( diff --git a/ax/generators/torch/botorch_modular/acquisition.py b/ax/generators/torch/botorch_modular/acquisition.py index 4dfda6c11ff..2522cf00bfb 100644 --- a/ax/generators/torch/botorch_modular/acquisition.py +++ b/ax/generators/torch/botorch_modular/acquisition.py @@ -310,6 +310,7 @@ def _update_objective_thresholds(self, torch_opt_config: TorchOptConfig) -> None """ if not ( torch_opt_config.is_moo + and not torch_opt_config.use_learned_objective and ( self._objective_thresholds is None or self._objective_thresholds.isnan().any() diff --git a/ax/generators/torch/botorch_modular/generator.py b/ax/generators/torch/botorch_modular/generator.py index 70a2ef744f9..fc94f73d0b6 100644 --- a/ax/generators/torch/botorch_modular/generator.py +++ b/ax/generators/torch/botorch_modular/generator.py @@ -563,10 +563,20 @@ def _instantiate_acquisition( self._user_specified_botorch_acqf_class is None and self._botorch_acqf_classes_with_options is None ): + datasets = self.surrogate.training_data + if torch_opt_config.use_learned_objective: + # The auxiliary preference data lives in outcome space, not in the + # search space used to check feasibility of observed designs. + outcome_names = set(self.surrogate.outcomes) + datasets = [ + dataset + for dataset in datasets + if outcome_names.issuperset(dataset.outcome_names) + ] self._botorch_acqf_class = choose_botorch_acqf_class( search_space_digest=search_space_digest, torch_opt_config=torch_opt_config, - datasets=self.surrogate.training_data, + datasets=datasets, use_p_feasible=self.use_p_feasible, ) return self.acquisition_class( diff --git a/ax/generators/torch/utils.py b/ax/generators/torch/utils.py index 8fb063fe5c4..b0d970dadaf 100644 --- a/ax/generators/torch/utils.py +++ b/ax/generators/torch/utils.py @@ -81,6 +81,21 @@ def extract_objectives( ) +class _SubsetLearnedObjective(LearnedObjective): + """Evaluate learned utility on the objective columns of the posterior samples.""" + + def __init__(self, pref_model: Model, outcome_indices: Tensor) -> None: + super().__init__(pref_model=pref_model) + self._outcome_indices: Tensor + self.register_buffer("_outcome_indices", outcome_indices) + + def forward(self, samples: Tensor, X: Tensor | None = None) -> Tensor: + """Keep constraint-only columns out of the preference model's input.""" + return super().forward( + samples=samples.index_select(dim=-1, index=self._outcome_indices), X=X + ) + + @dataclass class SubsetModelData: model: Model @@ -370,14 +385,25 @@ def get_botorch_objective_and_transform( (optionally) a `PosteriorTransform`. """ - if learned_objective_preference_model is not None: - objective = LearnedObjective(pref_model=learned_objective_preference_model) - return objective, None # qLogProbabilityOfFeasibility uses constraints only, not objectives or # posterior transforms. if issubclass(botorch_acqf_class, qLogProbabilityOfFeasibility): return None, None + if learned_objective_preference_model is not None: + # The model also predicts constraint-only outcomes. The preference model + # was trained on objective outcomes in model output order. + objective_mask = (objective_weights != 0).any(dim=0) + if not objective_mask.all(): + return ( + _SubsetLearnedObjective( + pref_model=learned_objective_preference_model, + outcome_indices=objective_mask.nonzero(as_tuple=True)[0], + ), + None, + ) + return LearnedObjective(pref_model=learned_objective_preference_model), None + if issubclass( botorch_acqf_class, ( diff --git a/ax/storage/json_store/tests/test_json_store.py b/ax/storage/json_store/tests/test_json_store.py index be4e9e2e9e9..75d4bc24966 100644 --- a/ax/storage/json_store/tests/test_json_store.py +++ b/ax/storage/json_store/tests/test_json_store.py @@ -1902,8 +1902,12 @@ def test_preference_optimization_config_with_pruning_target_json_roundtrip( # Setup: create PreferenceOptimizationConfig with # pruning_target_parameterization pruning_target_parameterization = get_arm() + outcome_constraint = get_outcome_constraint( + metric=Metric(name="constraint_metric"), relative=False + ) preference_config = PreferenceOptimizationConfig( objective=get_multi_objective(), + outcome_constraints=[outcome_constraint], pruning_target_parameterization=pruning_target_parameterization, preference_profile_name="default", ) diff --git a/ax/storage/sqa_store/tests/test_sqa_store.py b/ax/storage/sqa_store/tests/test_sqa_store.py index f24ff59f6a7..fd5362dc352 100644 --- a/ax/storage/sqa_store/tests/test_sqa_store.py +++ b/ax/storage/sqa_store/tests/test_sqa_store.py @@ -1612,11 +1612,15 @@ def test_preference_optimization_config_sqa_roundtrip(self) -> None: ) test_test_profile = "test_profile_name" + outcome_constraint = OutcomeConstraint( + expression="m3 <= 0.5", metric_name_to_signature={"m3": "m3"} + ) for expect_relativized_outcomes in (True, False): with self.subTest(f"{expect_relativized_outcomes=}"): pref_config = PreferenceOptimizationConfig( objective=multi_objective, preference_profile_name=test_test_profile, + outcome_constraints=[outcome_constraint], expect_relativized_outcomes=expect_relativized_outcomes, ) experiment = Experiment( @@ -1639,6 +1643,9 @@ def test_preference_optimization_config_sqa_roundtrip(self) -> None: loaded_config.expect_relativized_outcomes, expect_relativized_outcomes, ) + self.assertEqual( + loaded_config.outcome_constraints, [outcome_constraint] + ) loaded_objective = assert_is_instance( loaded_config.objective, MultiObjective )