forked from facebook/Ax
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_experiment.py
More file actions
2710 lines (2427 loc) · 110 KB
/
test_experiment.py
File metadata and controls
2710 lines (2427 loc) · 110 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 time import sleep
from unittest.mock import MagicMock, patch
import pandas as pd
from ax.adapter.registry import Generators
from ax.core import BatchTrial, Experiment, Trial
from ax.core.arm import Arm
from ax.core.auxiliary import AuxiliaryExperiment, AuxiliaryExperimentPurpose
from ax.core.base_trial import BaseTrial, TrialStatus
from ax.core.data import Data, sort_by_trial_index_and_arm_name
from ax.core.evaluations_to_data import raw_evaluations_to_data
from ax.core.experiment_status import ExperimentStatus
from ax.core.generator_run import GeneratorRun
from ax.core.llm_provider import LLMMessage
from ax.core.map_metric import MapMetric
from ax.core.metric import Metric
from ax.core.objective import MultiObjective, Objective
from ax.core.optimization_config import (
MultiObjectiveOptimizationConfig,
ObjectiveThreshold,
OptimizationConfig,
PreferenceOptimizationConfig,
)
from ax.core.outcome_constraint import OutcomeConstraint
from ax.core.parameter import (
ChoiceParameter,
DerivedParameter,
FixedParameter,
ParameterType,
RangeParameter,
)
from ax.core.search_space import SearchSpace
from ax.core.types import ComparisonOp
from ax.exceptions.core import (
AxError,
OptimizationNotConfiguredError,
RunnerNotFoundError,
UnsupportedError,
UserInputError,
)
from ax.generation_strategy.generation_node import GenerationNode
from ax.generation_strategy.generation_strategy import GenerationStrategy
from ax.generation_strategy.generator_spec import GeneratorSpec
from ax.metrics.branin import BraninMetric
from ax.metrics.hartmann6 import Hartmann6Metric
from ax.metrics.noisy_function import NoisyFunctionMetric
from ax.runners.synthetic import SyntheticRunner
from ax.service.ax_client import AxClient
from ax.service.utils.instantiation import ObjectiveProperties
from ax.storage.sqa_store.db import init_test_engine_and_session_factory
from ax.storage.sqa_store.load import load_experiment
from ax.storage.sqa_store.save import save_experiment
from ax.utils.common.constants import Keys
from ax.utils.common.random import set_rng_seed
from ax.utils.common.testutils import TestCase
from ax.utils.testing.core_stubs import (
get_arm,
get_branin_arms,
get_branin_experiment,
get_branin_experiment_with_multi_objective,
get_branin_experiment_with_timestamp_map_metric,
get_branin_optimization_config,
get_branin_search_space,
get_data,
get_experiment,
get_experiment_with_data,
get_experiment_with_map_data_type,
get_experiment_with_observations,
get_hierarchical_search_space,
get_optimization_config,
get_optimization_config_no_constraints,
get_scalarized_outcome_constraint,
get_search_space,
get_sobol,
get_status_quo,
get_test_map_data_experiment,
)
from ax.utils.testing.mock import mock_botorch_optimize
from pandas.testing import assert_frame_equal
from pyre_extensions import assert_is_instance, none_throws
DUMMY_RUN_METADATA_KEY_1 = "test_run_metadata_key_1"
DUMMY_RUN_METADATA_KEY_2 = "test_run_metadata_key_2"
DUMMY_RUN_METADATA_VALUE_1 = "test_run_metadata_value_1"
DUMMY_RUN_METADATA_VALUE_2 = "test_run_metadata_value_2"
DUMMY_RUN_METADATA: dict[str, str] = {
DUMMY_RUN_METADATA_KEY_1: DUMMY_RUN_METADATA_VALUE_1,
DUMMY_RUN_METADATA_KEY_2: DUMMY_RUN_METADATA_VALUE_2,
}
DUMMY_ABANDONED_REASON = "test abandoned reason"
DUMMY_ARM_NAME = "test_arm_name"
class TestMetric(Metric):
"""Shell metric class for testing."""
__test__ = False
pass
class SyntheticRunnerWithMetadataKeys(SyntheticRunner):
@property
def run_metadata_report_keys(self) -> list[str]:
return [DUMMY_RUN_METADATA_KEY_1, DUMMY_RUN_METADATA_KEY_2]
class ExperimentTest(TestCase):
def setUp(self) -> None:
super().setUp()
self.experiment = get_experiment()
def _setup_branin_experiment(self, n: int) -> Experiment:
exp = Experiment(
name="test3",
search_space=get_branin_search_space(),
tracking_metrics=[BraninMetric(name="b", param_names=["x1", "x2"])],
runner=SyntheticRunner(),
)
batch = exp.new_batch_trial()
batch.add_arms_and_weights(arms=get_branin_arms(n=n, seed=0))
batch.run()
batch_2 = exp.new_batch_trial()
batch_2.add_arms_and_weights(arms=get_branin_arms(n=3 * n, seed=1))
batch_2.run()
return exp
def test_experiment_init(self) -> None:
self.assertEqual(self.experiment.name, "test")
self.assertEqual(self.experiment.description, "test description")
self.assertEqual(self.experiment.name, "test")
self.assertIsNotNone(self.experiment.time_created)
self.assertEqual(self.experiment.experiment_type, None)
self.assertEqual(self.experiment.num_abandoned_arms, 0)
with self.assertWarnsRegex(
DeprecationWarning, "default_data_type is deprecated"
):
Experiment(
search_space=self.experiment.search_space,
default_data_type="foo",
)
def test_experiment_name(self) -> None:
self.assertTrue(self.experiment.has_name)
self.experiment.name = None
self.assertFalse(self.experiment.has_name)
with self.assertRaises(ValueError):
self.experiment.name
self.experiment.name = "test"
def test_experiment_type(self) -> None:
self.experiment.experiment_type = "test"
self.assertEqual(self.experiment.experiment_type, "test")
def test_eq(self) -> None:
self.assertEqual(self.experiment, self.experiment)
experiment2 = Experiment(
name="test2",
search_space=get_search_space(),
optimization_config=get_optimization_config(),
status_quo=get_arm(),
description="test description",
)
self.assertNotEqual(self.experiment, experiment2)
def test_db_id(self) -> None:
self.assertIsNone(self.experiment.db_id)
some_id = 123456789
self.experiment.db_id = some_id
self.assertEqual(self.experiment.db_id, some_id)
def test_tracking_metrics_merge(self) -> None:
# Tracking and optimization metrics should get merged
# m1 is on optimization_config while m3 is not
exp = Experiment(
name="test2",
search_space=get_search_space(),
optimization_config=get_optimization_config(),
tracking_metrics=[Metric(name="m1"), Metric(name="m3")],
)
self.assertEqual(
len(none_throws(exp.optimization_config).metrics) + 1, len(exp.metrics)
)
def test_basic_batch_creation(self) -> None:
batch = self.experiment.new_batch_trial()
self.assertEqual(len(self.experiment.trials), 1)
self.assertEqual(self.experiment.trials[0], batch)
# Try (and fail) to re-attach batch
with self.assertRaises(ValueError):
self.experiment._attach_trial(batch)
# Try (and fail) to attach batch to another experiment
with self.assertRaises(ValueError):
new_exp = get_experiment()
new_exp._attach_trial(batch)
def test_supports_trial_type(self) -> None:
exp = get_experiment()
self.assertTrue(exp.supports_trial_type(None))
self.assertTrue(exp.supports_trial_type(Keys.SHORT_RUN))
self.assertTrue(exp.supports_trial_type(Keys.LONG_RUN))
self.assertTrue(exp.supports_trial_type(Keys.LILO_LABELING))
self.assertFalse(exp.supports_trial_type("unsupported_type"))
# Verify LILO_LABELING trial type works with new_batch_trial
batch = exp.new_batch_trial(trial_type=Keys.LILO_LABELING)
self.assertEqual(batch.trial_type, Keys.LILO_LABELING)
def test_repr(self) -> None:
self.assertEqual("Experiment(test)", str(self.experiment))
def test_basic_properties(self) -> None:
self.assertEqual(self.experiment.status_quo, get_status_quo())
self.assertEqual(self.experiment.search_space, get_search_space())
self.assertEqual(self.experiment.optimization_config, get_optimization_config())
self.assertEqual(self.experiment.is_test, True)
def test_only_range_parameter_constraints(self) -> None:
self.assertEqual(0, 0)
self.assertTrue(True)
ax_client = AxClient()
# Create an experiment with valid parameter constraints
ax_client.create_experiment(
name="experiment",
parameters=[
{
"name": "x1",
"type": "range",
"bounds": [0.0, 1.0],
},
{
"name": "x2",
"type": "range",
"bounds": [0.0, 1.0],
},
],
objectives={"objective": ObjectiveProperties(minimize=False)},
parameter_constraints=["x1 + x2 <= 1"],
)
# Try (and fail) to create an experiment with constraints on choice
# paramaters
with self.assertRaises(ValueError):
ax_client.create_experiment(
name="experiment",
parameters=[
{
"name": "x1",
"type": "choice",
"values": [0.0, 1.0],
},
{
"name": "x2",
"type": "range",
"bounds": [0.0, 1.0],
},
],
objectives={"objective": ObjectiveProperties(minimize=False)},
parameter_constraints=["x1 + x2 <= 1"],
)
# Try (and fail) to create an experiment with constraints on fixed
# parameters
with self.assertRaises(ValueError):
ax_client.create_experiment(
name="experiment",
parameters=[
{"name": "x1", "type": "fixed", "value": 0.0},
{
"name": "x2",
"type": "range",
"bounds": [0.0, 1.0],
},
],
objectives={"objective": ObjectiveProperties(minimize=False)},
parameter_constraints=["x1 + x2 <= 1"],
)
def test_metric_setters(self) -> None:
# Establish current metrics size
self.assertEqual(
len(get_optimization_config().metrics) + 1, len(self.experiment.metrics)
)
# Add optimization config with 1 different metric
opt_config = get_optimization_config()
opt_config.outcome_constraints[0].metric = Metric(name="m3")
self.experiment.optimization_config = opt_config
# Verify total metrics has increaed by 1.
self.assertEqual(
len(get_optimization_config().metrics) + 2, len(self.experiment.metrics)
)
# Add optimization config with 1 scalarized constraint composed of 2 metrics
opt_config = get_optimization_config()
opt_config.outcome_constraints = opt_config.outcome_constraints + [
get_scalarized_outcome_constraint()
]
self.experiment.optimization_config = opt_config
# Verify total metrics size is the same.
self.assertEqual(len(opt_config.metrics) + 2, len(self.experiment.metrics))
self.assertEqual(
len(get_optimization_config().metrics) + 4, len(self.experiment.metrics)
)
# set back
self.experiment.optimization_config = get_optimization_config()
# Test adding new tracking metric
self.experiment.add_tracking_metric(Metric(name="m4"))
self.assertEqual(
len(get_optimization_config().metrics) + 5, len(self.experiment.metrics)
)
# Test adding new tracking metrics
self.experiment.add_tracking_metrics([Metric(name="z1")])
self.assertEqual(
len(get_optimization_config().metrics) + 6, len(self.experiment.metrics)
)
# Verify update_tracking_metric updates the metric definition
self.assertIsNone(self.experiment.metrics["m4"].lower_is_better)
self.experiment.update_tracking_metric(Metric(name="m4", lower_is_better=True))
self.assertTrue(self.experiment.metrics["m4"].lower_is_better)
# Verify unable to add existing metric
with self.assertRaises(ValueError):
self.experiment.add_tracking_metric(Metric(name="m4"))
# Verify unable to add existing metric
with self.assertRaises(ValueError):
self.experiment.add_tracking_metrics([Metric(name="z1"), Metric(name="m4")])
# Verify unable to add metric in optimization config
with self.assertRaises(ValueError):
self.experiment.add_tracking_metric(Metric(name="m1"))
# Verify unable to add metric in optimization config
with self.assertRaises(ValueError):
self.experiment.add_tracking_metrics([Metric(name="z2"), Metric(name="m1")])
# Cannot update metric not already on experiment
with self.assertRaises(ValueError):
self.experiment.update_tracking_metric(Metric(name="m5"))
# Cannot remove metric not already on experiment
with self.assertRaises(ValueError):
self.experiment.remove_tracking_metric(metric_name="m5")
def test_search_space_setter(self) -> None:
one_param_ss = SearchSpace(parameters=[get_search_space().parameters["w"]])
# Verify all search space ok with no trials
self.experiment.search_space = one_param_ss
self.assertEqual(len(self.experiment.parameters), 1)
# Reset search space and add batch to trigger validations
self.experiment.search_space = get_search_space()
self.experiment.new_batch_trial()
# Try search space with too few parameters
with self.assertRaises(ValueError):
self.experiment.search_space = one_param_ss
# Try search space with different type
bad_type_ss = get_search_space()
bad_type_ss.parameters["x"]._parameter_type = ParameterType.FLOAT
with self.assertRaises(ValueError):
self.experiment.search_space = bad_type_ss
# Try search space with additional parameters
extra_param_ss = get_search_space()
extra_param_ss.add_parameter(FixedParameter("l", ParameterType.FLOAT, 0.5))
with self.assertRaises(ValueError):
self.experiment.search_space = extra_param_ss
def test_add_search_space_parameters(self) -> None:
new_param = RangeParameter(
name="new_param",
parameter_type=ParameterType.FLOAT,
lower=0.0,
upper=1.0,
)
with self.subTest("Add parameter to experiment with no trials"):
experiment = self.experiment.clone_with(trial_indices=[])
experiment.add_parameters_to_search_space(
parameters=[new_param],
status_quo_values={new_param.name: 0.0},
)
# Verify parameter was added
self.assertIn("new_param", experiment.search_space.parameters)
self.assertEqual(experiment.search_space.parameters["new_param"], new_param)
# Verify backfill value was used as status quo
self.assertIsNotNone(experiment.status_quo)
self.assertIn("new_param", experiment.status_quo.parameters)
self.assertEqual(experiment.status_quo.parameters["new_param"], 0.0)
def test_add_derived_parameter_to_search_space_with_trials(self) -> None:
"""Test adding DerivedParameters to an experiment that has existing trials.
DerivedParameters should not require backfill values since their values
are computed from other parameters.
"""
# Create a simple experiment with an existing RangeParameter "w"
# Clone without status_quo to simplify the test
experiment = self.experiment.clone_with()
experiment._status_quo = None
experiment.new_batch_trial()
# Create a DerivedParameter that depends on existing parameter "w"
# d2 = 2.0 * w + 1.0
derived_param = DerivedParameter(
name="d2",
parameter_type=ParameterType.FLOAT,
expression_str="2.0 * w + 1.0",
)
# Should not raise an error even though trials exist
# because DerivedParameters don't need backfill values
experiment.add_parameters_to_search_space(parameters=[derived_param])
# Verify the DerivedParameter was added
self.assertIn("d2", experiment.search_space.parameters)
self.assertEqual(experiment.search_space.parameters["d2"], derived_param)
# Verify the DerivedParameter value can be computed for existing arms
trial = experiment.trials[0]
for arm in trial.arms:
# Verify "w" exists in the arm parameters
self.assertIn("w", arm.parameters)
w_value = arm.parameters["w"]
# Compute expected derived value
expected_d_value = 2.0 * w_value + 1.0
# The derived parameter value should be computed correctly
self.assertEqual(
derived_param.compute(arm.parameters),
expected_d_value,
)
def test_add_derived_parameter_without_backfill_requires_dependency_exists(
self,
) -> None:
"""Test that adding a DerivedParameter whose dependencies don't exist fails."""
experiment = self.experiment.clone_with()
experiment._status_quo = None
experiment.new_batch_trial()
# Create a DerivedParameter that depends on a non-existent parameter "z"
derived_param = DerivedParameter(
name="d",
parameter_type=ParameterType.FLOAT,
expression_str="2.0 * nonexistent + 1.0",
)
# This should raise an error because the dependency "nonexistent" doesn't exist
# in the search space.
with self.assertRaises(UserInputError):
experiment.add_parameters_to_search_space(parameters=[derived_param])
def test_disable_search_space_parameters(self) -> None:
with self.subTest(
"Test error when trying to disable parameter not in search space"
):
experiment = self.experiment.clone_with()
with self.assertRaises(UserInputError):
experiment.disable_parameters_in_search_space({"nonexistent": 1.0})
with self.subTest("Test error when providing invalid default value"):
experiment = self.experiment.clone_with()
with self.assertRaises(UserInputError):
experiment.disable_parameters_in_search_space({"w": "string_value"})
with self.subTest("Test successfully disabling parameter"):
experiment = self.experiment.clone_with()
experiment.disable_parameters_in_search_space({"w": 2.5})
# Verify parameter was disabled (has default value)
self.assertEqual(experiment.search_space.parameters["w"].default_value, 2.5)
with self.subTest("Test re-enable parameter"):
# Using the same experiment as above
parameter = experiment.search_space.parameters["w"].clone()
parameter._default_value = None
experiment.add_parameters_to_search_space(parameters=[parameter])
# Verify parameter was re-enabled
self.assertIsNone(experiment.search_space.parameters["w"].default_value)
def test_optimization_config_setter(self) -> None:
# Establish current metrics size
self.assertEqual(
len(get_optimization_config().metrics) + 1, len(self.experiment.metrics)
)
# Add optimization config with 1 different metric
opt_config = get_optimization_config()
opt_config.outcome_constraints[0].metric = Metric(name="m3")
self
def test_status_quo_setter(self) -> None:
sq_parameters = self.experiment.status_quo.parameters
# Verify normal update when no trials exist
sq_parameters["w"] = 3.5
self.experiment.status_quo = Arm(sq_parameters)
self.assertEqual(self.experiment.status_quo.parameters["w"], 3.5)
self.assertEqual(self.experiment.status_quo.name, "status_quo_e0")
# Verify all None values
self.experiment.status_quo = Arm(dict.fromkeys(sq_parameters))
self.assertIsNone(self.experiment.status_quo.parameters["w"])
# Switch back to sq with values
self.experiment.status_quo = Arm(sq_parameters)
# Try extra param
sq_parameters["a"] = 4
with self.assertRaises(ValueError):
self.experiment.status_quo = Arm(sq_parameters)
# Try missing param - need to use a copy since we modified sq_parameters earlier
sq_parameters_copy = sq_parameters.copy()
sq_parameters_copy.pop("w", None) # Use pop with default to avoid KeyError
with self.assertRaises(ValueError):
self.experiment.status_quo = Arm(sq_parameters_copy)
# Try wrong type
sq_parameters.pop("a")
sq_parameters["w"] = "hello"
with self.assertRaises(ValueError):
self.experiment.status_quo = Arm(sq_parameters)
# Verify arms_by_signature, arms_by_name contain all three versions of the SQ
self.assertEqual(len(self.experiment.arms_by_signature), 3)
self.assertEqual(len(self.experiment.arms_by_name), 3)
# Try to change status_quo after trials have been created
_ = self.experiment.new_batch_trial(should_add_status_quo_arm=True)
sq_parameters["w"] = 3.7
with self.assertRaises(UnsupportedError) as e:
self.experiment.status_quo = Arm(sq_parameters)
self.assertIn(
"Modifications of status_quo are disabled after trials have been created",
str(e.exception),
)
# Verify status_quo wasn't changed
self.assertEqual(self.experiment.status_quo.parameters["w"], 3.5)
def test_register_arm(self) -> None:
# Create a new arm, register on experiment
parameters = self.experiment.status_quo.parameters
parameters["w"] = 3.5
arm = Arm(name="my_arm_name", parameters=parameters)
self.experiment._register_arm(arm)
self.assertEqual(self.experiment.arms_by_name[arm.name], arm)
self.assertEqual(self.experiment.arms_by_signature[arm.signature], arm)
def test_fetch_and_store_data(self) -> None:
n = 10
exp = self._setup_branin_experiment(n)
batch = exp.trials[0]
batch.mark_completed()
self.assertEqual(exp.completed_trials, [batch])
# Test fetch data
batch_data = batch.fetch_data()
self.assertEqual(len(batch_data.df), n)
exp_data = exp.fetch_data()
res = exp.fetch_trials_data_results(metrics=[exp.metrics["b"]])
res_one_metric = {k: v["b"] for k, v in res.items()}
exp_data2 = Metric._unwrap_experiment_data(results=res_one_metric)
self.assertEqual(len(exp_data2.df), 4 * n)
self.assertEqual(len(exp_data.df), 4 * n)
self.assertEqual(len(exp.arms_by_name), 4 * n)
# Verify that `metrics` kwarg to `experiment.fetch_data` is respected.
exp.add_tracking_metric(
Metric(
name="not_yet_on_experiment",
signature_override="not_yet_on_experiment_signature",
)
)
exp.attach_data(
Data(
df=pd.DataFrame.from_records(
[
{
"arm_name": "0_0",
"metric_name": "not_yet_on_experiment",
"mean": 3,
"sem": 0,
"trial_index": 0,
"metric_signature": "not_yet_on_experiment_signature",
}
]
)
)
)
self.assertEqual(
set(
exp.fetch_data(
metrics=[
Metric(
name="not_yet_on_experiment",
signature_override="not_yet_on_experiment_signature",
)
]
)
.df["metric_name"]
.values
),
{"not_yet_on_experiment"},
)
self.assertEqual(
set(
exp.fetch_data(
metrics=[
Metric(
name="not_yet_on_experiment",
signature_override="not_yet_on_experiment_signature",
)
]
)
.df["metric_signature"]
.values
),
{"not_yet_on_experiment_signature"},
)
# Verify data lookup includes trials attached from `fetch_data`.
self.assertEqual(len(exp.lookup_data(trial_indices={1}).df), 30)
# Test local storage
exp.attach_data(batch_data)
exp.attach_data(exp_data)
# data for 2 trials
self.assertEqual(len(exp.lookup_data().trial_indices), 2)
# The data from `exp_data` completely replaces the data from
# `batch_data` because both are for metric "b", and `batch_data` covers a
# subset of the arms and trials. There is an additional observation from
# "not_yet_on_experiment".
self.assertEqual(len(exp.lookup_data().df), len(exp_data.df) + 1)
# Test retrieving original batch 0 data
trial_0_df = exp.lookup_data(trial_indices={0}).df
self.assertEqual((trial_0_df["metric_name"] == "b").sum(), n)
self.assertEqual(
(trial_0_df["metric_name"] == "not_yet_on_experiment").sum(), 1
)
# Test retrieving full exp data
df = exp.lookup_data().df
self.assertEqual((df["metric_name"] == "b").sum(), 4 * n)
self.assertEqual((df["metric_name"] == "not_yet_on_experiment").sum(), 1)
# Make sure that lookup_data() + filtering on trial index = 0 gives the
# same result as `lookup_data_for_trial(0)`
self.assertEqual(
(df["trial_index"] == 0).sum(),
len(exp.lookup_data(trial_indices={0}).df),
)
new_data = Data(
df=pd.DataFrame.from_records(
[
{
"arm_name": "0_0",
# but now it is
"metric_name": "not_yet_on_experiment",
"mean": 3,
"sem": 0,
"trial_index": 0,
"metric_signature": "not_yet_on_experiment_signature",
},
{
"arm_name": "0_0",
"metric_name": "z",
"mean": 3,
"sem": 0,
"trial_index": 0,
"metric_signature": "z",
},
]
)
)
exp.attach_data(new_data)
self.assertIn("z", exp.lookup_data().df["metric_name"].tolist())
# Verify we don't get the data if the trial is abandoned
batch._status = TrialStatus.ABANDONED
self.assertEqual(len(batch.fetch_data().df), 0)
self.assertEqual(len(exp.fetch_data().df), 3 * n)
# Verify we do get the stored data if there are an unimplemented metrics.
# Remove attached data for nonexistent metric.
exp.data = Data(df=exp.data.full_df.loc[lambda x: x["metric_name"] != "z"])
# Remove implemented metric that is `available_while_running`
# (and therefore not pulled from cache).
exp.remove_tracking_metric(metric_name="b")
exp.add_tracking_metric(Metric(name="b")) # Add unimplemented metric.
batch._status = TrialStatus.COMPLETED
# Data should be getting looked up now.
looked_up_data = exp.lookup_data()
looked_up_df = looked_up_data.full_df
self.assertFalse((looked_up_df["metric_name"] == "z").any())
self.assertTrue(
batch.fetch_data()
.full_df.sort_values(["arm_name", "metric_name"], ignore_index=True)
.equals(
looked_up_df.loc[lambda x: (x["trial_index"] == 0)].sort_values(
["arm_name", "metric_name"], ignore_index=True
)
)
)
metrics_in_data = set(batch.fetch_data().df["metric_name"].values)
# Data for metric "z" should no longer be present since we removed it.
self.assertEqual(metrics_in_data, {"b", "not_yet_on_experiment"})
# Verify that `metrics` kwarg to `experiment.fetch_data` is respected
fetched_data = exp.fetch_data(metrics=[Metric(name="not_on_experiment")])
# when pulling looked-up data.
self.assertEqual(fetched_data, Data())
def test_bulk_configure_metrics(self) -> None:
exp = get_branin_experiment_with_multi_objective()
exp.add_tracking_metric(
metric=Hartmann6Metric(name="no update", param_names=["x"])
)
# apply update to metric properties manually
inital_metrics = exp.metrics
for metric in inital_metrics.values():
if isinstance(metric, BraninMetric):
metric.param_names = ["foo", "bar"]
with self.subTest("updates both brannin metrics, but not hartmann"):
exp.bulk_configure_metrics_of_class(
metric_class=BraninMetric,
attributes_to_update={"param_names": ["foo", "bar"]},
)
self.assertEqual(inital_metrics, exp.metrics)
# double check the change is populated in opt config too
inital_metrics.pop("no update")
self.assertIsNotNone(exp.optimization_config)
self.assertEqual(inital_metrics, exp.optimization_config.metrics)
with self.subTest("parameter not in initialization"):
with self.assertRaisesRegex(
UserInputError, "does not contain the requested "
):
exp.bulk_configure_metrics_of_class(
metric_class=BraninMetric,
attributes_to_update={"fake": 1},
)
with self.subTest("no metrics to update"):
with self.assertRaisesRegex(UserInputError, "No metrics of class"):
exp.bulk_configure_metrics_of_class(
metric_class=NoisyFunctionMetric,
attributes_to_update={"fake": 1},
)
def test_empty_metrics(self) -> None:
empty_experiment = Experiment(
name="test_experiment", search_space=get_search_space()
)
self.assertEqual(empty_experiment.num_trials, 0)
with self.assertRaises(ValueError):
empty_experiment.fetch_data()
batch = empty_experiment.new_batch_trial()
batch.mark_running(no_runner_required=True)
self.assertEqual(empty_experiment.num_trials, 1)
with self.assertRaises(ValueError):
batch.fetch_data()
empty_experiment.add_tracking_metric(Metric(name="ax_test_metric"))
self.assertTrue(empty_experiment.fetch_data().df.empty)
empty_experiment.attach_data(get_data())
batch.mark_completed()
self.assertFalse(empty_experiment.fetch_data().df.empty)
def test_num_arms_no_deduplication(self) -> None:
exp = Experiment(name="test_experiment", search_space=get_search_space())
arm = get_arm()
exp.new_batch_trial().add_arm(arm)
trial = exp.new_batch_trial().add_arm(arm)
self.assertEqual(exp.sum_trial_sizes, 2)
self.assertEqual(len(exp.arms_by_name), 1)
trial.mark_arm_abandoned(trial.arms[0].name)
self.assertEqual(exp.num_abandoned_arms, 1)
def test_experiment_without_name(self) -> None:
exp = Experiment(
search_space=get_branin_search_space(),
tracking_metrics=[BraninMetric(name="b", param_names=["x1", "x2"])],
runner=SyntheticRunner(),
)
self.assertEqual("Experiment(None)", str(exp))
batch = exp.new_batch_trial()
batch.add_arms_and_weights(arms=get_branin_arms(n=5, seed=0))
batch.run()
self.assertEqual(batch.run_metadata, {"name": "0"})
def test_experiment_runner(self) -> None:
original_runner = SyntheticRunner()
self.experiment.runner = original_runner
batch = self.experiment.new_batch_trial()
batch.run()
self.assertEqual(batch.runner, original_runner)
# Simulate a failed run/deployment, in which the runner is attached
# but the actual run fails, and so the trial remains CANDIDATE.
candidate_batch = self.experiment.new_batch_trial()
candidate_batch.run()
candidate_batch._status = TrialStatus.CANDIDATE
self.assertEqual(self.experiment.trials_expecting_data, [batch])
tbs = self.experiment.trials_by_status # All statuses should be present
self.assertEqual(len(tbs), len(TrialStatus))
self.assertEqual(tbs[TrialStatus.RUNNING], [batch])
self.assertEqual(tbs[TrialStatus.CANDIDATE], [candidate_batch])
tibs = self.experiment.trial_indices_by_status
self.assertEqual(len(tibs), len(TrialStatus))
self.assertEqual(tibs[TrialStatus.RUNNING], {0})
self.assertEqual(tibs[TrialStatus.CANDIDATE], {1})
identifier = {"new_runner": True}
# pyre-fixme[6]: For 1st param expected `Optional[str]` but got `Dict[str,
# bool]`.
new_runner = SyntheticRunner(dummy_metadata=identifier)
# Don't update trials that have been run.
self.assertEqual(batch.runner, original_runner)
# Update default runner
self.experiment.runner = new_runner
self.assertEqual(self.experiment.runner, new_runner)
# Update candidate trial runners.
self.assertEqual(self.experiment.trials[1].runner, new_runner)
def test_attach(self) -> None:
"""
Test that
- calling `experiment.attach_data` with `overwrite_existing_data` or
`combine_with_last_data` provided produces a warning that this
option is deprecated.
- calling `experiment.attach_data` with any other unsupported arguments
produces a ValueError
- `experiment.attach_data` results in combining old dfs with new without
loss of trial-arm-metric[-step] observations and deduplicating in
favor of new
"""
exp = Experiment(
name="test",
search_space=get_branin_search_space(),
optimization_config=OptimizationConfig(
objective=Objective(metric=Metric(name="a", lower_is_better=True))
),
tracking_metrics=[Metric(name="b"), Metric(name="c")],
runner=SyntheticRunner(),
)
# Add data
arm_name = "0_0"
trial_index = 0
orig_b_value = 1.0
df1 = pd.DataFrame(
{
"trial_index": [trial_index, trial_index],
"arm_name": [arm_name, arm_name],
"metric_name": ["a", "b"],
"metric_signature": ["a", "b"],
"mean": [orig_b_value, 2.0],
"sem": [0.1, 0.2],
}
)
data1 = Data(df=df1)
with self.assertRaisesRegex(ValueError, "Cannot attach data for trials"):
exp.attach_data(data=data1)
exp.attach_trial(parameterizations=[{"x1": 0.0, "x2": 1.0}])
with self.subTest("args deprecated"):
deprecation_msg = "is deprecated"
for kwargs in [
{"overwrite_existing_data": True},
{"combine_with_last_data": True},
{"overwrite_existing_data": True, "combine_with_last_data": False},
]:
with self.assertWarnsRegex(
DeprecationWarning, expected_regex=deprecation_msg, msg=kwargs
):
exp.attach_data(data1, **kwargs)
with self.subTest("Unexpected arguments"):
with self.assertRaisesRegex(ValueError, "Unexpected arguments"):
exp.attach_data(data=data1, foo="bar")
# (1) use a fresh experiment with no data on it and with three metrics
exp.attach_data(data1)
self.assertIn(trial_index, exp.data.trial_indices)
new_b_value = 3.0
# b is updated, c is new
df2 = pd.DataFrame(
{
"trial_index": [trial_index, trial_index],
"arm_name": [arm_name, arm_name],
"metric_name": ["b", "c"],
"metric_signature": ["b", "c"],
"mean": [new_b_value, 4.0],
"sem": [0.3, 0.4],
}
)
data2 = Data(df=df2)
exp.attach_data(data2, combine_with_last_data=True)
self.assertIn(trial_index, exp.data.trial_indices)
# (5) assert that `exp._data_by_trial[0]`'s one value is a Data with
# metrics a, b, and c, containing the more recent value for metric b.
attached_df = exp.data.filter(trial_indices=[trial_index]).full_df
# All three metrics are present on the new data
self.assertEqual(set(attached_df["metric_name"]), {"a", "b", "c"})
# Check that metric b has the updated value (3.0)
b_value = attached_df.loc[attached_df["metric_name"] == "b", "mean"].item()
self.assertEqual(b_value, new_b_value)
# Attach some Data with has_step_column=True when we didn't previously
# have such data. This is an important case as Metrics transition to
# MapMetrics
map_data = Data(df=df2.assign(step=0))
exp.attach_data(data=map_data)
data = exp.lookup_data(trial_indices=[0])
self.assertIsInstance(data, Data)
self.assertTrue(data.has_step_column)
# Metric "a" only from first fetch, metrics "b" and "c" with step NaN
# from second fetch, metrics "b" and "c" with step 0.0 from third fetch
self.assertEqual(len(data.full_df), 5)
self.assertEqual(data.full_df["step"].isnull().sum(), 3)
self.assertEqual((data.full_df["step"] == 0).sum(), 2)
with self.subTest("Mix of Data with and without step columns gives NaNs"):
exp = get_branin_experiment_with_timestamp_map_metric(
with_trials_and_data=True,
)
self.assertEqual(exp.lookup_data().full_df["step"].isna().sum(), 2)
def test_lookup_data(self) -> None:
exp = Experiment(
name="test",
search_space=get_branin_search_space(),
optimization_config=OptimizationConfig(
objective=Objective(metric=Metric(name="a", lower_is_better=True))
),
tracking_metrics=[Metric(name="b"), Metric(name="c")],
runner=SyntheticRunner(),
)
exp.attach_trial(parameterizations=[{"x1": 0.0, "x2": 0.0}])
exp.attach_trial(parameterizations=[{"x1": 0.0, "x2": 0.0}])
# Add a trial
attached_df = pd.DataFrame(
{
"trial_index": [0, 1],
"arm_name": ["0_0", "0_0"],
"metric_name": ["a", "b"],
"metric_signature": ["a", "b"],
"mean": [1.0, 2.0],
"sem": [0.1, 0.2],
}
)
exp.attach_data(data=Data(df=attached_df))
with self.subTest("No trial indices"):
looked_up = exp.lookup_data()
self.assertIsInstance(looked_up, Data)
self.assertEqual(set(looked_up.full_df["trial_index"]), {0, 1})
with self.subTest("One trial index"):
looked_up = exp.lookup_data(trial_indices=[0])
self.assertIsInstance(looked_up, Data)
self.assertEqual(set(looked_up.full_df["trial_index"]), {0})
with self.subTest("Empty trial indices"):
looked_up = exp.lookup_data(trial_indices=[])
self.assertIsInstance(looked_up, Data)
self.assertTrue(looked_up.empty)
def test_attach_and_sort_data(self) -> None:
n = 4
exp = self._setup_branin_experiment(n)
batch = exp.trials[0]