forked from facebook/Ax
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadapter_utils.py
More file actions
1461 lines (1275 loc) · 54.6 KB
/
adapter_utils.py
File metadata and controls
1461 lines (1275 loc) · 54.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from __future__ import annotations
import warnings
from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence
from copy import deepcopy
from logging import Logger
from typing import Any, cast, SupportsFloat, TYPE_CHECKING
import numpy as np
import numpy.typing as npt
import torch
from ax.adapter.transforms.base import Transform
from ax.adapter.transforms.utils import (
derelativize_optimization_config_with_raw_status_quo,
)
from ax.core.arm import Arm
from ax.core.experiment import Experiment
from ax.core.objective import MultiObjective, Objective, ScalarizedObjective
from ax.core.observation import Observation, ObservationData, ObservationFeatures
from ax.core.optimization_config import (
MultiObjectiveOptimizationConfig,
OptimizationConfig,
TRefPoint,
)
from ax.core.outcome_constraint import (
ComparisonOp,
OutcomeConstraint,
ScalarizedOutcomeConstraint,
)
from ax.core.parameter import ChoiceParameter, Parameter, ParameterType, RangeParameter
from ax.core.parameter_constraint import ParameterConstraint
from ax.core.search_space import SearchSpace, SearchSpaceDigest
from ax.core.types import TBounds, TCandidateMetadata, TNumeric
from ax.exceptions.core import DataRequiredError, UserInputError
from ax.generators.torch.botorch_moo_utils import (
get_weighted_mc_objective_and_objective_thresholds,
pareto_frontier_evaluator,
)
from ax.utils.common.constants import Keys
from ax.utils.common.hash_utils import get_current_lilo_hash
from ax.utils.common.logger import get_logger
from ax.utils.common.typeutils import (
assert_is_instance_of_tuple,
assert_is_instance_optional,
)
from botorch.models.utils.assorted import consolidate_duplicates
from botorch.utils.containers import SliceContainer
from botorch.utils.datasets import ContextualDataset, RankingDataset, SupervisedDataset
from botorch.utils.multi_objective.box_decompositions.dominated import (
DominatedPartitioning,
)
from pyre_extensions import assert_is_instance, none_throws
from torch import LongTensor, Tensor
logger: Logger = get_logger(__name__)
if TYPE_CHECKING:
# import as module to make sphinx-autodoc-typehints happy
from ax import adapter as adapter_module # noqa F401
def extract_parameter_constraints(
parameter_constraints: list[ParameterConstraint], param_names: list[str]
) -> TBounds:
"""Convert Ax parameter constraints into a tuple of NumPy arrays representing the
system of linear inequality constraints.
Args:
parameter_constraints: A list of parameter constraint objects.
param_names: A list of parameter names.
Returns:
An optional tuple of NumPy arrays (A, b) representing the system of linear
inequality constraints A x < b.
"""
if len(parameter_constraints) == 0:
return None
A = np.zeros((len(parameter_constraints), len(param_names)))
b = np.zeros((len(parameter_constraints), 1))
for i, c in enumerate(parameter_constraints):
b[i, 0] = c.bound
for name, val in c.constraint_dict.items():
A[i, param_names.index(name)] = val
return (A, b)
def extract_search_space_digest(
search_space: SearchSpace, param_names: list[str]
) -> SearchSpaceDigest:
"""Extract basic parameter properties from a search space.
This is typically called with the transformed search space and makes certain
assumptions regarding the parameters being transformed.
For ChoiceParameters:
* The choices are assumed to be numerical. ChoiceToNumericChoice
and OrderedChoiceToIntegerRange
transforms handle this.
* If is_task, its index is added to task_features.
* If ordered, its index is added to ordinal_features.
* Otherwise, its index is added to categorical_features.
* In all cases, the choices are added to discrete_choices.
* The minimum and maximum value are added to the bounds.
* The target_value is added to target_values.
For RangeParameters:
* They're assumed not to be in the log_scale. The Log transform handles this.
* If integer, its index is added to ordinal_features and the choices are added
to discrete_choices.
* The minimum and maximum value are added to the bounds.
If a parameter is_fidelity:
* Its target_value is assumed to be numerical.
* The target_value is added to target_values.
* Its index is added to fidelity_features.
"""
bounds: list[tuple[int | float, int | float]] = []
ordinal_features: list[int] = []
categorical_features: list[int] = []
discrete_choices: dict[int, list[int | float]] = {}
task_features: list[int] = []
fidelity_features: list[int] = []
target_values: dict[int, int | float] = {}
hierarchical_dependencies: dict[int, dict[int | float, list[int]]] | None = None
for i, p_name in enumerate(param_names):
p = search_space.parameters[p_name]
if isinstance(p, ChoiceParameter):
if p.is_task:
task_features.append(i)
target_values[i] = cast(
TNumeric,
assert_is_instance_of_tuple(p.target_value, (int, float)),
)
elif p.is_ordered:
ordinal_features.append(i)
else:
categorical_features.append(i)
# at this point we can assume that values are numeric due to transforms
numeric_values: list[TNumeric] = [
cast(TNumeric, assert_is_instance_of_tuple(v, (int, float)))
for v in p.values
]
discrete_choices[i] = numeric_values
bounds.append((min(numeric_values), max(numeric_values)))
elif isinstance(p, RangeParameter):
if p.log_scale or p.logit_scale:
raise UserInputError(
"Log and Logit scale parameters must be transformed using the "
"corresponding transform within the `Adapter`. After applying "
f"the transforms, we have {p.log_scale=} and {p.logit_scale=}."
)
if p.parameter_type == ParameterType.INT:
ordinal_features.append(i)
d_choices: list[TNumeric] = list(range(int(p.lower), int(p.upper) + 1))
discrete_choices[i] = d_choices
bounds.append((p.lower, p.upper))
else:
raise ValueError(f"Unknown parameter type {type(p)}")
if p.is_fidelity:
fidelity_features.append(i)
target_values[i] = cast(
TNumeric,
assert_is_instance_of_tuple(p.target_value, (int, float)),
)
if search_space.is_hierarchical:
hierarchical_dependencies = {}
for p_name, p in search_space.parameters.items():
if p.is_hierarchical:
hierarchical_dependencies[param_names.index(p_name)] = {
cast(
TNumeric,
assert_is_instance_of_tuple(parent_value, (int, float)),
): [
param_names.index(activated_param)
for activated_param in activated_params
]
for parent_value, activated_params in p.dependents.items()
}
return SearchSpaceDigest(
feature_names=param_names,
bounds=bounds,
ordinal_features=ordinal_features,
categorical_features=categorical_features,
discrete_choices=discrete_choices,
task_features=task_features,
fidelity_features=fidelity_features,
target_values=target_values,
hierarchical_dependencies=hierarchical_dependencies,
)
def extract_objective_thresholds(
objective_thresholds: TRefPoint,
objective: Objective,
outcomes: list[str],
) -> npt.NDArray | None:
"""Extracts objective thresholds' values, in the order of `outcomes`.
Will return None if no objective thresholds, otherwise the extracted tensor
will be the same length as `outcomes`.
Outcomes that are not part of an objective and the objectives that do no have
a corresponding objective threshold will be given a threshold of NaN. We will
later infer appropriate threshold values for the objectives that are given a
threshold of NaN.
Args:
objective_thresholds: Objective thresholds to extract values from.
objective: The corresponding Objective, for validation purposes.
outcomes: n-length list of names of metrics.
Returns:
(n,) array of thresholds
"""
if len(objective_thresholds) == 0:
return None
objective_threshold_dict = {}
for ot in objective_thresholds:
if ot.relative:
raise ValueError(
f"Objective {ot.metric.signature} has a relative threshold that "
f"is not supported here."
)
objective_threshold_dict[ot.metric.signature] = ot.bound
# Check that all thresholds correspond to a metric.
if set(objective_threshold_dict.keys()).difference(set(objective.metric_names)):
raise ValueError(
"Some objective thresholds do not have corresponding metrics. "
f"Got {objective_thresholds=} and {objective=}."
)
# Initialize these to be NaN to make sure that objective thresholds for
# non-objective metrics are never used.
obj_t = np.full(len(outcomes), float("nan"))
for metric, threshold in objective_threshold_dict.items():
obj_t[outcomes.index(metric)] = threshold
return obj_t
def extract_objective_weights(objective: Objective, outcomes: list[str]) -> npt.NDArray:
"""Extract a weights for objectives.
Weights are for a maximization problem.
Give an objective weight to each modeled outcome. Outcomes that are modeled
but not part of the objective get weight 0.
In the single metric case, the objective is given either +/- 1, depending
on the minimize flag.
In the multiple metric case, each objective is given the input weight,
multiplied by the minimize flag.
Args:
objective: Objective to extract weights from.
outcomes: n-length list of names of metrics.
Returns:
n-length array of weights.
"""
objective_weights = np.zeros(len(outcomes))
if isinstance(objective, ScalarizedObjective):
s = -1.0 if objective.minimize else 1.0
for obj_metric, obj_weight in objective.metric_weights:
objective_weights[outcomes.index(obj_metric.signature)] = obj_weight * s
elif isinstance(objective, MultiObjective):
for obj in objective.objectives:
s = -1.0 if obj.minimize else 1.0
objective_weights[outcomes.index(obj.metric.signature)] = s
else:
s = -1.0 if objective.minimize else 1.0
objective_weights[outcomes.index(objective.metric.signature)] = s
return objective_weights
def extract_objective_weight_matrix(
objective: Objective, outcomes: list[str]
) -> npt.NDArray:
"""Extract a 2D weight matrix for objectives.
Each row corresponds to one objective and each column to one modeled
outcome. Outcomes that are not part of an objective get weight 0 in
every row.
For a single ``Objective`` (including ``ScalarizedObjective``), the
matrix has a single row. For a ``MultiObjective``, each sub-objective
gets its own row.
Args:
objective: Objective to extract weights from.
outcomes: n-length list of names of metrics.
Returns:
``(n_objectives, n)`` array of weights.
"""
if isinstance(objective, MultiObjective):
rows: list[npt.NDArray] = []
for obj in objective.objectives:
rows.append(extract_objective_weights(obj, outcomes))
return np.stack(rows, axis=0)
else:
# Single row – covers Objective and ScalarizedObjective
return extract_objective_weights(objective, outcomes).reshape(1, -1)
def extract_outcome_constraints(
outcome_constraints: list[OutcomeConstraint], outcomes: list[str]
) -> TBounds:
if len(outcome_constraints) == 0:
return None
# Extract outcome constraints
A = np.zeros((len(outcome_constraints), len(outcomes)))
b = np.zeros((len(outcome_constraints), 1))
for i, c in enumerate(outcome_constraints):
s = 1 if c.op == ComparisonOp.LEQ else -1
if isinstance(c, ScalarizedOutcomeConstraint):
for c_metric, c_weight in c.metric_weights:
j = outcomes.index(c_metric.signature)
A[i, j] = s * c_weight
else:
j = outcomes.index(c.metric.signature)
A[i, j] = s
b[i, 0] = s * c.bound
return (A, b)
def arm_to_np_array(arm: Arm | None, parameters: list[str]) -> npt.NDArray | None:
"""Converts an arm to a numpy array in the order of `parameters`.
Args:
arm: The Arm to extract values from.
parameters: n-length list of names of parameters.
Returns:
n-length array of target values.
"""
if arm is None:
return None
return np.array([arm.parameters[p_name] for p_name in parameters])
def validate_and_apply_final_transform(
objective_weights: npt.NDArray,
outcome_constraints: tuple[npt.NDArray, npt.NDArray] | None,
linear_constraints: tuple[npt.NDArray, npt.NDArray] | None,
pending_observations: list[npt.NDArray] | None,
objective_thresholds: npt.NDArray | None = None,
pruning_target_point: npt.NDArray | None = None,
final_transform: Callable[[npt.NDArray], Tensor] = torch.tensor,
) -> tuple[
Tensor,
tuple[Tensor, Tensor] | None,
tuple[Tensor, Tensor] | None,
list[Tensor] | None,
Tensor | None,
Tensor | None,
]:
# TODO: use some container down the road (similar to
# SearchSpaceDigest) to limit the return arguments
obj_weights_tensor = final_transform(objective_weights)
outcome_constraints_tensors: tuple[Tensor, Tensor] | None = None
if outcome_constraints is not None:
outcome_constraints_tensors = (
final_transform(outcome_constraints[0]),
final_transform(outcome_constraints[1]),
)
linear_constraints_tensors: tuple[Tensor, Tensor] | None = None
if linear_constraints is not None:
linear_constraints_tensors = (
final_transform(linear_constraints[0]),
final_transform(linear_constraints[1]),
)
pending_obs_tensors: list[Tensor] | None = None
if pending_observations is not None:
pending_obs_tensors = [
final_transform(pending_obs) for pending_obs in pending_observations
]
obj_thresholds_tensor: Tensor | None = None
if objective_thresholds is not None:
obj_thresholds_tensor = final_transform(objective_thresholds)
pruning_target_tensor: Tensor | None = None
if pruning_target_point is not None:
pruning_target_tensor = final_transform(pruning_target_point)
return (
obj_weights_tensor,
outcome_constraints_tensors,
linear_constraints_tensors,
pending_obs_tensors,
obj_thresholds_tensor,
pruning_target_tensor,
)
def get_fixed_features(
fixed_features: ObservationFeatures | None, param_names: list[str]
) -> dict[int, float] | None:
"""Reformat a set of fixed_features."""
if fixed_features is None or not fixed_features.parameters:
return None
params = fixed_features.parameters
params_set = set(params)
param_names_set = set(param_names)
if params_set > param_names_set:
raise ValueError(
"Fixed features contains parameters not in "
f"`param_names`: {params_set - param_names_set}."
)
fixed_features_dict = {
i: float(assert_is_instance(params[p_name], SupportsFloat))
for i, p_name in enumerate(param_names)
if p_name in params
}
return fixed_features_dict
def get_fixed_features_from_experiment(
experiment: Experiment,
) -> ObservationFeatures:
completed_indices = [t.index for t in experiment.completed_trials]
completed_indices.append(0) # handle case of no completed trials
return ObservationFeatures(
parameters={},
trial_index=max(completed_indices),
)
def pending_observations_as_array_list(
pending_observations: dict[str, list[ObservationFeatures]],
outcome_names: list[str],
param_names: list[str],
) -> list[npt.NDArray] | None:
"""Re-format pending observations.
Args:
pending_observations: List of raw numpy pending observations.
outcome_names: List of outcome names.
param_names: List fitted param names.
Returns:
Filtered pending observations data, by outcome and param names.
"""
if len(pending_observations) == 0:
return None
pending = [np.array([]) for _ in outcome_names]
for metric_signature, po_list in pending_observations.items():
# It is possible that some metrics attached to the experiment should
# not be included in pending features for a given model. For example,
# if a model is fit to the initial data that is missing some of the
# metrics on the experiment or if a model just should not be fit for
# some of the metrics attached to the experiment, so metrics that
# appear in pending_observations (drawn from an experiment) but not
# in outcome_names (metrics, expected for the model) are filtered out.
if metric_signature not in outcome_names:
continue
pending[outcome_names.index(metric_signature)] = np.array(
[[po.parameters[p] for p in param_names] for po in po_list]
)
return pending
def parse_observation_features(
X: npt.NDArray,
param_names: list[str],
candidate_metadata: Sequence[TCandidateMetadata] | None = None,
) -> list[ObservationFeatures]:
"""Re-format raw model-generated candidates into ObservationFeatures.
Args:
param_names: List of param names.
X: Raw np.ndarray of candidate values.
candidate_metadata: Model's metadata for candidates it produced.
Returns:
List of candidates, represented as ObservationFeatures.
"""
if candidate_metadata and len(candidate_metadata) != len(X):
raise ValueError(
"Observations metadata list provided is not of "
"the same size as the number of candidates."
)
observation_features = []
for i, x in enumerate(X):
observation_features.append(
ObservationFeatures(
parameters=dict(zip(param_names, x, strict=True)),
metadata=candidate_metadata[i] if candidate_metadata else None,
)
)
return observation_features
def transform_callback(
param_names: list[str],
transforms: MutableMapping[str, Transform],
) -> Callable[[npt.NDArray], npt.NDArray]:
"""A closure for performing the `round trip` transformations.
The function rounds points by de-transforming points back into
the original space (done by applying transforms in reverse), and then
re-transforming them.
This function is specifically for points which are formatted as numpy
arrays. This function is passed to _model_gen.
Args:
param_names: Names of parameters to transform.
transforms: Ordered set of transforms which were applied to the points.
Returns:
a function with for performing the roundtrip transform.
"""
def _roundtrip_transform(x: npt.NDArray) -> npt.NDArray:
"""Inner function for performing aforementioned functionality.
Args:
x: points in the transformed space (e.g. all transforms have been applied
to them)
Returns:
points in the transformed space, but rounded via the original space.
"""
# apply reverse terminal transform to turn array to ObservationFeatures
observation_features = [
ObservationFeatures(
parameters={p: float(x[i]) for i, p in enumerate(param_names)}
)
]
# reverse loop through the transforms and do untransform
for t in reversed(list(transforms.values())):
observation_features = t.untransform_observation_features(
observation_features
)
# forward loop through the transforms and do transform
for t in transforms.values():
observation_features = t.transform_observation_features(
observation_features
)
new_x: list[float] = [
float(observation_features[0].parameters[p]) for p in param_names
]
# turn it back into an array
return np.array(new_x)
return _roundtrip_transform
def get_pareto_frontier_and_configs(
adapter: adapter_module.torch.TorchAdapter,
observation_features: list[ObservationFeatures],
observation_data: list[ObservationData] | None = None,
objective_thresholds: TRefPoint | None = None,
optimization_config: MultiObjectiveOptimizationConfig | None = None,
arm_names: list[str | None] | None = None,
use_model_predictions: bool = True,
) -> tuple[list[Observation], Tensor, Tensor, Tensor | None]:
"""Helper that applies transforms and calls ``frontier_evaluator``.
Returns the ``frontier_evaluator`` configs in addition to the Pareto
observations.
Args:
adapter: ``Adapter`` used to predict metrics outcomes.
observation_features: Observation features to consider for the Pareto
frontier.
observation_data: Data for computing the Pareto front, unless
``observation_features`` are provided and ``model_predictions is True``.
objective_thresholds: Metric values bounding the region of interest in
the objective outcome space; used to override objective thresholds
specified in ``optimization_config``, if necessary.
optimization_config: Multi-objective optimization config.
arm_names: Arm names for each observation in ``observation_features``.
use_model_predictions: If ``True``, will use model predictions at
``observation_features`` to compute Pareto front. If ``False``,
will use ``observation_data`` directly to compute Pareto front, ignoring
``observation_features``.
Returns: Four-item tuple of:
- frontier_observations: Observations of points on the pareto frontier,
- f: n x m tensor representation of the Pareto frontier values where n is the
length of frontier_observations and m is the number of metrics,
- obj_w: m tensor of objective weights,
- obj_t: m tensor of objective thresholds corresponding to Y, or None if no
objective thresholds used.
"""
# Input validation
if use_model_predictions:
if observation_data is not None:
warnings.warn(
"You provided `observation_data` when `use_model_predictions` is True; "
"`observation_data` will not be used.",
stacklevel=2,
)
elif observation_data is None:
raise ValueError(
"`observation_data` must not be None when `use_model_predictions` is False."
)
array_to_tensor = adapter._array_to_tensor
if use_model_predictions:
observation_data = adapter._predict_observation_data(
observation_features=observation_features
)
Y, Yvar = observation_data_to_array(
outcomes=adapter.outcomes, observation_data=none_throws(observation_data)
)
Y, Yvar = (array_to_tensor(Y), array_to_tensor(Yvar))
if arm_names is None:
arm_names = [None] * len(observation_features)
# Extract optimization config: make sure that the problem is a MOO
# problem and clone the optimization config with specified
# `objective_thresholds` if those are provided. If `optimization_config`
# is not specified, uses the one stored on `adapter`.
optimization_config = _get_multiobjective_optimization_config(
adapter=adapter,
optimization_config=optimization_config,
objective_thresholds=objective_thresholds,
)
# Transform optimization config.
# de-relativize outcome constraints and objective thresholds
optimization_config = assert_is_instance(
derelativize_optimization_config_with_raw_status_quo(
optimization_config=optimization_config, adapter=adapter
),
MultiObjectiveOptimizationConfig,
)
# Extract weights, constraints, and objective_thresholds
objective_weights = extract_objective_weight_matrix(
objective=optimization_config.objective, outcomes=adapter.outcomes
)
outcome_constraints = extract_outcome_constraints(
outcome_constraints=optimization_config.outcome_constraints,
outcomes=adapter.outcomes,
)
obj_t = extract_objective_thresholds(
objective_thresholds=optimization_config.objective_thresholds,
objective=optimization_config.objective,
outcomes=adapter.outcomes,
)
if obj_t is not None:
obj_t = array_to_tensor(obj_t)
# Transform to tensors.
obj_w, oc_c, _, _, _, _ = validate_and_apply_final_transform(
objective_weights=objective_weights,
outcome_constraints=outcome_constraints,
linear_constraints=None,
pending_observations=None,
final_transform=array_to_tensor,
)
f, cov, indx = pareto_frontier_evaluator(
model=None,
X=None,
Y=Y,
Yvar=Yvar,
objective_thresholds=obj_t,
objective_weights=obj_w,
outcome_constraints=oc_c,
)
f, cov = f.detach().cpu().clone(), cov.detach().cpu().clone()
indx = indx.tolist()
frontier_observation_data = array_to_observation_data(
f=f.numpy(), cov=cov.numpy(), outcomes=none_throws(adapter.outcomes)
)
# Construct observations
frontier_observations = []
for i, obsd in enumerate(frontier_observation_data):
frontier_observations.append(
Observation(
features=deepcopy(observation_features[indx[i]]),
data=deepcopy(obsd),
arm_name=arm_names[indx[i]],
)
)
return (
frontier_observations,
f,
obj_w.cpu(),
obj_t.cpu() if obj_t is not None else None,
)
def pareto_frontier(
adapter: adapter_module.torch.TorchAdapter,
observation_features: list[ObservationFeatures],
observation_data: list[ObservationData] | None = None,
objective_thresholds: TRefPoint | None = None,
optimization_config: MultiObjectiveOptimizationConfig | None = None,
arm_names: list[str | None] | None = None,
use_model_predictions: bool = True,
) -> list[Observation]:
"""Compute the list of points on the Pareto frontier as `Observation`-s
in the untransformed search space.
Args:
adapter: ``Adapter`` used to predict metrics outcomes.
observation_features: Observation features to consider for the Pareto
frontier.
observation_data: Data for computing the Pareto front, unless
``observation_features`` are provided and ``model_predictions is True``.
objective_thresholds: Metric values bounding the region of interest in
the objective outcome space; used to override objective thresholds
specified in ``optimization_config``, if necessary.
optimization_config: Multi-objective optimization config.
arm_names: Arm names for each observation in ``observation_features``.
use_model_predictions: If ``True``, will use model predictions at
``observation_features`` to compute Pareto front. If ``False``,
will use ``observation_data`` directly to compute Pareto front, ignoring
``observation_features``.
Returns: Points on the Pareto frontier as `Observation`-s in order of descending
individual hypervolume if possible.
"""
frontier_observations, f, obj_w, obj_t = get_pareto_frontier_and_configs(
adapter=adapter,
observation_features=observation_features,
observation_data=observation_data,
objective_thresholds=objective_thresholds,
optimization_config=optimization_config,
arm_names=arm_names,
use_model_predictions=use_model_predictions,
)
# If no objective thresholds are present we cannot compute hypervolume -- return
# frontier observations in arbitrary order
if obj_t is None:
return frontier_observations
# Apply appropriate weights and thresholds
obj, obj_t = get_weighted_mc_objective_and_objective_thresholds(
objective_weights=obj_w, objective_thresholds=obj_t
)
f_t = obj(f)
# Compute individual hypervolumes by taking the difference between the observation
# and the reference point and multiplying
individual_hypervolumes = (
(f_t.unsqueeze(dim=0) - obj_t).clamp_min(0).prod(dim=-1).squeeze().tolist()
)
if not isinstance(individual_hypervolumes, list):
individual_hypervolumes = [individual_hypervolumes]
return [
obs
for obs, _ in sorted(
zip(frontier_observations, individual_hypervolumes),
key=lambda tup: tup[1],
reverse=True,
)
]
def predicted_pareto_frontier(
adapter: adapter_module.torch.TorchAdapter,
objective_thresholds: TRefPoint | None = None,
observation_features: list[ObservationFeatures] | None = None,
optimization_config: MultiObjectiveOptimizationConfig | None = None,
) -> list[Observation]:
"""Generate a Pareto frontier based on the posterior means of given
observation features. Given a model and optionally features to evaluate
(will use model training data if not specified), use the model to predict
which points lie on the Pareto frontier.
Args:
adapter: ``Adapter`` used to predict metrics outcomes.
observation_features: Observation features to predict, if provided and
``use_model_predictions is True``.
objective_thresholds: Metric values bounding the region of interest in
the objective outcome space; used to override objective thresholds
specified in ``optimization_config``, if necessary.
optimization_config: Multi-objective optimization config.
Returns:
Observations representing points on the Pareto frontier.
"""
if observation_features is None:
observation_features, _, arm_names = _get_adapter_training_data(
adapter=adapter, in_design_only=True
)
else:
arm_names = None
if not observation_features:
raise ValueError(
"Must receive observation_features as input or the model must "
"have training data."
)
pareto_observations = pareto_frontier(
adapter=adapter,
objective_thresholds=objective_thresholds,
observation_features=observation_features,
optimization_config=optimization_config,
arm_names=arm_names,
)
return pareto_observations
def observed_pareto_frontier(
adapter: adapter_module.torch.TorchAdapter,
objective_thresholds: TRefPoint | None = None,
optimization_config: MultiObjectiveOptimizationConfig | None = None,
) -> list[Observation]:
"""Generate a pareto frontier based on observed data. Given observed data
(sourced from model training data), return points on the Pareto frontier
as `Observation`-s.
Args:
adapter: ``Adapter`` that holds previous training data.
objective_thresholds: Metric values bounding the region of interest in
the objective outcome space; used to override objective thresholds
in the optimization config, if needed.
optimization_config: Multi-objective optimization config.
Returns:
Data representing points on the pareto frontier.
"""
# Get observation_data from current training data
obs_feats, obs_data, arm_names = _get_adapter_training_data(
adapter=adapter, in_design_only=True
)
pareto_observations = pareto_frontier(
adapter=adapter,
objective_thresholds=objective_thresholds,
observation_data=obs_data,
observation_features=obs_feats,
optimization_config=optimization_config,
arm_names=arm_names,
use_model_predictions=False,
)
return pareto_observations
def hypervolume(
adapter: adapter_module.torch.TorchAdapter,
observation_features: list[ObservationFeatures],
objective_thresholds: TRefPoint | None = None,
observation_data: list[ObservationData] | None = None,
optimization_config: MultiObjectiveOptimizationConfig | None = None,
selected_metrics: list[str] | None = None,
use_model_predictions: bool = True,
) -> float:
"""Helper function that computes (feasible) hypervolume.
Args:
adapter: The adapter.
observation_features: The observation features for the in-sample arms.
objective_thresholds: The objective thresholds to be used for computing
the hypervolume. If None, these are extracted from the optimization
config.
observation_data: The observed outcomes for the in-sample arms.
optimization_config: The optimization config specifying the objectives,
objectives thresholds, and outcome constraints.
selected_metrics: A list of objective metric names specifying which
objectives to use in hypervolume computation. By default, all
objectives are used.
use_model_predictions: A boolean indicating whether to use model predictions
for determining the in-sample Pareto frontier instead of the raw observed
values.
Returns:
The (feasible) hypervolume.
"""
frontier_observations, f, obj_w, obj_t = get_pareto_frontier_and_configs(
adapter=adapter,
observation_features=observation_features,
observation_data=observation_data,
objective_thresholds=objective_thresholds,
optimization_config=optimization_config,
use_model_predictions=use_model_predictions,
)
if obj_t is None:
raise ValueError(
"Cannot compute hypervolume without having objective thresholds specified."
)
oc = _get_multiobjective_optimization_config(
adapter=adapter,
optimization_config=optimization_config,
objective_thresholds=objective_thresholds,
)
# Set to all metrics if unspecified
if selected_metrics is None:
selected_metrics = oc.objective.metric_names
# filter to only include objectives
else:
if any(m not in oc.objective.metric_names for m in selected_metrics):
raise ValueError("All selected metrics must be objectives.")
# Create a mask indicating selected metrics
selected_metrics_mask = torch.tensor(
[metric in selected_metrics for metric in adapter.outcomes],
dtype=torch.bool,
device=f.device,
)
# Apply appropriate weights and thresholds
obj, obj_t = get_weighted_mc_objective_and_objective_thresholds(
objective_weights=obj_w, objective_thresholds=none_throws(obj_t)
)
f_t = obj(f)
obj_mask = (obj_w != 0).any(dim=0).nonzero().view(-1)
selected_metrics_mask = selected_metrics_mask[obj_mask]
f_t = f_t[:, selected_metrics_mask]
obj_t = obj_t[selected_metrics_mask]
bd = DominatedPartitioning(ref_point=obj_t, Y=f_t)
return bd.compute_hypervolume().item()
def _get_multiobjective_optimization_config(
adapter: adapter_module.torch.TorchAdapter,
optimization_config: OptimizationConfig | None = None,
objective_thresholds: TRefPoint | None = None,
) -> MultiObjectiveOptimizationConfig:
# Optimization_config
mooc = optimization_config or assert_is_instance_optional(
adapter._optimization_config, MultiObjectiveOptimizationConfig
)
if not mooc:
raise ValueError(
"Experiment must have an existing optimization_config "
"of type `MultiObjectiveOptimizationConfig` "
"or `optimization_config` must be passed as an argument."
)
if not isinstance(mooc, MultiObjectiveOptimizationConfig):
raise ValueError(
"optimization_config must be a MultiObjectiveOptimizationConfig."
)
if objective_thresholds:
mooc = mooc.clone_with_args(objective_thresholds=objective_thresholds)
return mooc
def predicted_hypervolume(
adapter: adapter_module.torch.TorchAdapter,
objective_thresholds: TRefPoint | None = None,
observation_features: list[ObservationFeatures] | None = None,
optimization_config: MultiObjectiveOptimizationConfig | None = None,
selected_metrics: list[str] | None = None,
) -> float:
"""Calculate hypervolume of a pareto frontier based on the posterior means of
given observation features.
Given a model and features to evaluate calculate the hypervolume of the pareto
frontier formed from their predicted outcomes.
Args:
adapter: Adapter used to predict metrics outcomes.
objective_thresholds: point defining the origin of hyperrectangles that
can contribute to hypervolume.
observation_features: observation features to predict. Model's training
data used by default if unspecified.
optimization_config: Optimization config
selected_metrics: If specified, hypervolume will only be evaluated on
the specified subset of metrics. Otherwise, all metrics will be used.
Returns:
calculated hypervolume.
"""
if observation_features is None:
(
observation_features,
_,
__,
) = _get_adapter_training_data(adapter=adapter)
if not observation_features:
raise ValueError(
"Must receive observation_features as input or the model must "
"have training data."
)
return hypervolume(
adapter=adapter,
objective_thresholds=objective_thresholds,
observation_features=observation_features,
optimization_config=optimization_config,
selected_metrics=selected_metrics,
)