forked from facebook/Ax
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencoder.py
More file actions
1299 lines (1195 loc) · 52.9 KB
/
encoder.py
File metadata and controls
1299 lines (1195 loc) · 52.9 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
import dataclasses
from enum import Enum
from logging import Logger
from typing import Any, cast
from ax.analysis.graphviz.graphviz_analysis import GraphvizAnalysisCard
from ax.analysis.healthcheck.healthcheck_analysis import HealthcheckAnalysisCard
from ax.analysis.markdown.markdown_analysis import MarkdownAnalysisCard
from ax.analysis.plotly.plotly_analysis import PlotlyAnalysisCard
from ax.core.analysis_card import (
AnalysisCard,
AnalysisCardBase,
AnalysisCardGroup,
ErrorAnalysisCard,
NotApplicableStateAnalysisCard,
)
from ax.core.arm import Arm
from ax.core.auxiliary import AuxiliaryExperiment, AuxiliaryExperimentPurpose
from ax.core.base_trial import BaseTrial
from ax.core.batch_trial import AbandonedArm, BatchTrial
from ax.core.data import Data
from ax.core.evaluations_to_data import DataType
from ax.core.experiment import Experiment
from ax.core.generator_run import GeneratorRun
from ax.core.llm_provider import LLMMessage
from ax.core.metric import Metric
from ax.core.multi_type_experiment import MultiTypeExperiment
from ax.core.objective import MultiObjective, Objective, ScalarizedObjective
from ax.core.optimization_config import (
MultiObjectiveOptimizationConfig,
OptimizationConfig,
PreferenceOptimizationConfig,
)
from ax.core.outcome_constraint import (
ObjectiveThreshold,
OutcomeConstraint,
ScalarizedOutcomeConstraint,
)
from ax.core.parameter import (
ChoiceParameter,
DerivedParameter,
FixedParameter,
Parameter,
RangeParameter,
)
from ax.core.parameter_constraint import ParameterConstraint
from ax.core.runner import Runner
from ax.core.search_space import SearchSpace
from ax.core.trial import Trial
from ax.exceptions.core import UnsupportedError
from ax.exceptions.storage import SQAEncodeError
from ax.generation_strategy.generation_strategy import GenerationStrategy
from ax.storage.json_store.encoder import object_to_json
from ax.storage.json_store.encoders import arm_to_dict
from ax.storage.sqa_store.load import _get_experiment_id
from ax.storage.sqa_store.sqa_classes import (
SQAAbandonedArm,
SQAAnalysisCard,
SQAArm,
SQAAuxiliaryExperiment,
SQAData,
SQAExperiment,
SQAGenerationStrategy,
SQAGeneratorRun,
SQAMetric,
SQAParameter,
SQAParameterConstraint,
SQARunner,
SQATrial,
)
from ax.storage.sqa_store.sqa_config import SQAConfig
from ax.storage.utils import (
DomainType,
EXPECT_RELATIVIZED_OUTCOMES,
MetricIntent,
ParameterConstraintType,
PREFERENCE_PROFILE_NAME,
)
from ax.utils.common.base import Base
from ax.utils.common.constants import Keys
from ax.utils.common.logger import get_logger
from pyre_extensions import assert_is_instance, none_throws
logger: Logger = get_logger(__name__)
class Encoder:
"""Class that contains methods for storing an Ax experiment to SQLAlchemy.
Instantiate with an instance of Config to customize the functionality.
For even more flexibility, create a subclass.
Attributes:
config: Metadata needed to save and load an experiment to SQLAlchemy.
"""
def __init__(self, config: SQAConfig) -> None:
self.config = config
@classmethod
def validate_experiment_metadata(
cls,
experiment: Experiment,
existing_sqa_experiment_id: int | None,
) -> None:
"""Validates required experiment metadata."""
if experiment.db_id is not None:
if existing_sqa_experiment_id is None:
raise ValueError(
f"Experiment with ID {experiment.db_id} was already saved to the "
"database with a different name. Changing the name of an "
"experiment is not allowed."
)
elif experiment.db_id != existing_sqa_experiment_id:
raise ValueError(
f"experiment.db_id = {experiment.db_id} but the experiment in the "
f"database with the name {experiment.name} has the id "
f"{existing_sqa_experiment_id}."
)
else:
# experiment.db_id is None
if existing_sqa_experiment_id is not None:
raise ValueError(
f"An experiment already exists with the name {experiment.name}. "
"If you need to override this existing experiment, first delete it "
"via `delete_experiment` in ax/storage/sqa_store/delete.py, "
"and then resave."
)
def get_enum_value(
self, value: str | None, enum: Enum | type[Enum] | None
) -> int | None:
"""Given an enum name (string) and an enum (of ints), return the
corresponding enum value. If the name is not present in the enum,
throw an error.
"""
if value is None:
return None
error = SQAEncodeError(
f"Value {value} is invalid for enum {enum}. You may be "
"using a registry or config that doesn't support the value "
"you are trying to save."
)
if enum is None:
raise error
try:
# pyre-ignore[16]: `Enum` has no attribute `__getitem__`. T29651755
return enum[value].value
except KeyError:
raise error
def experiment_to_sqa(self, experiment: Experiment) -> SQAExperiment:
"""Convert Ax Experiment to SQLAlchemy.
In addition to creating and storing a new Experiment object, we need to
create and store copies of the Trials, Metrics, Parameters,
ParameterConstraints, and Runner owned by this Experiment.
"""
optimization_metrics = self.optimization_config_to_sqa(
experiment.optimization_config,
experiment_metrics=experiment._metrics,
)
tracking_metrics = []
for metric in experiment.tracking_metrics:
tracking_metrics.append(self.metric_to_sqa(metric))
parameters, parameter_constraints = self.search_space_to_sqa(
experiment.search_space
)
status_quo_name = None
status_quo_parameters = None
if experiment.status_quo is not None:
status_quo_name = none_throws(experiment.status_quo).name
status_quo_parameters = none_throws(experiment.status_quo).parameters
trials = []
for trial in experiment.trials.values():
trial_sqa = self.trial_to_sqa(
trial=trial,
experiment_metrics=experiment._metrics,
)
trials.append(trial_sqa)
experiment_data = self.experiment_data_to_sqa(experiment=experiment)
experiment_type = self.get_enum_value(
value=experiment.experiment_type, enum=self.config.experiment_type_enum
)
# New auxiliary experiments logic
auxiliary_experiments = self.auxiliary_experiments_by_purpose_to_sqa(
target_experiment=experiment,
auxiliary_experiments_by_purpose=(
experiment.auxiliary_experiments_by_purpose_for_storage
),
)
# Legacy auxiliary experiments logic
auxiliary_experiments_by_purpose = {}
for (
aux_exp_type_enum,
aux_exps,
) in experiment.auxiliary_experiments_by_purpose.items():
aux_exp_type = aux_exp_type_enum.value
aux_exp_jsons = [
self.encode_auxiliary_experiment(aux_exp) for aux_exp in aux_exps
]
auxiliary_experiments_by_purpose[aux_exp_type] = aux_exp_jsons
runners = []
if isinstance(experiment, MultiTypeExperiment):
experiment._properties[Keys.SUBCLASS] = "MultiTypeExperiment"
for trial_type, runner in experiment._trial_type_to_runner.items():
runner_sqa = self.runner_to_sqa(none_throws(runner), trial_type)
runners.append(runner_sqa)
for metric in tracking_metrics:
metric.trial_type = experiment._metric_to_trial_type[metric.name]
if metric.name in experiment._metric_to_canonical_name:
metric.canonical_name = experiment._metric_to_canonical_name[
metric.name
]
elif experiment.runner:
runners.append(self.runner_to_sqa(none_throws(experiment.runner)))
properties = experiment._properties.copy()
if (
oc := experiment.optimization_config
) is not None and oc.pruning_target_parameterization is not None:
properties["pruning_target_parameterization"] = arm_to_dict(
oc.pruning_target_parameterization
)
if Keys.LLM_MESSAGES in properties:
properties[Keys.LLM_MESSAGES] = [
dataclasses.asdict(m) if isinstance(m, LLMMessage) else m
for m in properties[Keys.LLM_MESSAGES]
]
# pyre-ignore[9]: Expected `Base` for 1st...yping.Type[Experiment]`.
experiment_class: type[SQAExperiment] = self.config.class_to_sqa_class[
Experiment
]
exp_sqa = experiment_class(
id=experiment.db_id, # pyre-ignore
description=experiment.description,
is_test=experiment.is_test,
name=experiment.name,
status_quo_name=status_quo_name,
status_quo_parameters=status_quo_parameters,
time_created=experiment.time_created,
status=experiment.status,
experiment_type=experiment_type,
metrics=optimization_metrics + tracking_metrics,
parameters=parameters,
parameter_constraints=parameter_constraints,
trials=trials,
runners=runners,
data=experiment_data,
properties=properties,
default_trial_type=experiment.default_trial_type,
# In for backward compatibility. Experiment._default_data_type no
# longer exists.
default_data_type=DataType.DATA,
auxiliary_experiments_by_purpose=auxiliary_experiments_by_purpose,
auxiliary_experiments=auxiliary_experiments,
)
return exp_sqa
def parameter_to_sqa(self, parameter: Parameter) -> SQAParameter:
"""Convert Ax Parameter to SQLAlchemy."""
# pyre-fixme[9]: Expected `Base` for 1st...typing.Type[Parameter]`.
parameter_class: SQAParameter = self.config.class_to_sqa_class[Parameter]
if isinstance(parameter, RangeParameter):
if parameter.logit_scale:
raise NotImplementedError(
"Cannot encode logit-scale parameter to SQLAlchemy because "
"the DB schema does not have a corresponding column. "
"Please reach out to the AE team if you need this feature. "
)
# pyre-fixme[29]: `SQAParameter` is not a function.
return parameter_class(
id=parameter.db_id,
name=parameter.name,
domain_type=DomainType.RANGE,
parameter_type=parameter.parameter_type,
lower=float(parameter.lower),
upper=float(parameter.upper),
log_scale=parameter.log_scale,
digits=parameter.digits,
is_fidelity=parameter.is_fidelity,
target_value=parameter.target_value,
dependents=parameter.dependents if parameter.is_hierarchical else None,
backfill_value=parameter.backfill_value,
default_value=parameter.default_value,
)
elif isinstance(parameter, ChoiceParameter):
if parameter._bypass_cardinality_check:
raise UnsupportedError(
"`bypass_cardinality_check` should only be set to `True` "
"when constructing parameters within the modeling layer. "
"It is not supported for storage."
)
# pyre-fixme[29]: `SQAParameter` is not a function.
return parameter_class(
id=parameter.db_id,
name=parameter.name,
domain_type=DomainType.CHOICE,
parameter_type=parameter.parameter_type,
choice_values=parameter.values,
is_ordered=parameter.is_ordered,
is_task=parameter.is_task,
log_scale=parameter.log_scale,
is_fidelity=parameter.is_fidelity,
target_value=parameter.target_value,
dependents=parameter.dependents if parameter.is_hierarchical else None,
backfill_value=parameter.backfill_value,
default_value=parameter.default_value,
)
elif isinstance(parameter, FixedParameter):
# pyre-fixme[29]: `SQAParameter` is not a function.
return parameter_class(
id=parameter.db_id,
name=parameter.name,
domain_type=DomainType.FIXED,
parameter_type=parameter.parameter_type,
fixed_value=parameter.value,
is_fidelity=parameter.is_fidelity,
target_value=parameter.target_value,
dependents=parameter.dependents if parameter.is_hierarchical else None,
backfill_value=parameter.backfill_value,
default_value=parameter.default_value,
)
elif isinstance(parameter, DerivedParameter):
# pyre-fixme[29]: `SQAParameter` is not a function.
return parameter_class(
id=parameter.db_id,
name=parameter.name,
domain_type=DomainType.DERIVED,
parameter_type=parameter.parameter_type,
expression_str=parameter.expression_str,
is_fidelity=parameter.is_fidelity,
target_value=parameter.target_value,
)
else:
raise SQAEncodeError(
"Cannot encode parameter to SQLAlchemy because parameter's "
f"subclass ({type(parameter)}) is invalid."
)
def parameter_constraint_to_sqa(
self, parameter_constraint: ParameterConstraint
) -> SQAParameterConstraint:
"""Convert Ax ParameterConstraint to SQLAlchemy."""
# pyre-fixme[9]: parameter_constraint_cl... used as type `SQABase`.
param_constraint_cls: SQAParameterConstraint = self.config.class_to_sqa_class[
ParameterConstraint
]
# pyre-fixme[29]: `SQAParameterConstraint` is not a function.
return param_constraint_cls(
id=parameter_constraint.db_id,
type=ParameterConstraintType.LINEAR,
constraint_dict=parameter_constraint.constraint_dict,
bound=parameter_constraint.bound,
)
def search_space_to_sqa(
self, search_space: SearchSpace | None
) -> tuple[list[SQAParameter], list[SQAParameterConstraint]]:
"""Convert Ax SearchSpace to a list of SQLAlchemy Parameters and
ParameterConstraints.
"""
parameters, parameter_constraints = [], []
if search_space is not None:
for parameter in search_space.parameters.values():
parameters.append(self.parameter_to_sqa(parameter=parameter))
for parameter_constraint in search_space.parameter_constraints:
parameter_constraints.append(
self.parameter_constraint_to_sqa(
parameter_constraint=parameter_constraint
)
)
return parameters, parameter_constraints
def get_metric_type_and_properties(
self, metric: Metric
) -> tuple[int, dict[str, Any]]:
"""Given an Ax Metric, convert its type into a member of MetricType enum,
and construct a dictionary to be stored in the database `properties`
json blob.
"""
metric_class = type(metric)
metric_type_or_none = self.config.metric_registry.get(metric_class)
if metric_type_or_none is None:
raise SQAEncodeError(
"Cannot encode metric to SQLAlchemy because metric's "
f"subclass ({metric_class}) is missing from the registry. "
"The metric registry currently contains the following: "
f"{','.join(map(str, self.config.metric_registry.keys()))} "
)
metric_type = int(metric_type_or_none)
properties = metric_class.serialize_init_args(obj=metric)
return metric_type, object_to_json(
properties,
encoder_registry=self.config.json_encoder_registry,
class_encoder_registry=self.config.json_class_encoder_registry,
)
def metric_to_sqa(self, metric: Metric) -> SQAMetric:
"""Convert Ax Metric to SQLAlchemy."""
metric_type, properties = self.get_metric_type_and_properties(metric=metric)
# pyre-fixme: Expected `Base` for 1st...t `typing.Type[Metric]`.
metric_class: SQAMetric = self.config.class_to_sqa_class[Metric]
# pyre-fixme[29]: `SQAMetric` is not a function.
return metric_class(
id=metric.db_id,
name=metric.name,
signature=metric.signature,
metric_type=metric_type,
intent=MetricIntent.TRACKING,
properties=properties,
lower_is_better=metric.lower_is_better,
)
def get_children_metrics_by_name(
self, metrics: list[Metric], weights: list[float]
) -> dict[str, tuple[Metric, float, SQAMetric, tuple[int, dict[str, Any]]]]:
return {
metric.name: (
metric,
weight,
cast(SQAMetric, self.config.class_to_sqa_class[Metric]),
self.get_metric_type_and_properties(metric=metric),
)
for (metric, weight) in zip(metrics, weights)
}
def objective_to_sqa(
self,
objective: Objective,
experiment_metrics: dict[str, Metric] | None = None,
) -> SQAMetric:
"""Convert Ax Objective to SQLAlchemy."""
if objective.is_scalarized_objective or isinstance(
objective, ScalarizedObjective
):
objective_sqa = self.scalarized_objective_to_sqa(
objective, experiment_metrics=experiment_metrics
)
elif objective.is_multi_objective or isinstance(objective, MultiObjective):
objective_sqa = self.multi_objective_to_sqa(
objective, experiment_metrics=experiment_metrics
)
else:
metric_name = objective.metric_names[0]
metric = (
experiment_metrics.get(metric_name, Metric(name=metric_name))
if experiment_metrics
else Metric(name=metric_name)
)
metric_type, properties = self.get_metric_type_and_properties(metric=metric)
metric_class = cast(SQAMetric, self.config.class_to_sqa_class[Metric])
objective_sqa = (
metric_class( # pyre-ignore[29]: `SQAMetric` is not a function.
id=objective.db_id,
name=metric.name,
signature=metric.signature,
metric_type=metric_type,
intent=MetricIntent.OBJECTIVE,
minimize=objective.minimize,
properties=properties,
lower_is_better=metric.lower_is_better,
)
)
return assert_is_instance(objective_sqa, SQAMetric)
def multi_objective_to_sqa(
self,
multi_objective: Objective,
experiment_metrics: dict[str, Metric] | None = None,
) -> SQAMetric:
"""Convert Ax Multi Objective to SQLAlchemy.
Returns: A parent `SQAMetric`, whose children are the `SQAMetric`-s
corresponding to `metrics` attribute of `MultiObjective`.
NOTE: The parent is used as a placeholder for storage purposes.
"""
# Constructing children SQAMetric classes (these are the real metrics in
# the `MultiObjective`).
children_objectives = []
metric_weights_dict = dict(multi_objective.metric_weights)
for metric_name in multi_objective.metric_names:
metric = (
experiment_metrics.get(metric_name, Metric(name=metric_name))
if experiment_metrics
else Metric(name=metric_name)
)
objective_cls = cast(SQAMetric, self.config.class_to_sqa_class[Metric])
type_and_properties = self.get_metric_type_and_properties(metric=metric)
weight = metric_weights_dict.get(metric_name, 1.0)
children_objectives.append(
objective_cls( # pyre-ignore[29]: `SQAMetric` is not a func.
id=None,
name=metric.name,
signature=metric.signature,
metric_type=type_and_properties[0],
intent=MetricIntent.OBJECTIVE,
minimize=weight < 0,
properties=type_and_properties[1],
lower_is_better=metric.lower_is_better,
)
)
# Constructing a parent SQAMetric class (not a real metric, only a placeholder
# to group the metrics together).
parent_metric_cls = cast(SQAMetric, self.config.class_to_sqa_class[Metric])
parent_metric = (
parent_metric_cls( # pyre-ignore[29]: `SQAMetric` is not a func.
id=multi_objective.db_id,
name="multi_objective",
metric_type=self.config.metric_registry[Metric],
intent=MetricIntent.MULTI_OBJECTIVE,
scalarized_objective_children_metrics=children_objectives,
signature="multi_objective",
)
)
return parent_metric
def preference_objective_to_sqa(
self,
multi_objective: Objective,
preference_profile_name: str,
expect_relativized_outcomes: bool,
experiment_metrics: dict[str, Metric] | None = None,
) -> SQAMetric:
"""Convert Ax PreferenceOptimizationConfig objective to SQLAlchemy.
Returns: A parent `SQAMetric`, whose children are the `SQAMetric`-s
corresponding to `metrics` attribute of the `MultiObjective` from
`PreferenceOptimizationConfig`. The parent stores the config-level
properties (preference_profile_name, expect_relativized_outcomes)
in its properties field.
NOTE: The parent is used as a placeholder for storage purposes.
"""
# Constructing children SQAMetric classes (these are the real metrics in
# the `MultiObjective`).
children_objectives = []
metric_weights_dict = dict(multi_objective.metric_weights)
for metric_name in multi_objective.metric_names:
metric = (
experiment_metrics.get(metric_name, Metric(name=metric_name))
if experiment_metrics
else Metric(name=metric_name)
)
objective_cls = cast(SQAMetric, self.config.class_to_sqa_class[Metric])
type_and_properties = self.get_metric_type_and_properties(metric=metric)
weight = metric_weights_dict.get(metric_name, 1.0)
children_objectives.append(
objective_cls( # pyre-ignore[29]: `SQAMetric` is not a func.
id=None,
name=metric.name,
signature=metric.signature,
metric_type=type_and_properties[0],
intent=MetricIntent.OBJECTIVE,
minimize=weight < 0,
properties=type_and_properties[1],
lower_is_better=metric.lower_is_better,
)
)
# Store config-level properties in parent metric's properties field
parent_properties = {
PREFERENCE_PROFILE_NAME: preference_profile_name,
EXPECT_RELATIVIZED_OUTCOMES: expect_relativized_outcomes,
}
# Constructing a parent SQAMetric class (not a real metric, only a placeholder
# to group the metrics together and store PreferenceOptimizationConfig fields).
parent_metric_cls = cast(SQAMetric, self.config.class_to_sqa_class[Metric])
parent_metric = (
parent_metric_cls( # pyre-ignore[29]: `SQAMetric` is not a func.
id=multi_objective.db_id,
name="preference_objective",
metric_type=self.config.metric_registry[Metric],
intent=MetricIntent.PREFERENCE_OBJECTIVE,
scalarized_objective_children_metrics=children_objectives,
signature="preference_objective",
properties=parent_properties,
)
)
return parent_metric
def scalarized_objective_to_sqa(
self,
objective: Objective,
experiment_metrics: dict[str, Metric] | None = None,
) -> SQAMetric:
"""Convert Ax Scalarized Objective to SQLAlchemy.
Returns: A parent `SQAMetric`, whose children are the `SQAMetric`-s
corresponding to `metrics` attribute of `ScalarizedObjective`.
NOTE: The parent is used as a placeholder for storage purposes.
"""
metric_weights = objective.metric_weights
if not metric_weights:
raise SQAEncodeError(
"Metrics and weights in scalarized objective "
"must be lists of equal length."
)
# Infer minimize from effective weights: if all weights are <= 0 (with
# at least one < 0), the objective was constructed with minimize=True.
minimize = all(w <= 0 for _, w in metric_weights) and any(
w < 0 for _, w in metric_weights
)
# Constructing children SQAMetric classes (these are the real metrics in
# the `ScalarizedObjective`).
children_metrics = []
for metric_name, w in metric_weights:
metric = (
experiment_metrics.get(metric_name, Metric(name=metric_name))
if experiment_metrics
else Metric(name=metric_name)
)
metric_cls = cast(SQAMetric, self.config.class_to_sqa_class[Metric])
type_and_properties = self.get_metric_type_and_properties(metric=metric)
children_metrics.append(
metric_cls( # pyre-ignore[29]: `SQAMetric` is not a function.
id=None,
name=metric_name,
signature=metric.signature,
metric_type=type_and_properties[0],
intent=MetricIntent.OBJECTIVE,
minimize=minimize,
properties=type_and_properties[1],
lower_is_better=metric.lower_is_better,
scalarized_objective_weight=w,
)
)
# For plain Objective instances (not deprecated ScalarizedObjective
# subclass), store the original expression so it can be restored
# losslessly during decoding.
parent_properties: dict[str, Any] = {}
if type(objective) is Objective:
parent_properties["expression"] = objective.expression
# Constructing a parent SQAMetric class
parent_metric_cls = cast(SQAMetric, self.config.class_to_sqa_class[Metric])
parent_metric = parent_metric_cls( # pyre-ignore[29]: `SQAMetric` not a func.
id=objective.db_id,
name="scalarized_objective",
metric_type=self.config.metric_registry[Metric],
intent=MetricIntent.SCALARIZED_OBJECTIVE,
minimize=minimize,
lower_is_better=minimize,
scalarized_objective_children_metrics=children_metrics,
signature="scalarized_objective",
properties=parent_properties,
)
return parent_metric
def outcome_constraint_to_sqa(
self,
outcome_constraint: OutcomeConstraint,
experiment_metrics: dict[str, Metric] | None = None,
) -> SQAMetric:
"""Convert Ax OutcomeConstraint to SQLAlchemy."""
if isinstance(outcome_constraint, ScalarizedOutcomeConstraint):
return self.scalarized_outcome_constraint_to_sqa(
outcome_constraint, experiment_metrics=experiment_metrics
)
metric_name = outcome_constraint.metric_names[0]
metric = (
experiment_metrics.get(metric_name, Metric(name=metric_name))
if experiment_metrics
else Metric(name=metric_name)
)
metric_type, properties = self.get_metric_type_and_properties(metric=metric)
# pyre-fixme: Expected `Base` for 1st...t `typing.Type[Metric]`.
metric_class: SQAMetric = self.config.class_to_sqa_class[Metric]
# pyre-fixme[29]: `SQAMetric` is not a function.
constraint_sqa = metric_class(
id=outcome_constraint.db_id,
name=metric.name,
signature=metric.signature,
metric_type=metric_type,
intent=MetricIntent.OUTCOME_CONSTRAINT,
bound=outcome_constraint.bound,
op=outcome_constraint.op,
relative=outcome_constraint.relative,
properties=properties,
lower_is_better=metric.lower_is_better,
)
return constraint_sqa
def scalarized_outcome_constraint_to_sqa(
self,
outcome_constraint: ScalarizedOutcomeConstraint,
experiment_metrics: dict[str, Metric] | None = None,
) -> SQAMetric:
"""Convert Ax Scalarized OutcomeConstraint to SQLAlchemy."""
metric_weights = outcome_constraint.metric_weights
if not metric_weights:
raise SQAEncodeError(
"Metrics and weights in scalarized OutcomeConstraint "
"must be lists of equal length."
)
# Constructing children SQAMetric classes (these are the real metrics in
# the `ScalarizedObjective`).
children_metrics = []
for metric_name, w in metric_weights:
metric = (
experiment_metrics.get(metric_name, Metric(name=metric_name))
if experiment_metrics
else Metric(name=metric_name)
)
metric_cls = cast(SQAMetric, self.config.class_to_sqa_class[Metric])
type_and_properties = self.get_metric_type_and_properties(metric=metric)
children_metrics.append(
metric_cls( # pyre-ignore[29]: `SQAMetric` is not a function.
id=None,
name=metric_name,
signature=metric.signature,
metric_type=type_and_properties[0],
intent=MetricIntent.OUTCOME_CONSTRAINT,
properties=type_and_properties[1],
lower_is_better=metric.lower_is_better,
scalarized_outcome_constraint_weight=w,
bound=outcome_constraint.bound,
op=outcome_constraint.op,
relative=outcome_constraint.relative,
)
)
# Constructing a parent SQAMetric class
parent_metric_cls = cast(SQAMetric, self.config.class_to_sqa_class[Metric])
parent_metric = parent_metric_cls( # pyre-ignore[29]: `SQAMetric` not a func.
id=outcome_constraint.db_id,
name="scalarized_outcome_constraint",
signature="scalarized_outcome_constraint",
metric_type=self.config.metric_registry[Metric],
intent=MetricIntent.SCALARIZED_OUTCOME_CONSTRAINT,
bound=outcome_constraint.bound,
op=outcome_constraint.op,
relative=outcome_constraint.relative,
scalarized_outcome_constraint_children_metrics=children_metrics,
)
return parent_metric
def objective_threshold_to_sqa(
self,
objective_threshold: ObjectiveThreshold,
experiment_metrics: dict[str, Metric] | None = None,
) -> SQAMetric:
"""Convert Ax OutcomeConstraint to SQLAlchemy."""
metric_name = objective_threshold.metric_names[0]
metric = (
experiment_metrics.get(metric_name, Metric(name=metric_name))
if experiment_metrics
else Metric(name=metric_name)
)
metric_type, properties = self.get_metric_type_and_properties(metric=metric)
# pyre-fixme: Expected `Base` for 1st...t `typing.Type[Metric]`.
metric_class: SQAMetric = self.config.class_to_sqa_class[Metric]
# pyre-fixme[29]: `SQAMetric` is not a function.
return metric_class(
id=objective_threshold.db_id,
name=metric.name,
signature=metric.signature,
metric_type=metric_type,
intent=MetricIntent.OBJECTIVE_THRESHOLD,
bound=objective_threshold.bound,
op=objective_threshold.op,
relative=objective_threshold.relative,
properties=properties,
lower_is_better=metric.lower_is_better,
)
def optimization_config_to_sqa(
self,
optimization_config: OptimizationConfig | None,
experiment_metrics: dict[str, Metric] | None = None,
) -> list[SQAMetric]:
"""Convert Ax OptimizationConfig to a list of SQLAlchemy Metrics."""
if optimization_config is None:
return []
metrics_sqa = []
# Handle PreferenceOptimizationConfig separately
if isinstance(optimization_config, PreferenceOptimizationConfig):
objective = optimization_config.objective
if not (
isinstance(objective, MultiObjective) or objective.is_multi_objective
):
raise SQAEncodeError(
f"PreferenceOptimizationConfig requires a MultiObjective, "
f"got {type(objective).__name__}"
)
obj_sqa = self.preference_objective_to_sqa(
multi_objective=objective,
preference_profile_name=optimization_config.preference_profile_name,
expect_relativized_outcomes=(
optimization_config.expect_relativized_outcomes
),
experiment_metrics=experiment_metrics,
)
else:
obj_sqa = self.objective_to_sqa(
objective=optimization_config.objective,
experiment_metrics=experiment_metrics,
)
metrics_sqa.append(obj_sqa)
for constraint in optimization_config.outcome_constraints:
constraint_sqa = self.outcome_constraint_to_sqa(
outcome_constraint=constraint,
experiment_metrics=experiment_metrics,
)
metrics_sqa.append(constraint_sqa)
if isinstance(optimization_config, MultiObjectiveOptimizationConfig) and not (
isinstance(optimization_config, PreferenceOptimizationConfig)
):
for threshold in optimization_config.objective_thresholds:
threshold_sqa = self.objective_threshold_to_sqa(
objective_threshold=assert_is_instance(
threshold, ObjectiveThreshold
),
experiment_metrics=experiment_metrics,
)
metrics_sqa.append(threshold_sqa)
return metrics_sqa
def arm_to_sqa(self, arm: Arm, weight: float | None = 1.0) -> SQAArm:
"""Convert Ax Arm to SQLAlchemy."""
# pyre-fixme: Expected `Base` for 1st... got `typing.Type[Arm]`.
arm_class: SQAArm = self.config.class_to_sqa_class[Arm]
# pyre-fixme[29]: `SQAArm` is not a function.
return arm_class(
id=arm.db_id, parameters=arm.parameters, name=arm._name, weight=weight
)
def abandoned_arm_to_sqa(self, abandoned_arm: AbandonedArm) -> SQAAbandonedArm:
"""Convert Ax AbandonedArm to SQLAlchemy."""
# pyre-fixme[9]: abandoned_arm_class is ....sqa_store.db.SQABase]`.
abandoned_arm_class: SQAAbandonedArm = self.config.class_to_sqa_class[
AbandonedArm
]
# pyre-fixme[29]: `SQAAbandonedArm` is not a function.
return abandoned_arm_class(
id=abandoned_arm.db_id,
name=abandoned_arm.name,
abandoned_reason=abandoned_arm.reason,
time_abandoned=abandoned_arm.time,
)
def generator_run_to_sqa(
self,
generator_run: GeneratorRun,
weight: float | None = None,
reduced_state: bool = False,
experiment_metrics: dict[str, Metric] | None = None,
) -> SQAGeneratorRun:
"""Convert Ax GeneratorRun to SQLAlchemy.
In addition to creating and storing a new GeneratorRun object, we need to
create and store copies of the Arms, Metrics, Parameters, and
ParameterConstraints owned by this GeneratorRun.
"""
arms = []
for arm, arm_weight in generator_run.arm_weights.items():
arms.append(self.arm_to_sqa(arm=arm, weight=arm_weight))
metrics = self.optimization_config_to_sqa(
generator_run.optimization_config,
experiment_metrics=experiment_metrics,
)
parameters, parameter_constraints = self.search_space_to_sqa(
generator_run.search_space
)
best_arm_name = None
best_arm_parameters = None
best_arm_predictions = None
if generator_run.best_arm_predictions is not None:
best_arm, model_predict_arm = generator_run.best_arm_predictions
if model_predict_arm is not None:
best_arm_predictions = list(model_predict_arm)
else:
logger.warning(
f"No model predictions found with best arm '{best_arm._name}'."
" Setting best_arm_predictions=None in storage"
)
best_arm_name = best_arm._name
best_arm_parameters = best_arm.parameters
model_predictions = (
list(generator_run.model_predictions)
if generator_run.model_predictions is not None
else None
)
generator_run_type = self.get_enum_value(
value=generator_run.generator_run_type,
enum=self.config.generator_run_type_enum,
)
# pyre-fixme: Expected `Base` for 1st...ing.Type[GeneratorRun]`.
generator_run_class: SQAGeneratorRun = self.config.class_to_sqa_class[
GeneratorRun
]
gr_sqa = generator_run_class( # pyre-ignore[29]: `SQAGeneratorRun` not a func.
id=generator_run.db_id,
arms=arms,
metrics=metrics,
parameters=parameters,
parameter_constraints=parameter_constraints,
time_created=generator_run.time_created,
generator_run_type=generator_run_type,
weight=weight,
fit_time=generator_run.fit_time,
gen_time=generator_run.gen_time,
best_arm_name=best_arm_name,
best_arm_parameters=best_arm_parameters,
best_arm_predictions=best_arm_predictions,
model_predictions=model_predictions,
# TODO: rename these in the db schema?
# We could just wait for the storage refactor instead.
model_key=generator_run._generator_key,
model_kwargs=(
object_to_json(
generator_run._generator_kwargs,
encoder_registry=self.config.json_encoder_registry,
class_encoder_registry=self.config.json_class_encoder_registry,
)
if not reduced_state
else None
),
bridge_kwargs=(
object_to_json(
generator_run._adapter_kwargs,
encoder_registry=self.config.json_encoder_registry,
class_encoder_registry=self.config.json_class_encoder_registry,
)
if not reduced_state
else None
),
gen_metadata=(
object_to_json(
generator_run._gen_metadata,
encoder_registry=self.config.json_encoder_registry,
class_encoder_registry=self.config.json_class_encoder_registry,
)
if not reduced_state
else None
),
model_state_after_gen=(
object_to_json(
generator_run._generator_state_after_gen,
encoder_registry=self.config.json_encoder_registry,
class_encoder_registry=self.config.json_class_encoder_registry,
)
if not reduced_state
else None
),
candidate_metadata_by_arm_signature=object_to_json(
generator_run._candidate_metadata_by_arm_signature,
encoder_registry=self.config.json_encoder_registry,
class_encoder_registry=self.config.json_class_encoder_registry,
),
generation_node_name=generator_run._generation_node_name,
suggested_experiment_status=generator_run.suggested_experiment_status,
)