-
Notifications
You must be signed in to change notification settings - Fork 372
Expand file tree
/
Copy pathexperiment.py
More file actions
2754 lines (2429 loc) · 113 KB
/
experiment.py
File metadata and controls
2754 lines (2429 loc) · 113 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 inspect
import logging
import warnings
from collections import defaultdict
from collections.abc import Hashable, Iterable, Mapping, Sequence
from copy import deepcopy
from datetime import datetime
from functools import partial, reduce
from typing import Any, cast, Self, Union
import ax.core.observation as observation
import pandas as pd
from ax.core.arm import Arm
from ax.core.auxiliary import (
AuxiliaryExperiment,
AuxiliaryExperimentPurpose,
AuxiliaryExperimentValidation,
TransferLearningMetadata,
)
from ax.core.base_trial import BaseTrial
from ax.core.batch_trial import BatchTrial
from ax.core.data import combine_data_rows_favoring_recent, Data
from ax.core.derived_metric import DerivedMetric
from ax.core.experiment_status import ExperimentStatus
from ax.core.generator_run import GeneratorRun
from ax.core.llm_provider import LLMMessage
from ax.core.metric import Metric, MetricFetchE, MetricFetchResult
from ax.core.objective import Objective
from ax.core.optimization_config import (
MultiObjectiveOptimizationConfig,
OptimizationConfig,
)
from ax.core.parameter import DerivedParameter, Parameter
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.core.trial_status import (
DEFAULT_STATUSES_TO_WARM_START,
STATUSES_EXPECTING_DATA,
TrialStatus,
)
from ax.core.types import ComparisonOp, TParameterization
from ax.exceptions.core import (
AxError,
OptimizationNotConfiguredError,
RunnerNotFoundError,
UnsupportedError,
UserInputError,
)
from ax.utils.common.base import Base
from ax.utils.common.constants import Keys
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.result import Err, Ok
from pyre_extensions import assert_is_instance, none_throws
logger: logging.Logger = get_logger(__name__)
NO_RETRY_EXCEPTIONS: tuple[type[Exception], ...] = (
cast(type[Exception], RunnerNotFoundError),
cast(type[Exception], NotImplementedError),
cast(type[Exception], UnsupportedError),
)
ROUND_FLOATS_IN_LOGS_TO_DECIMAL_PLACES: int = 6
round_floats_for_logging: partial[Any] = partial(
_round_floats_for_logging,
decimal_places=ROUND_FLOATS_IN_LOGS_TO_DECIMAL_PLACES,
)
METRIC_DF_COLNAMES: Mapping[Hashable, str] = {
"name": "Name",
"type": "Type",
"goal": "Goal",
"bound": "Bound",
"lower_is_better": "Lower is Better",
}
class Experiment(Base):
"""Base class for defining an experiment."""
def __init__(
self,
search_space: SearchSpace,
name: str | None = None,
optimization_config: OptimizationConfig | None = None,
metrics: Sequence[Metric] | None = None,
runner: Runner | None = None,
status_quo: Arm | None = None,
description: str | None = None,
is_test: bool = False,
experiment_type: str | None = None,
properties: dict[str, Any] | None = None,
default_data_type: Any = None,
auxiliary_experiments_by_purpose: None
| (dict[AuxiliaryExperimentPurpose, list[AuxiliaryExperiment]]) = None,
default_trial_type: str | None = None,
tracking_metrics: list[Metric] | None = None,
) -> None:
"""Inits Experiment.
Args:
search_space: Search space of the experiment.
name: Name of the experiment.
optimization_config: Optimization config of the experiment.
runner: Default runner used for trials on this experiment.
status_quo: Arm representing existing "control" arm.
description: Description of the experiment.
is_test: Mark experiment as test in metadata. This flag is meant purely
for development and integration testing purposes. Leave as False for
live experiments.
experiment_type: The class of experiments this one belongs to.
properties: Dictionary of this experiment's properties. It is meant to
only store primitives that pertain to Ax experiment state. Any trial
deployment-related information and modeling-layer configuration
should be stored elsewhere, e.g. in ``run_metadata`` of the trials.
default_data_type: Deprecated and ignored.
auxiliary_experiments_by_purpose: Dictionary of auxiliary experiments
for different purposes (e.g., transfer learning).
tracking_metrics: Deprecated. Use ``metrics`` directly instead.
"""
if default_data_type is not None:
warnings.warn(
"default_data_type is deprecated and will be removed in a future "
"release.",
DeprecationWarning,
stacklevel=2,
)
self._search_space: SearchSpace = search_space
self._status_quo: Arm | None = None
self._name = name
self.description = description
self._runner = runner
self.is_test: bool = is_test
self.data: Data = Data()
self._experiment_type: str | None = experiment_type
self._optimization_config: OptimizationConfig | None = None
self._metrics: dict[str, Metric] = {}
self._time_created: datetime = datetime.now()
self._status: ExperimentStatus | None = None
self._trials: dict[int, BaseTrial] = {}
self._properties: dict[str, Any] = properties or {}
# Initialize trial type to runner mapping
self._default_trial_type = default_trial_type
self._trial_type_to_runner: dict[str | None, Runner | None] = {
default_trial_type: runner
}
# Maps each trial type to the set of metric names relevant to that type.
# This is the complement of _trial_type_to_runner and is used for
# multi-type experiments where different metrics apply to different
# trial types.
self._trial_type_to_metric_names: dict[str, set[str]] = {}
# Used to keep track of whether any trials on the experiment
# specify a TTL. Since trials need to be checked for their TTL's
# expiration often, having this attribute helps avoid unnecessary
# TTL checks for experiments that do not use TTL.
self._trials_have_ttl = False
# Make sure all statuses appear in this dict, to avoid key errors.
self._trial_indices_by_status: dict[TrialStatus, set[int]] = {
status: set() for status in TrialStatus
}
self._arms_by_signature: dict[str, Arm] = {}
self._arms_by_name: dict[str, Arm] = {}
# Used to keep track of auxiliary experiments that were removed.
self._initial_auxiliary_experiments_by_purpose: dict[
AuxiliaryExperimentPurpose, list[AuxiliaryExperiment]
] = auxiliary_experiments_by_purpose or {}
# Only tracks active auxiliary experiments.
self.auxiliary_experiments_by_purpose: dict[
AuxiliaryExperimentPurpose, list[AuxiliaryExperiment]
] = {
purpose: [
auxiliary_experiment
for auxiliary_experiment in auxiliary_experiments
if auxiliary_experiment.is_active
]
for (
purpose,
auxiliary_experiments,
) in self._initial_auxiliary_experiments_by_purpose.items()
}
# Attach metrics from both tracking_metrics and metrics, preferring metrics if
# a naming collision occurs.
for m in [*(tracking_metrics or []), *(metrics or [])]:
self._metrics[m.name] = m
if self._default_trial_type is not None:
self._trial_type_to_metric_names.setdefault(
self._default_trial_type, set()
).add(m.name)
# call setters defined below
self.status_quo = status_quo
if optimization_config is not None:
# Auto-register placeholder Metric objects for any optimization
# config metric names not already on the experiment. The
# ``optimization_config`` setter (below) validates that every
# referenced metric name exists in ``self._metrics``, so
# placeholders are needed here to satisfy that check. These
# placeholders are later replaced in two ways:
# 1. During SQA decoding, the decoder overwrites them with
# properly typed metrics from the database
# (see ``sqa_store/decoder.py``).
# 2. Any call to ``add_metric`` or ``update_metric`` with a
# real Metric of the same name will overwrite a placeholder.
for name in optimization_config.metric_names:
if name not in self._metrics:
self._metrics[name] = Metric(name=name)
self.optimization_config = optimization_config
# Keyed on tuple[trial_index, metric_name].
self._metric_fetching_errors: dict[
tuple[int, str], dict[str, Union[int, str]]
] = {}
@property
def has_name(self) -> bool:
"""Return true if experiment's name is not None."""
return self._name is not None
@property
def name(self) -> str:
"""Get experiment name. Throws if name is None."""
if self._name is None:
raise ValueError("Experiment's name is None.")
return self._name
@name.setter
def name(self, name: str) -> None:
"""Set experiment name."""
self._name = name
@property
def time_created(self) -> datetime:
"""Creation time of the experiment."""
return self._time_created
@property
def experiment_type(self) -> str | None:
"""The type of the experiment."""
return self._experiment_type
@experiment_type.setter
def experiment_type(self, experiment_type: str | None) -> None:
"""Set the type of the experiment."""
self._experiment_type = experiment_type
@property
def status(self) -> ExperimentStatus | None:
"""The current status of the experiment.
Status tracks the high-level lifecycle phase of the experiment:
DRAFT, INITIALIZATION, OPTIMIZATION, COMPLETED.
For new experiments, status defaults to DRAFT. For legacy experiments
that were created before the status field was added, status may be None.
"""
return self._status
@status.setter
def status(self, status: ExperimentStatus | None) -> None:
"""Set the status of the experiment.
Args:
status: The new status for the experiment.
"""
self._status = status
@staticmethod
def experiment_status_from_generator_runs(
generator_runs: list[GeneratorRun],
) -> ExperimentStatus | None:
"""Extract and validate suggested experiment status from generator runs.
Collects the suggested_experiment_status directly from the GeneratorRun
objects, validates that all runs suggest the same status, and returns
that status.
Args:
generator_runs: List of generator runs to extract statuses from.
Returns:
The suggested experiment status that all generator runs agree on,
or None if no statuses were found or if there are conflicting statuses.
"""
suggested_statuses: set[ExperimentStatus] = set()
for gr in generator_runs:
if gr.suggested_experiment_status is not None:
suggested_statuses.add(gr.suggested_experiment_status)
if len(suggested_statuses) > 1:
# TODO: Consider making this invalid state an actual error once
# related development is completed.
logger.warning(
"Multiple different suggested experiment statuses found: "
f"{suggested_statuses}. "
"All generator runs used in a single gen() call should suggest the "
"same experiment status. Skipping updating experiment status."
)
return None
if len(suggested_statuses) == 0:
return None
return suggested_statuses.pop()
@property
def search_space(self) -> SearchSpace:
"""The search space for this experiment.
When setting a new search space, all parameter names and types
must be preserved. However, if no trials have been created, all
modifications are allowed.
"""
# TODO: maybe return a copy here to guard against implicit changes
return self._search_space
@search_space.setter
def search_space(self, search_space: SearchSpace) -> None:
# Allow all modifications when no trials present.
if not hasattr(self, "_search_space") or len(self.trials) < 1:
self._search_space = search_space
return
# At least 1 trial is present.
if self.immutable_search_space_and_opt_config:
raise UnsupportedError(
"Modifications of search space are disabled by the "
f"`{Keys.IMMUTABLE_SEARCH_SPACE_AND_OPT_CONF.value}` "
"property that is set to `True` on this experiment."
)
if len(search_space.parameters) < len(self._search_space.parameters):
raise ValueError(
"New search_space must contain all parameters in the existing."
)
for param_name, parameter in search_space.parameters.items():
if param_name not in self._search_space.parameters:
raise ValueError(
f"Cannot add new parameter `{param_name}` because "
"it is not defined in the existing search space."
)
elif (
parameter.parameter_type
!= self._search_space.parameters[param_name].parameter_type
):
raise ValueError(
f"Expected parameter `{param_name}` to be of type "
f"{self._search_space.parameters[param_name].parameter_type}, "
f"got {parameter.parameter_type}."
)
self._search_space = search_space
def add_parameters_to_search_space(
self,
parameters: Sequence[Parameter],
status_quo_values: TParameterization | None = None,
parameter_constraints: Sequence[ParameterConstraint] | None = None,
) -> None:
"""
Add new parameters to the experiment's search space. This allows extending
the search space after the experiment has run some trials.
Backfill values must be provided for all new parameters if the experiment has
already run some trials. The backfill values represent the parameter values
that were used in the existing trials.
Args:
parameters: A sequence of parameter configurations to add to the search
space.
status_quo_values: Optional parameter values for the new parameters to
use in the status quo (baseline) arm, if one is defined.
parameter_constraints: Optional sequence of typed ParameterConstraint
objects to add to the search space after the parameters are added.
"""
status_quo_values = status_quo_values or {}
# Additional checks iff a trial exists
if len(self.trials) != 0:
if any(
(parameter.backfill_value is None)
and not isinstance(parameter, DerivedParameter)
for parameter in parameters
):
raise UserInputError(
"Must provide backfill values for all new parameters (except "
"DerivedParameters) when adding parameters to an experiment "
"with existing trials."
)
# Validate status quo values
status_quo = self._status_quo
if status_quo_values is not None and status_quo is None:
logger.warning(
"Status quo values specified, but experiment does not have a "
"status quo. Ignoring provided status quo values."
)
if status_quo is not None:
parameter_names = {parameter.name for parameter in parameters}
status_quo_parameters = status_quo_values.keys()
disabled_parameters = {
parameter.name
for parameter in self._search_space.parameters.values()
if parameter.is_disabled
}
extra_status_quo_values = status_quo_parameters - parameter_names
if extra_status_quo_values:
logger.warning(
"Status quo value provided for parameters "
f"`{extra_status_quo_values}` which is are being added to "
"the search space. Ignoring provided status quo values."
)
missing_status_quo_values = (
parameter_names - disabled_parameters - status_quo_parameters
)
if missing_status_quo_values:
raise UserInputError(
"No status quo value provided for parameters "
f"`{missing_status_quo_values}` which are being added to "
"the search space."
)
for parameter_name, value in status_quo_values.items():
status_quo._parameters[parameter_name] = value
# Add parameters to search space
self._search_space.add_parameters(parameters)
# Add parameter constraints to search space
if parameter_constraints:
self._search_space.add_parameter_constraints(list(parameter_constraints))
def disable_parameters_in_search_space(
self, default_parameter_values: TParameterization
) -> None:
"""
Disable parameters in the experiment. This allows narrowing the search space
after the experiment has run some trials.
When parameters are disabled, they are effectively removed from the search
space for future trial generation. Existing trials remain valid, and the
disabled parameters are replaced with fixed default values for all subsequent
trials.
Args:
default_parameter_values: Fixed values to use for the disabled parameters
in all future trials. These values will be used for the parameter in
all subsequent trials.
"""
self._search_space.disable_parameters(default_parameter_values)
@property
def status_quo(self) -> Arm | None:
"""The existing arm that new arms will be compared against."""
return self._status_quo
@status_quo.setter
def status_quo(self, status_quo: Arm | None) -> None:
# Make status_quo immutable once any trial has been created.
if self._status_quo is not None and len(self.trials) > 0:
raise UnsupportedError(
"Modifications of status_quo are disabled after trials have been "
"created."
)
if status_quo == self.status_quo:
return # No need to update the SQ arm.
if status_quo is not None:
self.search_space.check_types(
parameterization=status_quo.parameters,
allow_extra_params=False,
raise_error=True,
)
self.search_space.check_all_parameters_present(
parameterization=status_quo.parameters, raise_error=True
)
# Compute a unique name if "status_quo" is taken
name = "status_quo"
sq_idx = 0
arms_by_name = self.arms_by_name
while name in arms_by_name:
name = f"status_quo_e{sq_idx}"
sq_idx += 1
self._name_and_store_arm_if_not_exists(arm=status_quo, proposed_name=name)
self._status_quo = status_quo
@property
def runner(self) -> Runner | None:
"""Default runner used for trials on this experiment."""
return self._runner
@runner.setter
def runner(self, runner: Runner | None) -> None:
"""Set the default runner and update trial type mapping."""
self._runner = runner
if runner is not None:
self._trial_type_to_runner[self._default_trial_type] = runner
else:
self._trial_type_to_runner = {None: None}
@runner.deleter
def runner(self) -> None:
"""Delete the runner."""
self._runner = None
self._trial_type_to_runner = {None: None}
@property
def parameters(self) -> dict[str, Parameter]:
"""The parameters in the experiment's search space."""
return self.search_space.parameters
@property
def arms_by_name(self) -> dict[str, Arm]:
"""The arms belonging to this experiment, by their name."""
return self._arms_by_name
@property
def arms_by_signature(self) -> dict[str, Arm]:
"""The arms belonging to this experiment, by their signature."""
return self._arms_by_signature
@property
def arms_by_signature_for_deduplication(self) -> dict[str, Arm]:
"""The arms belonging to this experiment that should be used for deduplication
in ``GenerationStrategy``, by their signature.
In its current form, this includes all arms except for those that are
associated with a ``FAILED`` trial.
- The ``CANDIDATE``, ``STAGED``, ``RUNNING``, and ``ABANDONED`` arms are
included as pending points during generation, so they should be less likely
to get suggested by the model again.
- The ``EARLY_STOPPED`` and ``COMPLETED`` trials were already evaluated, so
the model will have data for these and is unlikely to suggest them again.
"""
arms_dict = self.arms_by_signature.copy()
for trial in self.trials_by_status[TrialStatus.FAILED]:
for arm in trial.arms:
arms_dict.pop(arm.signature, None)
return arms_dict
@property
def sum_trial_sizes(self) -> int:
"""Sum of numbers of arms attached to each trial in this experiment."""
return reduce(lambda a, b: a + len(b.arms_by_name), self._trials.values(), 0)
@property
def num_abandoned_arms(self) -> int:
"""How many arms attached to this experiment are abandoned."""
abandoned = set()
for trial in self.trials.values():
for x in trial.abandoned_arms:
abandoned.add(x)
return len(abandoned)
@property
def optimization_config(self) -> OptimizationConfig | None:
"""The experiment's optimization config."""
return self._optimization_config
@optimization_config.setter
def optimization_config(self, optimization_config: OptimizationConfig) -> None:
if (
len(self.trials) > 0
and getattr(self, "_optimization_config", None) is not None
and self.immutable_search_space_and_opt_config
):
raise UnsupportedError(
"Modifications of optimization config are disabled by the "
f"`{Keys.IMMUTABLE_SEARCH_SPACE_AND_OPT_CONF.value}` "
"property that is set to `True` on this experiment."
)
for metric_name in optimization_config.metric_names:
if metric_name not in self._metrics:
raise ValueError(
f"Metric '{metric_name}' referenced in optimization config "
"but not found on experiment. Add it first with add_metric()."
)
self._optimization_config = optimization_config
resolved_trial_type = self._resolve_trial_type(None)
if resolved_trial_type is not None:
for metric_name in optimization_config.metric_names:
self._trial_type_to_metric_names.setdefault(
resolved_trial_type, set()
).add(metric_name)
@property
def is_moo_problem(self) -> bool:
"""Whether the experiment's optimization config contains multiple objectives."""
if self.optimization_config is None:
return False
return none_throws(self.optimization_config).is_moo_problem
@property
def is_bope_problem(self) -> bool:
"""Whether this experiment is a BO with Preference Exploration (BOPE)
experiment.
An experiment is considered a preference learning experiment if:
1. It has a PreferenceOptimizationConfig as its optimization config, OR
2. It has a PE_EXPERIMENT (preference exploration) auxiliary experiment attached
Returns:
True if this is a preference learning experiment, False otherwise.
"""
# Check if optimization config indicates preference learning
if self.optimization_config is not None:
if self.optimization_config.is_bope_problem:
return True
# Check if experiment has a PE_EXPERIMENT auxiliary experiment
return bool(
self.auxiliary_experiments_by_purpose.get(
AuxiliaryExperimentPurpose.PE_EXPERIMENT, []
)
)
@property
def immutable_search_space_and_opt_config(self) -> bool:
"""Boolean representing whether search space and metrics on this experiment
are mutable (by default they are).
NOTE: For experiments with immutable search spaces and metrics, generator
runs will not store copies of search space and metrics, which improves
storage layer performance. Not keeping copies of those on generator runs
also disables keeping track of changes to search space and metrics,
thereby necessitating that those attributes be immutable on experiment.
"""
return self._properties.get(Keys.IMMUTABLE_SEARCH_SPACE_AND_OPT_CONF, False)
@property
def llm_messages(self) -> list[LLMMessage]:
"""LLM conversation messages stored on this experiment.
These messages capture the conversation history for LLM-integrated
optimization workflows such as LILO (Language-in-the-Loop Optimization)
and LLAMBO. They include system prompts, user feedback, and assistant
responses that inform candidate generation.
"""
return self._properties.get(Keys.LLM_MESSAGES, [])
@llm_messages.setter
def llm_messages(self, messages: list[LLMMessage]) -> None:
self._properties[Keys.LLM_MESSAGES] = messages
def get_llm_messages_with_experiment_summary(
self,
) -> list[LLMMessage]:
"""Retrieve a copy of LLM messages with an experiment summary appended.
Returns a deep copy of the stored LLM messages with a user message
appended containing a markdown summary of the experiment's search
space, optimization config, and observed trial data. This is useful
for LLM-based workflows (e.g., LLAMBO, LILO) that condition on both
the conversation history and observed trial outcomes.
The summary always includes experiment metadata (search space and
optimization config). Arm parameters and trial results are included
when completed, early-stopped, or running trial data exists.
Returns:
A list of ``LLMMessage`` objects suitable for passing to an
``LLMProvider.generate()`` call.
"""
messages = [
LLMMessage(role=m.role, content=m.content, metadata=deepcopy(m.metadata))
for m in self.llm_messages
]
experiment_summary = self._format_experiment_summary_for_llm()
if experiment_summary:
messages.append(LLMMessage(role="user", content=experiment_summary))
return messages
def _format_experiment_summary_for_llm(self) -> str:
"""Format experiment summary as text for inclusion in LLM messages.
Produces a human-readable markdown summary of the experiment including:
- Experiment name
- Search space parameter definitions
- Optimization configuration (objectives and constraints)
- Arm parameterizations (deduplicated), when data is available
- Observed trial results with metric values
(mean ± 95% CI when SEM is available), when data is available
The experiment metadata (name, search space, optimization config) is
always included. Arm parameters and trial results are appended only
when completed, early-stopped, or running trial data exists.
Returns:
A markdown-formatted string summary of the experiment.
"""
sections: list[str] = []
# Experiment name
sections.append(f"## Experiment: {self._name or 'Unnamed'}")
# Search space parameters
param_lines: list[str] = ["### Search Space"]
for param in self.search_space.parameters.values():
param_lines.append(f"- {param}")
if self.search_space.is_hierarchical:
ss_str = self.search_space.hierarchical_structure_str(
parameter_names_only=True
)
param_lines.append(
"\n**Hierarchical Structure:**\n"
"Not all parameters are active at the same time. "
"The active parameters depend on the values of other parameters "
"as described in the tree below. Each top-level entry is a "
"parameter. Indented entries in parentheses, e.g. (0), are "
"possible values for that parameter. The parameters listed "
"under a value are the ones that become active when the parent "
"parameter takes that value. Only provide values for the "
f"active parameters.\n{ss_str}"
)
sections.append("\n".join(param_lines))
# Optimization config
opt_config = self.optimization_config
if opt_config is not None:
opt_lines: list[str] = ["### Optimization Config"]
objective = opt_config.objective
for metric_name, weight in objective.metric_weights:
direction = "minimize" if weight < 0 else "maximize"
opt_lines.append(f"- Objective: {direction} `{metric_name}`")
for constraint in opt_config.outcome_constraints:
opt_lines.append(f"- Constraint: `{constraint.expression}` ")
sections.append("\n".join(opt_lines))
# Trial data
data = self.lookup_data()
if data.df.empty:
return "\n\n".join(sections)
# Build arm parameters table (deduplicated by arm_name).
arm_param_rows: list[dict[str, str]] = []
seen_arms: set[str] = set()
# Build trial results table.
result_rows: list[dict[str, str]] = []
has_ci = False
for trial_index, trial in self.trials.items():
if trial.status not in (
TrialStatus.COMPLETED,
TrialStatus.EARLY_STOPPED,
TrialStatus.RUNNING,
):
continue
trial_data = data.df[data.df["trial_index"] == trial_index]
if trial_data.empty:
continue
for arm_name in trial_data["arm_name"].unique():
arm = trial.arms_by_name.get(arm_name)
if arm is None:
continue
# Deduplicated arm parameters.
if arm_name not in seen_arms:
seen_arms.add(arm_name)
arm_param_rows.append(
{
"arm_name": arm_name,
"parameters": str(arm.parameters),
}
)
# Metric results for this trial/arm.
arm_data = trial_data[trial_data["arm_name"] == arm_name]
row: dict[str, str] = {
"trial_index": str(trial_index),
"arm_name": arm_name,
"trial_status": trial.status.name,
}
for _, metric_row in arm_data.iterrows():
metric_name = metric_row["metric_name"]
mean = metric_row["mean"]
sem = metric_row.get("sem")
if sem is not None and not pd.isna(sem):
ci = 1.96 * sem
row[metric_name] = f"{mean:.4g} ± {ci:.4g}"
has_ci = True
else:
row[metric_name] = str(mean)
result_rows.append(row)
if not result_rows:
return "\n\n".join(sections)
# Arm parameters section.
params_df = pd.DataFrame(arm_param_rows)
sections.append(f"### Arm Parameters\n\n{params_df.to_markdown(index=False)}")
# Trial results section.
results_df = pd.DataFrame(result_rows)
ci_note = "\n\nMetric values with ± denote mean ± 95% CI." if has_ci else ""
sections.append(
f"### Trial Results{ci_note}\n\n{results_df.to_markdown(index=False)}"
)
return "\n\n".join(sections)
@property
def tracking_metrics(self) -> list[Metric]:
"""Metrics that are tracked but not part of the optimization config."""
if self._optimization_config is None:
return list(self._metrics.values())
opt_metric_names = self._optimization_config.metric_names
return [m for name, m in self._metrics.items() if name not in opt_metric_names]
@property
def optimization_config_metrics(self) -> list[Metric]:
"""Metrics that are part of the optimization config."""
if self._optimization_config is None:
return []
opt_metric_names = self._optimization_config.metric_names
return self.get_metrics(metric_names=list(opt_metric_names))
def get_metric(self, name: str) -> Metric:
"""Get a single Metric by name.
Args:
name: The name of the metric to retrieve.
Returns:
The Metric object with the given name.
Raises:
KeyError: If no metric with the given name exists.
"""
if name not in self._metrics:
raise KeyError(
f"Metric '{name}' not found. Available: {list(self._metrics.keys())}"
)
return self._metrics[name]
def _resolve_trial_type(self, trial_type: str | None) -> str | None:
"""Resolve an explicit or default trial type and validate it.
Returns ``trial_type`` if explicitly provided (after validating via
``supports_trial_type``), falls back to ``_default_trial_type`` when
available, and raises ``ValueError`` if this experiment uses trial types
(``_trial_type_to_metric_names`` is non-empty) but none could be
resolved.
Args:
trial_type: The explicitly provided trial type, or ``None``.
Returns:
The resolved trial type, which may be ``None`` for single-type
experiments.
Raises:
ValueError: If ``trial_type`` is provided but not supported, or if
no trial type could be resolved for a multi-type experiment.
"""
if trial_type is not None:
if not self.supports_trial_type(trial_type):
raise ValueError(f"`{trial_type}` is not a supported trial type.")
return trial_type
if self._default_trial_type is not None:
return self._default_trial_type
if self._trial_type_to_metric_names:
raise ValueError(
"This experiment has trial-type-aware metrics but no "
"`trial_type` was specified and no `default_trial_type` is set. "
"Please specify a `trial_type`."
)
return None
def add_metric(self, metric: Metric, trial_type: str | None = None) -> Self:
"""Add a new metric to the experiment.
Metrics that are not referenced by the experiment's optimization config
(i.e. not part of an objective or outcome constraint) are automatically
treated as tracking metrics.
Args:
metric: Metric to be added.
trial_type: If provided, associates the metric with this trial type.
When ``None`` and a ``default_trial_type`` is set, defaults to
the default trial type.
Raises:
ValueError: If the metric already exists, the trial type is not
supported, or trial types are in use but none could be resolved.
"""
if metric.name in self._metrics:
raise ValueError(
f"Metric `{metric.name}` already defined on experiment. "
"Use `update_metric` to update an existing metric definition."
)
trial_type = self._resolve_trial_type(trial_type)
if trial_type is not None:
self._trial_type_to_metric_names.setdefault(trial_type, set()).add(
metric.name
)
self._metrics[metric.name] = metric
return self
def add_tracking_metric(
self,
metric: Metric,
trial_type: str | None = None,
canonical_name: str | None = None,
) -> Self:
"""*Deprecated.* Use ``add_metric`` instead."""
warnings.warn(
"add_tracking_metric is deprecated. Use add_metric instead.",
DeprecationWarning,
stacklevel=2,
)
return self.add_metric(metric, trial_type=trial_type)
def add_tracking_metrics(
self,
metrics: list[Metric],
metrics_to_trial_types: dict[str, str] | None = None,
canonical_names: dict[str, str] | None = None,
) -> Experiment:
"""*Deprecated.* Use ``add_metric`` instead."""
warnings.warn(
"add_tracking_metrics is deprecated. Use add_metric instead.",
DeprecationWarning,
stacklevel=2,
)
metrics_to_trial_types = metrics_to_trial_types or {}
for metric in metrics:
canonical_name = (canonical_names or {}).get(metric.name)
self.add_tracking_metric(
metric=metric,
trial_type=metrics_to_trial_types.get(metric.name),
canonical_name=canonical_name,
)
return self
def update_metric(self, metric: Metric, trial_type: str | None = None) -> Self:
"""Redefine a metric that already exists on the experiment.
Args:
metric: New metric definition.
trial_type: If provided, reassociates the metric with this trial
type. When ``None``, keeps the metric's existing trial type.
"""
if metric.name not in self._metrics:
raise ValueError(f"Metric `{metric.name}` doesn't exist on experiment.")
if trial_type is not None:
trial_type = self._resolve_trial_type(trial_type)
# Remove from any existing trial type set
for names in self._trial_type_to_metric_names.values():
names.discard(metric.name)
# Add to new trial type set
self._trial_type_to_metric_names.setdefault(trial_type, set()).add(
metric.name
)
self._metrics[metric.name] = metric
return self
def update_tracking_metric(
self,
metric: Metric,
trial_type: str | None = None,
canonical_name: str | None = None,
) -> Experiment:
"""*Deprecated.* Use ``update_metric`` instead."""
warnings.warn(
"update_tracking_metric is deprecated. Use update_metric instead.",
DeprecationWarning,
stacklevel=2,
)
return self.update_metric(metric, trial_type=trial_type)
def remove_metric(self, metric_name: str) -> Self:
"""Remove a metric from the experiment.
Args:
metric_name: Unique name of metric to remove.
Raises:
ValueError: If the metric is referenced by the optimization config.
"""
if metric_name not in self._metrics: