-
Notifications
You must be signed in to change notification settings - Fork 312
/
ax_client.py
1896 lines (1701 loc) · 80.8 KB
/
ax_client.py
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 json
import logging
import warnings
from functools import partial
from logging import Logger
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Sequence,
Set,
Tuple,
Type,
TypeVar,
Union,
)
import ax.service.utils.early_stopping as early_stopping_utils
import numpy as np
import pandas as pd
import torch
from ax.core.arm import Arm
from ax.core.base_trial import BaseTrial, TrialStatus
from ax.core.experiment import DataType, Experiment
from ax.core.formatting_utils import data_and_evaluations_from_raw_data
from ax.core.generation_strategy_interface import GenerationStrategyInterface
from ax.core.generator_run import GeneratorRun
from ax.core.map_data import MapData
from ax.core.map_metric import MapMetric
from ax.core.objective import MultiObjective, Objective
from ax.core.observation import ObservationFeatures
from ax.core.optimization_config import (
MultiObjectiveOptimizationConfig,
OptimizationConfig,
)
from ax.core.trial import Trial
from ax.core.types import (
TEvaluationOutcome,
TModelPredictArm,
TParameterization,
TParamValue,
)
from ax.core.utils import get_pending_observation_features_based_on_trial_status
from ax.early_stopping.strategies import BaseEarlyStoppingStrategy
from ax.early_stopping.utils import estimate_early_stopping_savings
from ax.exceptions.constants import CHOLESKY_ERROR_ANNOTATION
from ax.exceptions.core import (
OptimizationComplete,
OptimizationShouldStop,
UnsupportedError,
UnsupportedPlotError,
)
from ax.exceptions.generation_strategy import MaxParallelismReachedException
from ax.global_stopping.strategies.base import BaseGlobalStoppingStrategy
from ax.global_stopping.strategies.improvement import constraint_satisfaction
from ax.modelbridge.dispatch_utils import choose_generation_strategy
from ax.modelbridge.generation_strategy import GenerationStrategy
from ax.modelbridge.prediction_utils import predict_by_features
from ax.plot.base import AxPlotConfig
from ax.plot.contour import plot_contour
from ax.plot.feature_importances import plot_feature_importance_by_feature
from ax.plot.helper import _format_dict
from ax.plot.trace import optimization_trace_single_method
from ax.service.utils.best_point_mixin import BestPointMixin
from ax.service.utils.instantiation import (
FixedFeatures,
InstantiationBase,
ObjectiveProperties,
)
from ax.service.utils.report_utils import exp_to_df
from ax.service.utils.with_db_settings_base import DBSettings, WithDBSettingsBase
from ax.storage.json_store.decoder import (
generation_strategy_from_json,
object_from_json,
)
from ax.storage.json_store.encoder import object_to_json
from ax.storage.json_store.registry import (
CORE_CLASS_DECODER_REGISTRY,
CORE_CLASS_ENCODER_REGISTRY,
CORE_DECODER_REGISTRY,
CORE_ENCODER_REGISTRY,
)
from ax.utils.common.docutils import copy_doc
from ax.utils.common.executils import retry_on_exception
from ax.utils.common.logger import _round_floats_for_logging, get_logger
from ax.utils.common.random import with_rng_seed
from ax.utils.common.typeutils import checked_cast, not_none
from pyre_extensions import assert_is_instance
logger: Logger = get_logger(__name__)
AxClientSubclass = TypeVar("AxClientSubclass", bound="AxClient")
ROUND_FLOATS_IN_LOGS_TO_DECIMAL_PLACES: int = 6
# pyre-fixme[5]: Global expression must be annotated.
round_floats_for_logging = partial(
_round_floats_for_logging,
decimal_places=ROUND_FLOATS_IN_LOGS_TO_DECIMAL_PLACES,
)
class AxClient(WithDBSettingsBase, BestPointMixin, InstantiationBase):
"""
Convenience handler for management of experimentation cycle through a
service-like API. External system manages scheduling of the cycle and makes
calls to this client to get next suggestion in the experiment and log back
data from the evaluation of that suggestion.
Note: `AxClient` expects to only propose 1 arm (suggestion) per trial; support
for use cases that require use of batches is coming soon.
Two custom types used in this class for convenience are `TParamValue` and
`TParameterization`. Those are shortcuts for `Union[str, bool, float, int]`
and `Dict[str, Union[str, bool, float, int]]`, respectively.
Args:
generation_strategy: Optional generation strategy. If not set, one is
intelligently chosen based on properties of search space.
db_settings: Settings for saving and reloading the underlying experiment
to a database. Expected to be of type
ax.storage.sqa_store.structs.DBSettings and require SQLAlchemy.
enforce_sequential_optimization: Whether to enforce that when it is
reasonable to switch models during the optimization (as prescribed
by `num_trials` in generation strategy), Ax will wait for enough trials
to be completed with data to proceed. Defaults to True. If set to
False, Ax will keep generating new trials from the previous model
until enough data is gathered. Use this only if necessary;
otherwise, it is more resource-efficient to
optimize sequentially, by waiting until enough data is available to
use the next model.
random_seed: Optional integer random seed, set to fix the optimization
random seed for reproducibility. Works only for Sobol quasi-random
generator and for BoTorch-powered models. For the latter models, the
trials generated from the same optimization setup with the same seed,
will be mostly similar, but the exact parameter values may still vary
and trials latter in the optimizations will diverge more and more.
This is because a degree of randomness is essential for high performance
of the Bayesian optimization models and is not controlled by the seed.
Note: In multi-threaded environments, the random seed is thread-safe,
but does not actually guarantee reproducibility. Whether the outcomes
will be exactly the same for two same operations that use the random
seed, depends on whether the threads modify the random state in the
same order across the two operations.
torch_device: An optional `torch.device` object, used to choose the device
used for generating new points for trials. Works only for torch-based
models, such as GPEI. Ignored if a `generation_strategy` is passed in
manually. To specify the device for a custom `generation_strategy`,
pass in `torch_device` as part of `model_kwargs`. See
https://ax.dev/tutorials/generation_strategy.html for a tutorial on
generation strategies.
verbose_logging: Whether Ax should log significant optimization events,
defaults to `True`.
suppress_storage_errors: Whether to suppress SQL storage-related errors if
encountered. Only use if SQL storage is not important for the given use
case, since this will only log, but not raise, an exception if its
encountered while saving to DB or loading from it.
early_stopping_strategy: A ``BaseEarlyStoppingStrategy`` that determines
whether a trial should be stopped given the current state of
the experiment. Used in ``should_stop_trials_early``.
global_stopping_strategy: A ``BaseGlobalStoppingStrategy`` that determines
whether the full optimization should be stopped or not.
"""
_experiment: Optional[Experiment] = None
def __init__(
self,
generation_strategy: Optional[GenerationStrategy] = None,
db_settings: Optional[DBSettings] = None,
enforce_sequential_optimization: bool = True,
random_seed: Optional[int] = None,
torch_device: Optional[torch.device] = None,
verbose_logging: bool = True,
suppress_storage_errors: bool = False,
early_stopping_strategy: Optional[BaseEarlyStoppingStrategy] = None,
global_stopping_strategy: Optional[BaseGlobalStoppingStrategy] = None,
) -> None:
super().__init__(
db_settings=db_settings,
suppress_all_errors=suppress_storage_errors,
)
if not verbose_logging:
logger.setLevel(logging.WARNING)
else:
logger.info(
"Starting optimization with verbose logging. To disable logging, "
"set the `verbose_logging` argument to `False`. Note that float "
"values in the logs are rounded to "
f"{ROUND_FLOATS_IN_LOGS_TO_DECIMAL_PLACES} decimal points."
)
if generation_strategy is not None and torch_device is not None:
warnings.warn(
"Both a `generation_strategy` and a `torch_device` were specified. "
"`torch_device` will be ignored. Instead, specify `torch_device` "
"by passing it in `model_kwargs` while creating the "
"`generation_strategy`.",
RuntimeWarning,
stacklevel=2,
)
self._generation_strategy = generation_strategy
self._enforce_sequential_optimization = enforce_sequential_optimization
self._random_seed = random_seed
self._torch_device = torch_device
self._suppress_storage_errors = suppress_storage_errors
self._early_stopping_strategy = early_stopping_strategy
self._global_stopping_strategy = global_stopping_strategy
if random_seed is not None:
logger.warning(
f"Random seed set to {random_seed}. Note that this setting "
"only affects the Sobol quasi-random generator "
"and BoTorch-powered Bayesian optimization models. For the latter "
"models, setting random seed to the same number for two optimizations "
"will make the generated trials similar, but not exactly the same, "
"and over time the trials will diverge more."
)
# ------------------------ Public API methods. ------------------------
def create_experiment(
self,
parameters: List[
Dict[str, Union[TParamValue, Sequence[TParamValue], Dict[str, List[str]]]]
],
name: Optional[str] = None,
description: Optional[str] = None,
owners: Optional[List[str]] = None,
objectives: Optional[Dict[str, ObjectiveProperties]] = None,
parameter_constraints: Optional[List[str]] = None,
outcome_constraints: Optional[List[str]] = None,
status_quo: Optional[TParameterization] = None,
overwrite_existing_experiment: bool = False,
experiment_type: Optional[str] = None,
tracking_metric_names: Optional[List[str]] = None,
choose_generation_strategy_kwargs: Optional[Dict[str, Any]] = None,
support_intermediate_data: bool = False,
immutable_search_space_and_opt_config: bool = True,
is_test: bool = False,
metric_definitions: Optional[Dict[str, Dict[str, Any]]] = None,
) -> None:
"""Create a new experiment and save it if DBSettings available.
Args:
parameters: List of dictionaries representing parameters in the
experiment search space.
Required elements in the dictionaries are:
1. "name" (name of parameter, string),
2. "type" (type of parameter: "range", "fixed", or "choice", string),
and one of the following:
3a. "bounds" for range parameters (list of two values, lower bound
first),
3b. "values" for choice parameters (list of values), or
3c. "value" for fixed parameters (single value).
Optional elements are:
1. "log_scale" (for float-valued range parameters, bool),
2. "value_type" (to specify type that values of this parameter should
take; expects "float", "int", "bool" or "str"),
3. "is_fidelity" (bool) and "target_value" (float) for fidelity
parameters,
4. "is_ordered" (bool) for choice parameters, and
5. "is_task" (bool) for task parameters.
6. "digits" (int) for float-valued range parameters.
name: Name of the experiment to be created.
description: Description of the experiment to be created.
objectives: Mapping from an objective name to object containing:
minimize: Whether this experiment represents a minimization problem.
threshold: The bound in the objective's threshold constraint.
parameter_constraints: List of string representation of parameter
constraints, such as "x3 >= x4" or "-x3 + 2*x4 - 3.5*x5 >= 2". For
the latter constraints, any number of arguments is accepted, and
acceptable operators are "<=" and ">=". Note that parameter
constraints may only be placed on range parameters, not choice
parameters or fixed parameters.
outcome_constraints: List of string representation of outcome
constraints of form "metric_name >= bound", like "m1 <= 3."
status_quo: Parameterization of the current state of the system.
If set, this will be added to each trial to be evaluated alongside
test configurations.
overwrite_existing_experiment: If an experiment has already been set
on this `AxClient` instance, whether to reset it to the new one.
If overwriting the experiment, generation strategy will be
re-selected for the new experiment and restarted.
To protect experiments in production, one cannot overwrite existing
experiments if the experiment is already stored in the database,
regardless of the value of `overwrite_existing_experiment`.
tracking_metric_names: Names of additional tracking metrics not used for
optimization.
choose_generation_strategy_kwargs: Keyword arguments to pass to
`choose_generation_strategy` function which determines what
generation strategy should be used when none was specified on init.
support_intermediate_data: Whether trials may report intermediate results
for trials that are still running (i.e. have not been completed via
`ax_client.complete_trial`).
immutable_search_space_and_opt_config: Whether it's possible to update the
search space and optimization config on this experiment after creation.
Defaults to True. If set to True, we won't store or load copies of the
search space and optimization config on each generator run, which will
improve storage performance.
is_test: Whether this experiment will be a test experiment (useful for
marking test experiments in storage etc). Defaults to False.
metric_definitions: A mapping of metric names to extra kwargs to pass
to that metric. Note these are modified in-place. Each
Metric must have its own dictionary (metrics cannot share a
single dictionary object).
"""
self._validate_early_stopping_strategy(support_intermediate_data)
objective_kwargs = {}
if objectives is not None:
objective_kwargs["objectives"] = {
objective: ("minimize" if properties.minimize else "maximize")
for objective, properties in objectives.items()
}
if len(objectives.keys()) > 1:
objective_kwargs["objective_thresholds"] = (
self.build_objective_thresholds(objectives)
)
experiment = self.make_experiment(
name=name,
description=description,
owners=owners,
parameters=parameters,
parameter_constraints=parameter_constraints,
outcome_constraints=outcome_constraints,
status_quo=status_quo,
experiment_type=experiment_type,
tracking_metric_names=tracking_metric_names,
metric_definitions=metric_definitions,
support_intermediate_data=support_intermediate_data,
immutable_search_space_and_opt_config=immutable_search_space_and_opt_config,
is_test=is_test,
**objective_kwargs,
)
self._set_runner(experiment=experiment)
self._set_experiment(
experiment=experiment,
overwrite_existing_experiment=overwrite_existing_experiment,
)
self._set_generation_strategy(
choose_generation_strategy_kwargs=choose_generation_strategy_kwargs
)
self._save_generation_strategy_to_db_if_possible()
@property
def status_quo(self) -> Optional[TParameterization]:
"""The parameterization of the status quo arm of the experiment."""
if self.experiment.status_quo:
return self.experiment.status_quo.parameters
return None
def set_status_quo(self, params: Optional[TParameterization]) -> None:
"""Set, or unset status quo on the experiment. There may be risk
in using this after a trial with the status quo arm has run.
Args:
status_quo: Parameterization of the current state of the system.
If set, this will be added to each trial to be evaluated alongside
test configurations.
"""
self.experiment.status_quo = None if params is None else Arm(parameters=params)
def set_optimization_config(
self,
objectives: Optional[Dict[str, ObjectiveProperties]] = None,
outcome_constraints: Optional[List[str]] = None,
metric_definitions: Optional[Dict[str, Dict[str, Any]]] = None,
) -> None:
"""Overwrite experiment's optimization config
Args:
objectives: Mapping from an objective name to object containing:
minimize: Whether this experiment represents a minimization problem.
threshold: The bound in the objective's threshold constraint.
outcome_constraints: List of string representation of outcome
constraints of form "metric_name >= bound", like "m1 <= 3."
metric_definitions: A mapping of metric names to extra kwargs to pass
to that metric
"""
optimization_config = self.make_optimization_config_from_properties(
objectives=objectives,
outcome_constraints=outcome_constraints,
status_quo_defined=self.experiment.status_quo is not None,
metric_definitions=metric_definitions,
)
if optimization_config:
self.experiment.optimization_config = optimization_config
self._save_experiment_to_db_if_possible(
experiment=self.experiment,
)
else:
raise ValueError(
"optimization config not set because it was missing objectives"
)
def add_tracking_metrics(
self,
metric_names: List[str],
metric_definitions: Optional[Dict[str, Dict[str, Any]]] = None,
) -> None:
"""Add a list of new metrics to the experiment.
If any of the metrics are already defined on the experiment,
we raise an error and don't add any of them to the experiment
Args:
metric_names: Names of metrics to be added.
metric_definitions: A mapping of metric names to extra kwargs to pass
to that metric. Note these are modified in-place. Each
Metric must have its is own dictionary (metrics cannot share a
single dictionary object).
"""
self.experiment.add_tracking_metrics(
metrics=[
self._make_metric(
name=metric_name, metric_definitions=metric_definitions
)
for metric_name in metric_names
]
)
@copy_doc(Experiment.remove_tracking_metric)
def remove_tracking_metric(self, metric_name: str) -> None:
self.experiment.remove_tracking_metric(metric_name=metric_name)
def set_search_space(
self,
parameters: List[
Dict[str, Union[TParamValue, Sequence[TParamValue], Dict[str, List[str]]]]
],
parameter_constraints: Optional[List[str]] = None,
) -> None:
"""Sets the search space on the experiment and saves.
This is expected to fail on base AxClient as experiment will have
immutable search space and optimization config set to True by default
Args:
parameters: List of dictionaries representing parameters in the
experiment search space.
Required elements in the dictionaries are:
1. "name" (name of parameter, string),
2. "type" (type of parameter: "range", "fixed", or "choice", string),
and one of the following:
3a. "bounds" for range parameters (list of two values, lower bound
first),
3b. "values" for choice parameters (list of values), or
3c. "value" for fixed parameters (single value).
Optional elements are:
1. "log_scale" (for float-valued range parameters, bool),
2. "value_type" (to specify type that values of this parameter should
take; expects "float", "int", "bool" or "str"),
3. "is_fidelity" (bool) and "target_value" (float) for fidelity
parameters,
4. "is_ordered" (bool) for choice parameters, and
5. "is_task" (bool) for task parameters.
6. "digits" (int) for float-valued range parameters.
parameter_constraints: List of string representation of parameter
constraints, such as "x3 >= x4" or "-x3 + 2*x4 - 3.5*x5 >= 2". For
the latter constraints, any number of arguments is accepted, and
acceptable operators are "<=" and ">=". Note that parameter
constraints may only be placed on range parameters, not choice
parameters or fixed parameters.
"""
self.experiment.search_space = self.make_search_space(
parameters=parameters, parameter_constraints=parameter_constraints
)
self._save_experiment_to_db_if_possible(
experiment=self.experiment,
)
@retry_on_exception(
logger=logger,
exception_types=(RuntimeError,),
check_message_contains=["Cholesky", "cholesky"],
suppress_all_errors=False,
wrap_error_message_in=CHOLESKY_ERROR_ANNOTATION,
)
def get_next_trial(
self,
ttl_seconds: Optional[int] = None,
force: bool = False,
fixed_features: Optional[FixedFeatures] = None,
) -> Tuple[TParameterization, int]:
"""
Generate trial with the next set of parameters to try in the iteration process.
Note: Service API currently supports only 1-arm trials.
Args:
ttl_seconds: If specified, will consider the trial failed after this
many seconds. Used to detect dead trials that were not marked
failed properly.
force: If set to True, this function will bypass the global stopping
strategy's decision and generate a new trial anyway.
fixed_features: A FixedFeatures object containing any
features that should be fixed at specified values during
generation.
Returns:
Tuple of trial parameterization, trial index
"""
# Check if the global stopping strategy suggests to stop the optimization.
# This is needed only if there is actually a stopping strategy specified,
# and if this function is not forced to generate a new trial.
if self.global_stopping_strategy and (not force):
# The strategy itself will check if enough trials have already been
# completed.
(
stop_optimization,
global_stopping_message,
) = self.global_stopping_strategy.should_stop_optimization(
experiment=self.experiment
)
if stop_optimization:
raise OptimizationShouldStop(message=global_stopping_message)
try:
trial = self.experiment.new_trial(
generator_run=self._gen_new_generator_run(
fixed_features=fixed_features
),
ttl_seconds=ttl_seconds,
)
except MaxParallelismReachedException as e:
if self._early_stopping_strategy is not None:
e.message += ( # noqa: B306
" When stopping trials early, make sure to call `stop_trial_early` "
"on the stopped trial."
)
raise e
logger.info(
f"Generated new trial {trial.index} with parameters "
f"{round_floats_for_logging(item=not_none(trial.arm).parameters)} "
f"using model {not_none(trial.generator_run)._model_key}."
)
trial.mark_running(no_runner_required=True)
self._save_or_update_trial_in_db_if_possible(
experiment=self.experiment, trial=trial
)
# TODO[T79183560]: Ensure correct handling of generator run when using
# foreign keys.
self._update_generation_strategy_in_db_if_possible(
generation_strategy=self.generation_strategy,
new_generator_runs=[self.generation_strategy._generator_runs[-1]],
)
return not_none(trial.arm).parameters, trial.index
def get_current_trial_generation_limit(self) -> Tuple[int, bool]:
"""How many trials this ``AxClient`` instance can currently produce via
calls to ``get_next_trial``, before more trials are completed, and whether
the optimization is complete.
NOTE: If return value of this function is ``(0, False)``, no more trials
can currently be procuded by this ``AxClient`` instance, but optimization
is not completed; once more trials are completed with data, more new
trials can be generated.
Returns: a two-item tuple of:
- the number of trials that can currently be produced, with -1
meaning unlimited trials,
- whether no more trials can be produced by this ``AxClient``
instance at any point (e.g. if the search space is exhausted or
generation strategy is completed.
"""
# Ensure that experiment is set on the generation strategy.
if self.generation_strategy._experiment is None:
self.generation_strategy.experiment = self.experiment
return self.generation_strategy.current_generator_run_limit()
def get_next_trials(
self,
max_trials: int,
ttl_seconds: Optional[int] = None,
fixed_features: Optional[FixedFeatures] = None,
) -> Tuple[Dict[int, TParameterization], bool]:
"""Generate as many trials as currently possible.
NOTE: Useful for running multiple trials in parallel: produces multiple trials,
with their number limited by:
- parallelism limit on current generation step,
- number of trials in current generation step,
- number of trials required to complete before moving to next generation step,
if applicable,
- and ``max_trials`` argument to this method.
Args:
max_trials: Limit on how many trials the call to this method should produce.
ttl_seconds: If specified, will consider the trial failed after this
many seconds. Used to detect dead trials that were not marked
failed properly.
fixed_features: A FixedFeatures object containing any
features that should be fixed at specified values during
generation.
Returns: two-item tuple of:
- mapping from trial indices to parameterizations in those trials,
- boolean indicator of whether optimization is completed and no more
trials can be generated going forward.
"""
gen_limit, optimization_complete = self.get_current_trial_generation_limit()
if optimization_complete:
return {}, True
# Trial generation limit of -1 indicates that unlimited trials can be
# generated, so we only want to limit `max_trials` if `trial_generation_
# limit` is non-negative.
if gen_limit >= 0:
max_trials = min(gen_limit, max_trials)
trials_dict = {}
for _ in range(max_trials):
try:
params, trial_index = self.get_next_trial(
ttl_seconds=ttl_seconds, fixed_features=fixed_features
)
trials_dict[trial_index] = params
except OptimizationComplete as err:
logger.info(
f"Encountered exception indicating optimization completion: {err}"
)
return trials_dict, True
# Check whether optimization is complete now that we generated a batch
# of trials.
_, optimization_complete = self.get_current_trial_generation_limit()
return trials_dict, optimization_complete
def abandon_trial(self, trial_index: int, reason: Optional[str] = None) -> None:
"""Abandons a trial and adds optional metadata to it.
Args:
trial_index: Index of trial within the experiment.
"""
trial = self.get_trial(trial_index)
trial.mark_abandoned(reason=reason)
def update_running_trial_with_intermediate_data(
self,
trial_index: int,
raw_data: TEvaluationOutcome,
metadata: Optional[Dict[str, Union[str, int]]] = None,
sample_size: Optional[int] = None,
) -> None:
"""
Updates the trial with given metric values without completing it. Also
adds optional metadata to it. Useful for intermediate results like
the metrics of a partially optimized machine learning model. In these
cases it should be called instead of `complete_trial` until it is
time to complete the trial.
NOTE: This method will raise an Exception if it is called multiple times
with the same ``raw_data``. These cases typically arise when ``raw_data``
does not change over time. To avoid this, pass a timestep metric in
``raw_data``, for example:
.. code-block:: python
for ts in range(100):
raw_data = [({"ts": ts}, {"my_objective": (1.0, 0.0)})]
ax_client.update_running_trial_with_intermediate_data(
trial_index=0, raw_data=raw_data
)
NOTE: When ``raw_data`` does not specify SEM for a given metric, Ax
will default to the assumption that the data is noisy (specifically,
corrupted by additive zero-mean Gaussian noise) and that the
level of noise should be inferred by the optimization model. To
indicate that the data is noiseless, set SEM to 0.0, for example:
.. code-block:: python
ax_client.update_running_trial_with_intermediate_data(
trial_index=0,
raw_data={"my_objective": (objective_mean_value, 0.0)}
)
Args:
trial_index: Index of trial within the experiment.
raw_data: Evaluation data for the trial. Can be a mapping from
metric name to a tuple of mean and SEM, just a tuple of mean and
SEM if only one metric in optimization, or just the mean if SEM is
unknown (then Ax will infer observation noise level).
Can also be a list of (fidelities, mapping from
metric name to a tuple of mean and SEM).
metadata: Additional metadata to track about this run.
sample_size: Number of samples collected for the underlying arm,
optional.
"""
if not isinstance(trial_index, int):
raise ValueError(f"Trial index must be an int, got: {trial_index}.")
if not self.experiment.default_data_type == DataType.MAP_DATA:
raise ValueError(
"`update_running_trial_with_intermediate_data` requires that "
"this client's `experiment` be constructed with "
"`support_intermediate_data=True` and have `default_data_type` of "
"`DataType.MAP_DATA`."
)
data_update_repr = self._update_trial_with_raw_data(
trial_index=trial_index,
raw_data=raw_data,
metadata=metadata,
sample_size=sample_size,
combine_with_last_data=True,
)
logger.info(f"Updated trial {trial_index} with data: " f"{data_update_repr}.")
def complete_trial(
self,
trial_index: int,
raw_data: TEvaluationOutcome,
metadata: Optional[Dict[str, Union[str, int]]] = None,
sample_size: Optional[int] = None,
) -> None:
"""
Completes the trial with given metric values and adds optional metadata
to it.
NOTE: When ``raw_data`` does not specify SEM for a given metric, Ax
will default to the assumption that the data is noisy (specifically,
corrupted by additive zero-mean Gaussian noise) and that the
level of noise should be inferred by the optimization model. To
indicate that the data is noiseless, set SEM to 0.0, for example:
.. code-block:: python
ax_client.complete_trial(
trial_index=0,
raw_data={"my_objective": (objective_mean_value, 0.0)}
)
Args:
trial_index: Index of trial within the experiment.
raw_data: Evaluation data for the trial. Can be a mapping from
metric name to a tuple of mean and SEM, just a tuple of mean and
SEM if only one metric in optimization, or just the mean if SEM is
unknown (then Ax will infer observation noise level).
Can also be a list of (fidelities, mapping from
metric name to a tuple of mean and SEM).
metadata: Additional metadata to track about this run.
sample_size: Number of samples collected for the underlying arm,
optional.
"""
# Validate that trial can be completed.
trial = self.get_trial(trial_index)
trial._validate_can_attach_data()
if not isinstance(trial_index, int):
raise ValueError(f"Trial index must be an int, got: {trial_index}.")
data_update_repr = self._update_trial_with_raw_data(
trial_index=trial_index,
raw_data=raw_data,
metadata=metadata,
sample_size=sample_size,
complete_trial=True,
combine_with_last_data=True,
)
logger.info(f"Completed trial {trial_index} with data: " f"{data_update_repr}.")
def update_trial_data(
self,
trial_index: int,
raw_data: TEvaluationOutcome,
metadata: Optional[Dict[str, Union[str, int]]] = None,
sample_size: Optional[int] = None,
) -> None:
"""
Attaches additional data or updates the existing data for a trial in a
terminal state. For example, if trial was completed with data for only
one of the required metrics, this can be used to attach data for the
remaining metrics.
NOTE: This does not change the trial status.
Args:
trial_index: Index of trial within the experiment.
raw_data: Evaluation data for the trial. Can be a mapping from
metric name to a tuple of mean and SEM, just a tuple of mean and
SEM if only one metric in optimization, or just the mean if there
is no SEM. Can also be a list of (fidelities, mapping from
metric name to a tuple of mean and SEM).
metadata: Additional metadata to track about this run.
sample_size: Number of samples collected for the underlying arm,
optional.
"""
if not isinstance(trial_index, int):
raise ValueError(f"Trial index must be an int, got: {trial_index}.")
trial = self.get_trial(trial_index)
if not trial.status.is_terminal:
raise ValueError(
f"Trial {trial.index} is not in a terminal state. Use "
"`ax_client.complete_trial` to complete the trial with new data "
"or use `ax_client.update_running_trial_with_intermediate_data` "
"to attach intermediate data to a running trial."
)
data_update_repr = self._update_trial_with_raw_data(
trial_index=trial_index,
raw_data=raw_data,
metadata=metadata,
sample_size=sample_size,
combine_with_last_data=True,
)
logger.info(f"Added data: {data_update_repr} to trial {trial.index}.")
def log_trial_failure(
self, trial_index: int, metadata: Optional[Dict[str, str]] = None
) -> None:
"""Mark that the given trial has failed while running.
Args:
trial_index: Index of trial within the experiment.
metadata: Additional metadata to track about this run.
"""
trial = self.experiment.trials[trial_index]
trial.mark_failed()
logger.info(f"Registered failure of trial {trial_index}.")
if metadata is not None:
trial._run_metadata = metadata
self._save_experiment_to_db_if_possible(
experiment=self.experiment,
)
def attach_trial(
self,
parameters: TParameterization,
ttl_seconds: Optional[int] = None,
run_metadata: Optional[Dict[str, Any]] = None,
arm_name: Optional[str] = None,
) -> Tuple[TParameterization, int]:
"""Attach a new trial with the given parameterization to the experiment.
Args:
parameters: Parameterization of the new trial.
ttl_seconds: If specified, will consider the trial failed after this
many seconds. Used to detect dead trials that were not marked
failed properly.
Returns:
Tuple of parameterization and trial index from newly created trial.
"""
output_parameters, trial_index = self.experiment.attach_trial(
parameterizations=[parameters],
arm_names=[arm_name] if arm_name else None,
ttl_seconds=ttl_seconds,
run_metadata=run_metadata,
)
self._save_or_update_trial_in_db_if_possible(
experiment=self.experiment,
trial=self.experiment.trials[trial_index],
)
return list(output_parameters.values())[0], trial_index
def get_trial_parameters(self, trial_index: int) -> TParameterization:
"""Retrieve the parameterization of the trial by the given index."""
return not_none(self.get_trial(trial_index).arm).parameters
def get_trials_data_frame(self) -> pd.DataFrame:
"""Get a Pandas DataFrame representation of this experiment. The columns
will include all the parameters in the search space and all the metrics
on this experiment. The rows will each correspond to a trial (if using
one-arm trials, which is the case in base ``AxClient``; will correspond
to arms in trials in the batch-trial case).
"""
return exp_to_df(exp=self.experiment)
def get_max_parallelism(self) -> List[Tuple[int, int]]:
"""Retrieves maximum number of trials that can be scheduled in parallel
at different stages of optimization.
Some optimization algorithms profit significantly from sequential
optimization (i.e. suggest a few points, get updated with data for them,
repeat, see https://ax.dev/docs/bayesopt.html).
Parallelism setting indicates how many trials should be running simulteneously
(generated, but not yet completed with data).
The output of this method is mapping of form
{num_trials -> max_parallelism_setting}, where the max_parallelism_setting
is used for num_trials trials. If max_parallelism_setting is -1, as
many of the trials can be ran in parallel, as necessary. If num_trials
in a tuple is -1, then the corresponding max_parallelism_setting
should be used for all subsequent trials.
For example, if the returned list is [(5, -1), (12, 6), (-1, 3)],
the schedule could be: run 5 trials with any parallelism, run 6 trials in
parallel twice, run 3 trials in parallel for as long as needed. Here,
'running' a trial means obtaining a next trial from `AxClient` through
get_next_trials and completing it with data when available.
Returns:
Mapping of form {num_trials -> max_parallelism_setting}.
"""
parallelism_settings = []
for step in self.generation_strategy._steps:
parallelism_settings.append(
(step.num_trials, step.max_parallelism or step.num_trials)
)
return parallelism_settings
def get_optimization_trace(
self, objective_optimum: Optional[float] = None
) -> AxPlotConfig:
"""Retrieves the plot configuration for optimization trace, which shows
the evolution of the objective mean over iterations.
Args:
objective_optimum: Optimal objective, if known, for display in the
visualization.
"""
if not self.experiment.trials:
raise ValueError("Cannot generate plot as there are no trials.")
objective = self.objective
if isinstance(objective, MultiObjective):
raise UnsupportedError(
"`get_optimization_trace` is not supported "
"for multi-objective experiments"
)
# Setting the objective values of infeasible points to be infinitely
# bad prevents them from increasing or decreasing the
# optimization trace.
def _constrained_trial_objective_mean(trial: BaseTrial) -> float:
if constraint_satisfaction(trial):
return checked_cast(Trial, trial).objective_mean
return float("inf") if self.objective.minimize else float("-inf")
objective_name = self.objective_name
best_objectives = np.array(
[
[
_constrained_trial_objective_mean(trial)
for trial in self.experiment.trials.values()
if trial.status.is_completed
]
]
)
hover_labels = [
_format_dict(not_none(checked_cast(Trial, trial).arm).parameters)
for trial in self.experiment.trials.values()
if trial.status.is_completed
]
return optimization_trace_single_method(
y=(
np.minimum.accumulate(best_objectives, axis=1)
if objective.minimize
else np.maximum.accumulate(best_objectives, axis=1)
),
optimum=objective_optimum,
title="Best objective found vs. # of iterations",
ylabel=objective_name.capitalize(),
hover_labels=hover_labels,
)
def get_contour_plot(
self,
param_x: Optional[str] = None,
param_y: Optional[str] = None,
metric_name: Optional[str] = None,
) -> AxPlotConfig:
"""Retrieves a plot configuration for a contour plot of the response
surface. For response surfaces with more than two parameters,
selected two parameters will appear on the axes, and remaining parameters
will be affixed to the middle of their range. If contour params arguments
are not provided, the first two parameters in the search space will be
used. If contour metrics are not provided, objective will be used.
Args:
param_x: name of parameters to use on x-axis for
the contour response surface plots.
param_y: name of parameters to use on y-axis for
the contour response surface plots.
metric_name: Name of the metric, for which to plot the response
surface.
"""
if not self.experiment.trials: