示例#1
0
    def test_validate_early_stopping_strategy(self):
        class DummyEarlyStoppingStrategy(BaseEarlyStoppingStrategy):
            def should_stop_trials_early(
                self,
                trial_indices: Set[int],
                experiment: Experiment,
                **kwargs: Dict[str, Any],
            ) -> Set[int]:
                return {}

        with patch(
                f"{BraninMetric.__module__}.BraninMetric.is_available_while_running",
                return_value=False,
        ), self.assertRaises(ValueError):
            Scheduler(
                experiment=self.branin_experiment,
                generation_strategy=self.sobol_GPEI_GS,
                options=SchedulerOptions(
                    early_stopping_strategy=DummyEarlyStoppingStrategy()),
            )

        # should not error
        Scheduler(
            experiment=self.branin_experiment,
            generation_strategy=self.sobol_GPEI_GS,
            options=SchedulerOptions(
                early_stopping_strategy=DummyEarlyStoppingStrategy()),
        )
示例#2
0
 def test_init(self):
     with self.assertRaisesRegex(UnsupportedError,
                                 ".* metrics .* implemented fetching"):
         scheduler = BareBonesTestScheduler(
             experiment=self.branin_experiment_no_impl_metrics,
             generation_strategy=self.sobol_GPEI_GS,
             options=SchedulerOptions(total_trials=10),
         )
     scheduler = BareBonesTestScheduler(
         experiment=self.branin_experiment,
         generation_strategy=self.sobol_GPEI_GS,
         options=SchedulerOptions(
             total_trials=0,
             tolerated_trial_failure_rate=0.2,
             init_seconds_between_polls=10,
         ),
     )
     self.assertEqual(scheduler.experiment, self.branin_experiment)
     self.assertEqual(scheduler.generation_strategy, self.sobol_GPEI_GS)
     self.assertEqual(scheduler.options.total_trials, 0)
     self.assertEqual(scheduler.options.tolerated_trial_failure_rate, 0.2)
     self.assertEqual(scheduler.options.init_seconds_between_polls, 10)
     self.assertIsNone(scheduler._latest_optimization_start_timestamp)
     for status_prop in ExperimentStatusProperties:
         self.assertEqual(
             scheduler.experiment._properties[status_prop.value], [])
     scheduler.run_all_trials()  # Runs no trials since total trials is 0.
     # `_latest_optimization_start_timestamp` should be set now.
     self.assertLessEqual(
         scheduler._latest_optimization_start_timestamp,
         current_timestamp_in_millis(),
     )
示例#3
0
    def test_run_trials_in_batches(self):
        with self.assertRaisesRegex(UnsupportedError,
                                    "only if `poll_available_capacity`"):
            scheduler = BareBonesTestScheduler(
                experiment=self.branin_experiment,  # Has runner and metrics.
                generation_strategy=self.two_sobol_steps_GS,
                options=SchedulerOptions(
                    init_seconds_between_polls=0,
                    run_trials_in_batches=True,
                ),
            )
            scheduler.run_n_trials(max_trials=3)

        class PollAvailableCapacityScheduler(BareBonesTestScheduler):
            def poll_available_capacity(self):
                return 2

        scheduler = PollAvailableCapacityScheduler(
            experiment=self.branin_experiment,  # Has runner and metrics.
            generation_strategy=self.two_sobol_steps_GS,
            options=SchedulerOptions(
                init_seconds_between_polls=0,
                run_trials_in_batches=True,
            ),
        )

        with patch.object(scheduler,
                          "run_trials",
                          side_effect=scheduler.run_trials) as mock_run_trials:
            scheduler.run_n_trials(max_trials=3)
            # Trials should be dispatched twice, as total of three trials
            # should be dispatched but capacity is limited to 2.
            self.assertEqual(mock_run_trials.call_count, ceil(3 / 2))
示例#4
0
 def test_repr(self):
     scheduler = Scheduler(
         experiment=self.branin_experiment,
         generation_strategy=self.sobol_GPEI_GS,
         options=SchedulerOptions(
             total_trials=0,
             tolerated_trial_failure_rate=0.2,
             init_seconds_between_polls=10,
         ),
     )
     self.assertEqual(
         f"{scheduler}",
         ("Scheduler(experiment=Experiment(branin_test_experiment), "
          "generation_strategy=GenerationStrategy(name='Sobol+GPEI', "
          "steps=[Sobol for 5 trials, GPEI for subsequent trials]), "
          "options=SchedulerOptions(max_pending_trials=10, "
          "trial_type=<class 'ax.core.trial.Trial'>, "
          "total_trials=0, tolerated_trial_failure_rate=0.2, "
          "min_failed_trials_for_failure_rate_check=5, log_filepath=None, "
          "logging_level=20, ttl_seconds_for_trials=None, init_seconds_between_"
          "polls=10, min_seconds_before_poll=1.0, seconds_between_polls_backoff_"
          "factor=1.5, run_trials_in_batches=False, "
          "debug_log_run_metadata=False, early_stopping_strategy=None, "
          "suppress_storage_errors_after_retries=False))"),
     )
示例#5
0
 def test_run_trials_and_yield_results_with_early_stopper(self):
     total_trials = 3
     self.branin_experiment.runner = InfinitePollRunner()
     scheduler = EarlyStopsInsteadOfNormalCompletionScheduler(
         experiment=self.branin_experiment,  # Has runner and metrics.
         generation_strategy=self.two_sobol_steps_GS,
         options=SchedulerOptions(init_seconds_between_polls=0.1, ),
     )
     # All trials should be marked complete after one run.
     with patch.object(
             scheduler,
             "should_stop_trials_early",
             wraps=scheduler.should_stop_trials_early,
     ) as mock_should_stop_trials_early, patch.object(
             scheduler, "stop_trial_runs",
             return_value=None) as mock_stop_trial_runs:
         res_list = list(
             scheduler.run_trials_and_yield_results(
                 max_trials=total_trials))
         # Two steps complete the experiment given parallelism.
         expected_num_polls = 2
         self.assertEqual(len(res_list), expected_num_polls + 1)
         # Both trials in first batch of parallelism will be early stopped
         self.assertEqual(len(res_list[0]["trials_early_stopped_so_far"]),
                          2)
         # Third trial in second batch of parallelism will be early stopped
         self.assertEqual(len(res_list[1]["trials_early_stopped_so_far"]),
                          3)
         self.assertEqual(mock_should_stop_trials_early.call_count,
                          expected_num_polls)
         self.assertEqual(mock_stop_trial_runs.call_count,
                          expected_num_polls)
示例#6
0
    def test_stop_at_MAX_SECONDS_BETWEEN_POLLS(self):
        class InfinitePollScheduler(BareBonesTestScheduler):
            def poll_trial_status(self):
                return {}

        scheduler = InfinitePollScheduler(
            experiment=self.branin_experiment,  # Has runner and metrics.
            generation_strategy=self.two_sobol_steps_GS,
            options=SchedulerOptions(
                total_trials=8,
                init_seconds_between_polls=
                1,  # No wait between polls so test is fast.
            ),
        )
        with patch.object(scheduler,
                          "wait_for_completed_trials_and_report_results",
                          return_value=None) as mock_await_trials:
            scheduler.run_all_trials(timeout_hours=1 / 60 /
                                     15)  # 4 second timeout.
            # We should be calling `wait_for_completed_trials_and_report_results`
            # N = total runtime / `MAX_SECONDS_BETWEEN_POLLS` times.
            self.assertEqual(
                len(mock_await_trials.call_args),
                2,  # MAX_SECONDS_BETWEEN_POLLS as patched in decorator
            )
示例#7
0
    def test_get_best_trial(self):
        scheduler = Scheduler(
            experiment=self.branin_experiment,  # Has runner and metrics.
            generation_strategy=self.two_sobol_steps_GS,
            options=SchedulerOptions(
                init_seconds_between_polls=
                0.1,  # Short between polls so test is fast.
            ),
        )

        self.assertIsNone(scheduler.get_best_parameters())

        scheduler.run_n_trials(max_trials=1)

        trial, params, _arm = scheduler.get_best_trial()
        just_params, _just_arm = scheduler.get_best_parameters()
        just_params_unmodeled, _just_arm_unmodled = scheduler.get_best_parameters(
            use_model_predictions=False)
        with self.assertRaisesRegex(NotImplementedError,
                                    "Please use `get_best_parameters`"):
            scheduler.get_pareto_optimal_parameters()

        self.assertEqual(trial, 0)
        self.assertIn("x1", params)
        self.assertIn("x2", params)

        self.assertEqual(params, just_params)
        self.assertEqual(params, just_params_unmodeled)
示例#8
0
    def test_run_trials_and_yield_results_with_early_stopper(self):
        class EarlyStopsInsteadOfNormalCompletionScheduler(
                BareBonesTestScheduler):
            def poll_trial_status(self):
                return {}

            def should_stop_trials_early(self, trial_indices: Set[int]):
                return {TrialStatus.COMPLETED: trial_indices}

        total_trials = 3
        scheduler = EarlyStopsInsteadOfNormalCompletionScheduler(
            experiment=self.branin_experiment,  # Has runner and metrics.
            generation_strategy=self.two_sobol_steps_GS,
            options=SchedulerOptions(init_seconds_between_polls=0.1, ),
        )
        # All trials should be marked complete after one run.
        with patch.object(
                scheduler,
                "should_stop_trials_early",
                wraps=scheduler.should_stop_trials_early,
        ) as mock_should_stop_trials_early:
            res_list = list(
                scheduler.run_trials_and_yield_results(
                    max_trials=total_trials))
            # Two steps complete the experiment given parallelism.
            expected_num_polls = 2
            self.assertEqual(len(res_list), expected_num_polls)
            self.assertIsInstance(res_list, list)
            self.assertDictEqual(
                res_list[0],
                {"trials_completed_so_far": set(range(total_trials))})
            self.assertEqual(mock_should_stop_trials_early.call_count,
                             expected_num_polls)
示例#9
0
 def test_run_preattached_trials_only(self):
     # assert that pre-attached trials run when max_trials = number of
     # pre-attached trials
     scheduler = Scheduler(
         experiment=self.branin_experiment,  # Has runner and metrics.
         generation_strategy=self.two_sobol_steps_GS,
         options=SchedulerOptions(
             init_seconds_between_polls=
             0.1,  # Short between polls so test is fast.
         ),
     )
     trial = scheduler.experiment.new_trial()
     parameter_dict = {"x1": 5, "x2": 5}
     trial.add_arm(Arm(parameters=parameter_dict))
     with self.assertRaisesRegex(
             UserInputError,
             "number of pre-attached candidate trials .* is greater than"):
         scheduler.run_n_trials(max_trials=0)
     scheduler.run_n_trials(max_trials=1)
     self.assertEqual(len(scheduler.experiment.trials), 1)
     self.assertDictEqual(scheduler.experiment.trials[0].arm.parameters,
                          parameter_dict)
     self.assertTrue(  # Make sure all trials got to complete.
         all(t.completed_successfully
             for t in scheduler.experiment.trials.values()))
示例#10
0
    def test_validate_early_stopping_strategy(self):
        with patch(
                f"{BraninMetric.__module__}.BraninMetric.is_available_while_running",
                return_value=False,
        ), self.assertRaises(ValueError):
            Scheduler(
                experiment=self.branin_experiment,
                generation_strategy=self.sobol_GPEI_GS,
                options=SchedulerOptions(
                    early_stopping_strategy=DummyEarlyStoppingStrategy()),
            )

        with patch.object(
                OptimizationConfig, "is_moo_problem", return_value=True
        ), self.assertRaisesRegex(
                UnsupportedError,
                "Early stopping is not supported on multi-objective problems",
        ):
            Scheduler(
                experiment=self.branin_experiment,
                generation_strategy=self.sobol_GPEI_GS,
                options=SchedulerOptions(
                    early_stopping_strategy=DummyEarlyStoppingStrategy()),
            )

        with patch(
                f"{Scheduler.__module__}.len",
                return_value=1,
        ), self.assertRaisesRegex(
                UnsupportedError,
                "Early stopping is not supported on problems with outcome constraints.",
        ):
            Scheduler(
                experiment=self.branin_experiment,
                generation_strategy=self.sobol_GPEI_GS,
                options=SchedulerOptions(
                    early_stopping_strategy=DummyEarlyStoppingStrategy()),
            )

        # should not error
        Scheduler(
            experiment=self.branin_experiment,
            generation_strategy=self.sobol_GPEI_GS,
            options=SchedulerOptions(
                early_stopping_strategy=DummyEarlyStoppingStrategy()),
        )
示例#11
0
    def test_failure_rate(self):
        class SchedulerWithFrequentFailedTrials(TestScheduler):

            poll_failed_next_time = True

            def poll_trial_status(self) -> Dict[TrialStatus, Set[int]]:
                running = [t.index for t in self.running_trials]
                status = (TrialStatus.FAILED if self.poll_failed_next_time else
                          TrialStatus.COMPLETED)
                # Poll different status next time.
                self.poll_failed_next_time = not self.poll_failed_next_time
                return {status: {running[randint(0, len(running) - 1)]}}

        scheduler = SchedulerWithFrequentFailedTrials(
            experiment=self.branin_experiment,
            generation_strategy=self.sobol_GS_no_parallelism,
            options=SchedulerOptions(
                total_trials=8,
                tolerated_trial_failure_rate=0.5,
                init_seconds_between_polls=
                0,  # No wait between polls so test is fast.
            ),
        )
        scheduler.run_all_trials()
        # Trials will have statuses: 0, 2, 4 - FAILED, 1, 3 - COMPLETED. Failure rate
        # is 0.5, and we start checking failure rate after first 3 trials.
        # Therefore, failure rate should be exceeded after trial #4.
        self.assertEqual(len(scheduler.experiment.trials), 5)

        # If we set a slightly lower failure rate, it will be reached after 4 trials.
        num_preexisting_trials = len(scheduler.experiment.trials)
        scheduler = SchedulerWithFrequentFailedTrials(
            experiment=self.branin_experiment,
            generation_strategy=self.sobol_GS_no_parallelism,
            options=SchedulerOptions(
                total_trials=8,
                tolerated_trial_failure_rate=0.49,
                init_seconds_between_polls=
                0,  # No wait between polls so test is fast.
            ),
        )
        self.assertEqual(scheduler._num_preexisting_trials,
                         num_preexisting_trials)
        scheduler.run_all_trials()
        self.assertEqual(len(scheduler.experiment.trials),
                         num_preexisting_trials + 4)
示例#12
0
 def test_run_multi_arm_generator_run_error(self, mock_gen):
     scheduler = TestScheduler(
         experiment=self.branin_experiment,
         generation_strategy=self.sobol_GPEI_GS,
         options=SchedulerOptions(total_trials=1),
     )
     with self.assertRaisesRegex(SchedulerInternalError, ".* only one was expected"):
         scheduler.run_all_trials()
示例#13
0
    def test_scheduler_with_odd_index_early_stopping_strategy(self):
        total_trials = 3

        class OddIndexEarlyStoppingStrategy(BaseEarlyStoppingStrategy):
            # Trials with odd indices will be early stopped
            # Thus, with 3 total trials, trial #1 will be early stopped
            def should_stop_trials_early(
                self,
                trial_indices: Set[int],
                experiment: Experiment,
                **kwargs: Dict[str, Any],
            ) -> Dict[int, Optional[str]]:
                # Make sure that we can lookup data for the trial,
                # even though we won't use it in this dummy strategy
                data = experiment.lookup_data(trial_indices=trial_indices)
                if data.df.empty:
                    raise Exception(
                        f"No data found for trials {trial_indices}; "
                        "can't determine whether or not to stop early."
                    )
                return {idx: None for idx in trial_indices if idx % 2 == 1}

        class SchedulerWithEarlyStoppingStrategy(BareBonesTestScheduler):
            poll_trial_status_count = 0

            def poll_trial_status(self):
                # In the first step, don't complete any trials
                # Trial #1 will be early stopped
                if self.poll_trial_status_count == 0:
                    self.poll_trial_status_count += 1
                    return {}

                # In the second step, complete trials 0 and 2
                self.poll_trial_status_count += 1
                return {TrialStatus.COMPLETED: {0, 2}}

        scheduler = SchedulerWithEarlyStoppingStrategy(
            experiment=self.branin_experiment,
            generation_strategy=self.two_sobol_steps_GS,
            options=SchedulerOptions(
                init_seconds_between_polls=0.1,
                early_stopping_strategy=OddIndexEarlyStoppingStrategy(),
            ),
        )
        with patch.object(
            scheduler, "stop_trial_runs", return_value=None
        ) as mock_stop_trial_runs:
            res_list = list(
                scheduler.run_trials_and_yield_results(max_trials=total_trials)
            )
            expected_num_steps = 2
            self.assertEqual(len(res_list), expected_num_steps + 1)
            # Trial #1 early stopped in first step
            self.assertEqual(res_list[0]["trials_early_stopped_so_far"], {1})
            # All trials completed by end of second step
            self.assertEqual(res_list[1]["trials_early_stopped_so_far"], {1})
            self.assertEqual(res_list[1]["trials_completed_so_far"], {0, 2})
            self.assertEqual(mock_stop_trial_runs.call_count, expected_num_steps)
示例#14
0
 def test_base_report_results(self):
     self.branin_experiment.runner = NoReportResultsRunner()
     scheduler = Scheduler(
         experiment=self.branin_experiment,  # Has runner and metrics.
         generation_strategy=self.two_sobol_steps_GS,
         options=SchedulerOptions(init_seconds_between_polls=0, ),
     )
     self.assertEqual(scheduler.run_n_trials(max_trials=3),
                      OptimizationResult())
示例#15
0
 def test_validate_runners_if_required(self):
     # `BareBonesTestScheduler` does not have runner and metrics, so it cannot
     # run on experiment that does not specify those (or specifies base Metric,
     # which do not implement data-fetching logic).
     scheduler = BareBonesTestScheduler(
         experiment=self.branin_experiment,
         generation_strategy=self.sobol_GPEI_GS,
         options=SchedulerOptions(total_trials=10),
     )
     self.branin_experiment.runner = None
     with self.assertRaisesRegex(NotImplementedError, ".* runner is required"):
         scheduler.run_all_trials()
示例#16
0
 def test_optimization_complete(self, _):
     # With runners & metrics, `BareBonesTestScheduler.run_all_trials` should run.
     scheduler = BareBonesTestScheduler(
         experiment=self.branin_experiment,  # Has runner and metrics.
         generation_strategy=self.two_sobol_steps_GS,
         options=SchedulerOptions(
             init_seconds_between_polls=0.1,  # Short between polls so test is fast.
         ),
     )
     scheduler.run_n_trials(max_trials=1)
     # no trials should run if _gen_multiple throws an OptimizationComplete error
     self.assertEqual(len(scheduler.experiment.trials), 0)
示例#17
0
 def test_retries(self):
     # Check that retries will be performed for a retriable error.
     self.branin_experiment.runner = BrokenRunnerRuntimeError()
     scheduler = Scheduler(
         experiment=self.branin_experiment,
         generation_strategy=self.two_sobol_steps_GS,
         options=SchedulerOptions(total_trials=1),
     )
     # Should raise after 3 retries.
     with self.assertRaisesRegex(RuntimeError, ".* testing .*"):
         scheduler.run_all_trials()
         self.assertEqual(scheduler.run_trial_call_count, 3)
示例#18
0
    def test_failure_rate(self):
        class SchedulerWithFrequentFailedTrials(TestScheduler):

            poll_failed_next_time = True

            def poll_trial_status(self) -> Dict[TrialStatus, Set[int]]:
                running = [t.index for t in self.running_trials]
                status = (
                    TrialStatus.FAILED
                    if self.poll_failed_next_time
                    else TrialStatus.COMPLETED
                )
                # Poll different status next time.
                self.poll_failed_next_time = not self.poll_failed_next_time
                return {status: {running[randint(0, len(running) - 1)]}}

        class SchedulerWithAllFailedTrials(TestScheduler):
            def poll_trial_status(self) -> Dict[TrialStatus, Set[int]]:
                running = [t.index for t in self.running_trials]
                return {TrialStatus.FAILED: {running[randint(0, len(running) - 1)]}}

        options = SchedulerOptions(
            total_trials=8,
            tolerated_trial_failure_rate=0.5,
            init_seconds_between_polls=0,  # No wait between polls so test is fast.
            min_failed_trials_for_failure_rate_check=2,
        )

        scheduler = SchedulerWithFrequentFailedTrials(
            experiment=self.branin_experiment,
            generation_strategy=self.sobol_GS_no_parallelism,
            options=options,
        )
        with self.assertRaises(FailureRateExceededError):
            scheduler.run_all_trials()
        # Trials will have statuses: 0, 2 - FAILED, 1 - COMPLETED. Failure rate
        # is 0.5, and so if 2 of the first 3 trials are failed, we can fail
        # immediately.
        self.assertEqual(len(scheduler.experiment.trials), 3)

        # If all trials fail, we can be certain that the sweep will
        # fail after only 2 trials.
        num_preexisting_trials = len(scheduler.experiment.trials)
        scheduler = SchedulerWithAllFailedTrials(
            experiment=self.branin_experiment,
            generation_strategy=self.sobol_GS_no_parallelism,
            options=options,
        )
        self.assertEqual(scheduler._num_preexisting_trials, num_preexisting_trials)
        with self.assertRaises(FailureRateExceededError):
            scheduler.run_all_trials()
        self.assertEqual(len(scheduler.experiment.trials), num_preexisting_trials + 2)
示例#19
0
 def test_retries_nonretriable_error(self):
     # Check that no retries will be performed for `ValueError`, since we
     # exclude it from the retriable errors.
     self.branin_experiment.runner = BrokenRunnerValueError()
     scheduler = Scheduler(
         experiment=self.branin_experiment,
         generation_strategy=self.two_sobol_steps_GS,
         options=SchedulerOptions(total_trials=1),
     )
     # Should raise right away since ValueError is non-retriable.
     with self.assertRaisesRegex(ValueError, ".* testing .*"):
         scheduler.run_all_trials()
         self.assertEqual(scheduler.run_trial_call_count, 1)
示例#20
0
 def test_timeout(self):
     # `TestScheduler` has `run_trial` and `fetch_trial_data` logic, so runner &
     # implemented metrics are not required.
     scheduler = TestScheduler(
         experiment=self.branin_experiment,
         generation_strategy=self.two_sobol_steps_GS,
         options=SchedulerOptions(
             total_trials=8,
             init_seconds_between_polls=0,  # No wait between polls so test is fast.
         ),
     )
     scheduler.run_all_trials(timeout_hours=0)  # Forcing optimization to time out.
     self.assertEqual(len(scheduler.experiment.trials), 0)
     self.assertIn("aborted", scheduler.experiment._properties["run_trials_success"])
示例#21
0
 def test_logging(self):
     with NamedTemporaryFile() as temp_file:
         BareBonesTestScheduler(
             experiment=self.branin_experiment,
             generation_strategy=self.sobol_GPEI_GS,
             options=SchedulerOptions(
                 total_trials=1,
                 init_seconds_between_polls=0,  # No wait bw polls so test is fast.
                 log_filepath=temp_file.name,
             ),
         ).run_all_trials()
         self.assertGreater(os.stat(temp_file.name).st_size, 0)
         self.assertIn("Running trials [0]", str(temp_file.readline()))
         temp_file.close()
示例#22
0
 def test_set_ttl(self):
     scheduler = TestScheduler(
         experiment=self.branin_experiment,
         generation_strategy=self.two_sobol_steps_GS,
         options=SchedulerOptions(
             total_trials=2,
             ttl_seconds_for_trials=1,
             init_seconds_between_polls=0,  # No wait between polls so test is fast.
             min_seconds_before_poll=0.0,
         ),
     )
     scheduler.run_all_trials()
     self.assertTrue(
         all(t.ttl_seconds == 1 for t in scheduler.experiment.trials.values())
     )
示例#23
0
 def test_stop_trial(self):
     # With runners & metrics, `BareBonesTestScheduler.run_all_trials` should run.
     scheduler = BareBonesTestScheduler(
         experiment=self.branin_experiment,  # Has runner and metrics.
         generation_strategy=self.two_sobol_steps_GS,
         options=SchedulerOptions(
             init_seconds_between_polls=0.1,  # Short between polls so test is fast.
         ),
     )
     with patch.object(
         scheduler.experiment.runner, "stop", return_value=None
     ) as mock_runner_stop:
         scheduler.run_n_trials(max_trials=1)
         scheduler.stop_trial_run(scheduler.experiment.trials[0])
         mock_runner_stop.assert_called_once()
示例#24
0
 def test_timeout(self):
     scheduler = Scheduler(
         experiment=self.branin_experiment,
         generation_strategy=self.two_sobol_steps_GS,
         options=SchedulerOptions(
             total_trials=8,
             init_seconds_between_polls=
             0,  # No wait between polls so test is fast.
         ),
     )
     scheduler.run_all_trials(
         timeout_hours=0)  # Forcing optimization to time out.
     self.assertEqual(len(scheduler.experiment.trials), 0)
     self.assertIn("aborted",
                   scheduler.experiment._properties["run_trials_success"])
示例#25
0
 def test_run_preattached_trials_only(self):
     # assert that pre-attached trials run when max_trials = 0
     scheduler = BareBonesTestScheduler(
         experiment=self.branin_experiment,  # Has runner and metrics.
         generation_strategy=self.two_sobol_steps_GS,
         options=SchedulerOptions(
             init_seconds_between_polls=0.1,  # Short between polls so test is fast.
         ),
     )
     trial = scheduler.experiment.new_trial()
     trial.add_arm(Arm(parameters={"x1": 5, "x2": 5}))
     scheduler.run_n_trials(max_trials=0)
     self.assertEqual(len(scheduler.experiment.trials), 1)
     self.assertTrue(  # Make sure all trials got to complete.
         all(t.completed_successfully for t in scheduler.experiment.trials.values())
     )
示例#26
0
 def test_suppress_all_storage_errors(self, mock_save_exp, _):
     init_test_engine_and_session_factory(force_init=True)
     config = SQAConfig()
     encoder = Encoder(config=config)
     decoder = Decoder(config=config)
     db_settings = DBSettings(encoder=encoder, decoder=decoder)
     BareBonesTestScheduler(
         experiment=self.branin_experiment,  # Has runner and metrics.
         generation_strategy=self.two_sobol_steps_GS,
         options=SchedulerOptions(
             init_seconds_between_polls=0.1,  # Short between polls so test is fast.
             suppress_storage_errors_after_retries=True,
         ),
         db_settings=db_settings,
     )
     self.assertEqual(mock_save_exp.call_count, 3)
示例#27
0
 def test_run_trials_and_yield_results(self):
     total_trials = 3
     scheduler = BareBonesTestScheduler(
         experiment=self.branin_experiment,  # Has runner and metrics.
         generation_strategy=self.two_sobol_steps_GS,
         options=SchedulerOptions(init_seconds_between_polls=0, ),
     )
     # `BaseBonesTestScheduler.poll_trial_status` is written to mark one
     # trial as `COMPLETED` at a time, so we should be obtaining results
     # as many times as `total_trials` and yielding from generator after
     # obtaining each new result.
     res_list = list(
         scheduler.run_trials_and_yield_results(max_trials=total_trials))
     self.assertEqual(len(res_list), total_trials)
     self.assertIsInstance(res_list, list)
     self.assertDictEqual(
         res_list[0], {"trials_completed_so_far": set(range(total_trials))})
示例#28
0
 def test_logging_level(self):
     # We don't have any warnings yet, so warning level of logging shouldn't yield
     # any logs as of now.
     with NamedTemporaryFile() as temp_file:
         BareBonesTestScheduler(
             experiment=self.branin_experiment,
             generation_strategy=self.sobol_GPEI_GS,
             options=SchedulerOptions(
                 total_trials=3,
                 init_seconds_between_polls=0,  # No wait bw polls so test is fast.
                 log_filepath=temp_file.name,
                 logging_level=WARNING,
             ),
         ).run_all_trials()
         # Ensure that the temp file remains empty
         self.assertEqual(os.stat(temp_file.name).st_size, 0)
         temp_file.close()
示例#29
0
    def test_base_report_results(self):
        class NoReportResultsScheduler(Scheduler):
            def poll_trial_status(self) -> Dict[TrialStatus, Set[int]]:
                if randint(0, 3) > 0:
                    running = [t.index for t in self.running_trials]
                    return {
                        TrialStatus.COMPLETED: {running[randint(0, len(running) - 1)]}
                    }
                return {}

        scheduler = NoReportResultsScheduler(
            experiment=self.branin_experiment,  # Has runner and metrics.
            generation_strategy=self.two_sobol_steps_GS,
            options=SchedulerOptions(
                init_seconds_between_polls=0,
            ),
        )
        self.assertEqual(scheduler.run_n_trials(max_trials=3), OptimizationResult())
示例#30
0
    def test_retries(self):
        # Check that retries will be performed for a retriable error.
        class BrokenSchedulerRuntimeError(BareBonesTestScheduler):

            run_trial_call_count = 0

            def run_trial(self, trial: BaseTrial) -> Dict[str, Any]:
                self.run_trial_call_count += 1
                raise RuntimeError("Failing for testing purposes.")

        scheduler = BrokenSchedulerRuntimeError(
            experiment=self.branin_experiment,
            generation_strategy=self.two_sobol_steps_GS,
            options=SchedulerOptions(total_trials=1),
        )
        # Should raise after 3 retries.
        with self.assertRaisesRegex(RuntimeError, ".* testing .*"):
            scheduler.run_all_trials()
            self.assertEqual(scheduler.run_trial_call_count, 3)