Automating Orchestration
Previously, we've demonstrated using Ax for ask-tell optimization,
a paradigm in which we "ask" Ax for candidate configurations and "tell" Ax our
observations. This can be effective in many scenerios, and it can be automated through
use of flow control statements like for and while loops. However there are some
situations where it would be beneficial to allow Ax to orchestrate the entire
optimization: deploying trials to external systems, polling their status, and reading
reading their results. This can be common in a number of real world engineering tasks,
including:
- Large scale machine learning experiments running workloads on high-performance computing clusters
- A/B tests conducted using an external experimentation platform
- Materials science optimizations utilizing a self-driving laboratory
Ax's Client can orchestrate automated adaptive experiments like this using its method
run_trials. Users create custom classes which implement Ax's IMetric and IRunner
protocols to handle data fetching and trial deployment respectively. Then, users simply
configure their Client as they would normally and call run_trials; Ax will deploy
trials, fetch data, generate candidates, and repeat as necessary. Ax can manage complex
orchestration tasks including launching multiple trials in parallel while still
respecting a user-defined concurrency limit, and gracefully handling trial failure by
allowing the experiment to continue even if some trials do not complete successfully or
data fetching fails.
In this tutorial we will optimize the Hartmann6 function as before, but we will configure custom Runners and Metrics to mimic an external execution system. The Runner will calculate Hartmann6 with the appropriate parameters, write the result to a file, and tell Ax the trial is ready after 5 seconds. The Metric will find the appropriate file and report the results back to Ax.
Learning Objectives
- Learn when it can be appropriate and/or advantageous to run Ax in a closed-loop
- Configure custom Runners and Metrics, allowing Ax to deploy trials and fetch data automatically
- Understand tradeoffs between parallelism and optimization performance
Prerequisites
- Understanding of adaptive experimentation and Bayesian optimization
- Familiarity with configuring and conducting experiments in Ax
Step 1: Import Necessary Modules
First, ensure you have all the necessary imports:
import os
import time
from typing import Any, Mapping
import numpy as np
from ax.api.client import Client
from ax.api.configs import RangeParameterConfig
from ax.api.protocols.metric import IMetric
from ax.api.protocols.runner import IRunner, TrialStatus
from ax.api.types import TParameterization
Step 2: Defining our custom Runner and Metric
As stated before, we will be creating custom Runner and Metric classes to mimic an external system. Let's start by defining our Hartmann6 function as before.
# Hartmann6 function
def hartmann6(x1, x2, x3, x4, x5, x6):
alpha = np.array([1.0, 1.2, 3.0, 3.2])
A = np.array([
[10, 3, 17, 3.5, 1.7, 8],
[0.05, 10, 17, 0.1, 8, 14],
[3, 3.5, 1.7, 10, 17, 8],
[17, 8, 0.05, 10, 0.1, 14]
])
P = 10**-4 * np.array([
[1312, 1696, 5569, 124, 8283, 5886],
[2329, 4135, 8307, 3736, 1004, 9991],
[2348, 1451, 3522, 2883, 3047, 6650],
[4047, 8828, 8732, 5743, 1091, 381]
])
outer = 0.0
for i in range(4):
inner = 0.0
for j, x in enumerate([x1, x2, x3, x4, x5, x6]):
inner += A[i, j] * (x - P[i, j])**2
outer += alpha[i] * np.exp(-inner)
return -outer
hartmann6(0.1, 0.45, 0.8, 0.25, 0.552, 1.0)
np.float64(-0.4878737485613134)
Next, we will define the MockRunner. The MockRunner requires two methods:
run_trial and poll_trial.
run_trial deploys a trial to the external system with the given parameters. In this
case, we will simply save a file containing the result of a call to the Hartmann6
function.
poll_trial queries the external system to see if the trial has completed, failed, or
if it's still running. In this mock example, we will check to see how many seconds have
elapsed since the run_trial was called and only report a trial as completed once 5
seconds have elapsed.
Runner's may also optionally implement a stop_trial method to terminate a trial's
execution before it has completed. This is necessary for using
early stopping in closed-loop experimentation, but we will skip
this for now.
class MockRunner(IRunner):
def run_trial(
self, trial_index: int, parameterization: TParameterization
) -> dict[str, Any]:
file_name = f"{int(time.time())}.txt"
x1 = parameterization["x1"]
x2 = parameterization["x2"]
x3 = parameterization["x3"]
x4 = parameterization["x4"]
x5 = parameterization["x5"]
x6 = parameterization["x6"]
result = hartmann6(x1, x2, x3, x4, x5, x6)
with open(file_name, "w") as f:
f.write(f"{result}")
return {"file_name": file_name}
def poll_trial(
self, trial_index: int, trial_metadata: Mapping[str, Any]
) -> TrialStatus:
file_name = trial_metadata["file_name"]
time_elapsed = time.time() - int(file_name[:4])
if time_elapsed < 5:
return TrialStatus.RUNNING
return TrialStatus.COMPLETED
It's worthwhile to instantiate your Runner and test it is behaving as expected. Let's
deploy a mock trial by manually calling run_trial and ensuring it creates a file.
runner = MockRunner()
trial_metadata = runner.run_trial(
trial_index=-1,
parameterization={
"x1": 0.1,
"x2": 0.45,
"x3": 0.8,
"x4": 0.25,
"x5": 0.552,
"x6": 1.0,
},
)
os.path.exists(trial_metadata["file_name"])
True
Now, we will implement the Metric. Metrics only need to implement a fetch method,
which returns a progression value (i.e. a step in a timeseries) and an observation
value. Note that the observation can either be a simple float or a (mean, SEM) pair if
the external system can report observed noise.
In this case, we have neither a relevant progression value nor observed noise so we will
simply read the file and report (0, value).
class MockMetric(IMetric):
def fetch(
self,
trial_index: int,
trial_metadata: Mapping[str, Any],
) -> tuple[int, float | tuple[float, float]]:
file_name = trial_metadata["file_name"]
with open(file_name, 'r') as file:
value = float(file.readline())
return (0, value)
Again, let's validate the Metric created above by instantiating it and reporting the value from the file generated during testing of the Runner.
# Note: all Metrics must have a name. This will become relevant when attaching metrics to the Client
hartmann6_metric = MockMetric(name="hartmann6")
hartmann6_metric.fetch(trial_index=-1, trial_metadata=trial_metadata)
(0, -0.4878737485613134)
Step 3: Initialize the Client and Configure the Experiment
Finally, we can initialize the Client and configure the experiment as before. This
will be familiar to readers of the
Getting Started with Ax tutorial -- the only difference is we will
attach the previously defined Runner and Metric by calling configure_runner and
configure_metrics respectively.
Note that when initializing hartmann6_metric we set name=hartmann6, matching the
objective we now set in configure_optimization. The configure_metrics method uses
this name to ensure that data fetched by this Metric is used correctly during the
experiment. Be careful to correctly set the name of the Metric to reflect its use as an
objective or outcome constraint.
client = Client()
# Define six float parameters for the Hartmann6 function
parameters = [
RangeParameterConfig(name=f"x{i + 1}", parameter_type="float", bounds=(0, 1))
for i in range(6)
]
client.configure_experiment(
parameters=parameters,
# The following arguments are only necessary when saving to the DB
name="hartmann6_experiment",
description="Optimization of the Hartmann6 function",
owner="developer",
)
client.configure_optimization(objective="-hartmann6")
client.configure_runner(runner=runner)
client.configure_metrics(metrics=[hartmann6_metric])
Step 5: Run trials
Once the Client has been configured, we can begin running trials.
Internally, Ax uses a class named Scheduler to orchestrate the trial deployment,
polling, data fetching, and candidate generation.

The run_trials method provides users with control over various orchestration settings
as well as the total maximum number of trials to evaluate:
parallelismdefines the maximum number of trials that may be run at once. If your external system supports multiple evaluations in parallel, increasing this number can significantly decrease experimentation time. However, it is important to note that as parallelism increases, optimiztion performance often decreases. This is because adaptive experimentation methods rely on previously observed data for candidate generation -- the more tirals that have been observed prior to generation of a new candidate, the more accurate Ax's model will be for generation of that candidate.tolerated_trial_failure_ratesets the proportion of trials are allowed to fail before Ax raises an Exception. Depending on how expensive a single trial is to evaluate or how unreliable trials are expected to be, the experimenter may want to be notified as soon as a single trial fails or they may not care until more than half the trials are failing. Set this value as is appropriate for your context.initial_seconds_between_pollssets the frequency at which the status of a trial is checked and the results are attempted to be fetched. Set this to be low for trials that are expected to complete quickly or high for trials the are expected to take a long time.
client.run_trials(
max_trials=30,
parallelism=3,
tolerated_trial_failure_rate=0.1,
initial_seconds_between_polls=1,
)
[INFO 05-08 22:38:15] Scheduler: Scheduler requires experiment to have immutable search space and optimization config. Setting property immutable_search_space_and_opt_config to True on experiment.
[INFO 05-08 22:38:15] Scheduler: Running trials [0]...
[INFO 05-08 22:38:16] Scheduler: Running trials [1]...
[INFO 05-08 22:38:17] Scheduler: Running trials [2]...
[INFO 05-08 22:38:18] Scheduler: Retrieved COMPLETED trials: 0 - 2.
[INFO 05-08 22:38:18] Scheduler: Running trials [3]...
[INFO 05-08 22:38:19] Scheduler: Running trials [4]...
[INFO 05-08 22:38:20] Scheduler: Running trials [5]...
[INFO 05-08 22:38:21] Scheduler: Retrieved COMPLETED trials: 3 - 5.
[INFO 05-08 22:38:22] Scheduler: Running trials [6]...
[INFO 05-08 22:38:25] Scheduler: Running trials [7]...
[INFO 05-08 22:38:27] Scheduler: Running trials [8]...
[INFO 05-08 22:38:28] Scheduler: Retrieved COMPLETED trials: 6 - 8.
[INFO 05-08 22:38:31] Scheduler: Running trials [9]...
[INFO 05-08 22:38:34] Scheduler: Running trials [10]...
[INFO 05-08 22:38:40] Scheduler: Running trials [11]...
[INFO 05-08 22:38:41] Scheduler: Retrieved COMPLETED trials: 9 - 11.
[INFO 05-08 22:38:44] Scheduler: Running trials [12]...
[INFO 05-08 22:38:47] Scheduler: Running trials [13]...
[INFO 05-08 22:38:51] Scheduler: Running trials [14]...
[INFO 05-08 22:38:52] Scheduler: Retrieved COMPLETED trials: 12 - 14.
[INFO 05-08 22:38:54] Scheduler: Running trials [15]...
[INFO 05-08 22:38:56] Scheduler: Running trials [16]...
[INFO 05-08 22:38:58] Scheduler: Running trials [17]...
[INFO 05-08 22:38:59] Scheduler: Retrieved COMPLETED trials: 15 - 17.
[INFO 05-08 22:39:03] Scheduler: Running trials [18]...
[INFO 05-08 22:39:07] Scheduler: Running trials [19]...
[INFO 05-08 22:39:11] Scheduler: Running trials [20]...
[INFO 05-08 22:39:12] Scheduler: Retrieved COMPLETED trials: 18 - 20.
[INFO 05-08 22:39:15] Scheduler: Running trials [21]...
[INFO 05-08 22:39:19] Scheduler: Running trials [22]...
[INFO 05-08 22:39:22] Scheduler: Running trials [23]...
[INFO 05-08 22:39:23] Scheduler: Retrieved COMPLETED trials: 21 - 23.
[INFO 05-08 22:39:25] Scheduler: Running trials [24]...
[INFO 05-08 22:39:29] Scheduler: Running trials [25]...
[INFO 05-08 22:39:30] Scheduler: Running trials [26]...
[INFO 05-08 22:39:31] Scheduler: Retrieved COMPLETED trials: 24 - 26.
[INFO 05-08 22:39:34] Scheduler: Running trials [27]...
[INFO 05-08 22:39:39] Scheduler: Running trials [28]...
[INFO 05-08 22:39:42] Scheduler: Running trials [29]...
[INFO 05-08 22:39:43] Scheduler: Retrieved COMPLETED trials: 27 - 29.
Step 6: Analyze Results
As before, Ax can compute the best parameterization observed and produce a number of analyses to help interpret the results of the experiment.
It is also worth noting that the experiment can be resumed at any time using Ax's
storage functionality. When configured to use a SQL databse, the Client saves a
snapshot of itself at various points throughout the call to run_trials, making it
incredibly easy to continue optimization after an unexpected failure. You can learn more
about storage in Ax here.
best_parameters, prediction, index, name = client.get_best_parameterization()
print("Best Parameters:", best_parameters)
print("Prediction (mean, variance):", prediction)
Best Parameters: {'x1': 0.40969082369062376, 'x2': 0.9578901325810083, 'x3': 0.7999735876213786, 'x4': 0.5847710063741918, 'x5': 0.46918227302071247, 'x6': 0.04104230959179908}
Prediction (mean, variance): {'hartmann6': (np.float64(-2.9916773867281474), np.float64(0.0024136261442267437))}
# display=True instructs Ax to sort then render the resulting analyses
cards = client.compute_analyses(display=True)
Parallel Coordinates for hartmann6
The parallel coordinates plot displays multi-dimensional data by representing each parameter as a parallel axis. This plot helps in assessing how thoroughly the search space has been explored and in identifying patterns or clusterings associated with high-performing (good) or low-performing (bad) arms. By tracing lines across the axes, one can observe correlations and interactions between parameters, gaining insights into the relationships that contribute to the success or failure of different configurations within the experiment.
Summary for hartmann6_experiment
High-level summary of the Trial-s in this Experiment
| trial_index | arm_name | trial_status | generation_node | hartmann6 | x1 | x2 | x3 | x4 | x5 | x6 | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 0 | 0_0 | COMPLETED | CenterOfSearchSpace | -0.505315 | 0.5 | 0.5 | 0.5 | 0.5 | 0.5 | 0.5 |
| 1 | 1 | 1_0 | COMPLETED | Sobol | -0.13967 | 0.088208 | 0.189382 | 0.879738 | 0.217179 | 0.833088 | 0.470028 |
| 2 | 2 | 2_0 | COMPLETED | Sobol | -0.004357 | 0.597786 | 0.952411 | 0.01775 | 0.947006 | 0.383126 | 0.642173 |
| 3 | 3 | 3_0 | COMPLETED | Sobol | -0.961139 | 0.803969 | 0.406135 | 0.688432 | 0.432231 | 0.19359 | 0.865524 |
| 4 | 4 | 4_0 | COMPLETED | Sobol | -1.22981 | 0.258978 | 0.641877 | 0.333988 | 0.669209 | 0.52684 | 0.006434 |
| 5 | 5 | 5_0 | COMPLETED | MBM | -0.07874 | 0.668624 | 0.412148 | 0.418424 | 0.307769 | 0.723591 | 0.486554 |
| 6 | 6 | 6_0 | COMPLETED | MBM | -0.071362 | 0 | 0.520338 | 0.660872 | 0.685162 | 0.303116 | 0 |
| 7 | 7 | 7_0 | COMPLETED | MBM | -1.06854 | 0.20356 | 0.785299 | 0.028529 | 0.728056 | 0.747402 | 0 |
| 8 | 8 | 8_0 | COMPLETED | MBM | -0.007155 | 1 | 0.716258 | 0.184684 | 0.613942 | 0.399294 | 0 |
| 9 | 9 | 9_0 | COMPLETED | MBM | -1.89128 | 0.305397 | 0.780554 | 0.021538 | 0.709217 | 0.71574 | 0.075649 |
| 10 | 10 | 10_0 | COMPLETED | MBM | -0.328946 | 0.246178 | 0.875999 | 0.322828 | 1 | 0.149409 | 0 |
| 11 | 11 | 11_0 | COMPLETED | MBM | -0.048562 | 0.256098 | 0.152913 | 0.099921 | 0.412479 | 0.542874 | 0 |
| 12 | 12 | 12_0 | COMPLETED | MBM | -2.4429 | 0.339853 | 0.796133 | 0.247633 | 0.63953 | 0.758443 | 0.087964 |
| 13 | 13 | 13_0 | COMPLETED | MBM | -0.819803 | 0.329772 | 0.713813 | 0 | 0.846972 | 0.72661 | 0.163026 |
| 14 | 14 | 14_0 | COMPLETED | MBM | -1.96406 | 0.319384 | 0.843039 | 0 | 0.567524 | 0.642134 | 0.181287 |
| 15 | 15 | 15_0 | COMPLETED | MBM | -2.87979 | 0.390625 | 0.869435 | 0.282015 | 0.627858 | 0.84906 | 0.038083 |
| 16 | 16 | 16_0 | COMPLETED | MBM | -0.136111 | 0.998021 | 0 | 1 | 0.423245 | 0 | 1 |
| 17 | 17 | 17_0 | COMPLETED | MBM | -1.70401 | 0.352353 | 0.795478 | 0.45839 | 0.630782 | 0.914945 | 0.212347 |
| 18 | 18 | 18_0 | COMPLETED | MBM | -2.8663 | 0.41466 | 0.900746 | 0.253614 | 0.53252 | 0.942251 | 0.036806 |
| 19 | 19 | 19_0 | COMPLETED | MBM | -3.01655 | 0.409691 | 0.95789 | 0.799974 | 0.584771 | 0.469182 | 0.041042 |
| 20 | 20 | 20_0 | COMPLETED | MBM | -2.67477 | 0.468379 | 0.818652 | 0 | 0.568045 | 0.730922 | 0.043499 |
| 21 | 21 | 21_0 | COMPLETED | MBM | -2.56508 | 0.421946 | 1 | 1 | 0.624585 | 1 | 0.045538 |
| 22 | 22 | 22_0 | COMPLETED | MBM | -2.74109 | 0.401297 | 1 | 0 | 0.595225 | 0 | 0.028772 |
| 23 | 23 | 23_0 | COMPLETED | MBM | -2.79074 | 0.410153 | 0.944591 | 1 | 0.597354 | 1 | 0 |
| 24 | 24 | 24_0 | COMPLETED | MBM | -2.98916 | 0.389366 | 0.889177 | 0.75589 | 0.518549 | 0.472542 | 0 |
| 25 | 25 | 25_0 | COMPLETED | MBM | -2.8787 | 0.38887 | 0.930858 | 0 | 0.554194 | 0.567271 | 0 |
| 26 | 26 | 26_0 | COMPLETED | MBM | -2.45671 | 0.404155 | 0.830838 | 1 | 0.42493 | 0.174433 | 0 |
| 27 | 27 | 27_0 | COMPLETED | MBM | -3.15668 | 0.405989 | 0.896999 | 0.694856 | 0.593678 | 0.290569 | 0.019137 |
| 28 | 28 | 28_0 | COMPLETED | MBM | -2.78016 | 0.340055 | 0.970947 | 1 | 0.553396 | 0.200183 | 0.025593 |
| 29 | 29 | 29_0 | COMPLETED | MBM | -0.675919 | 0.45832 | 0.332553 | 1 | 0.575311 | 0 | 0.988208 |
Sensitivity Analysis for hartmann6
Understand how each parameter affects hartmann6 according to a second-order sensitivity analysis.
x2, x6 vs. hartmann6
The contour plot visualizes the predicted outcomes for hartmann6 across a two-dimensional parameter space, with other parameters held fixed at their status_quo value (or mean value if status_quo is unavailable). This plot helps in identifying regions of optimal performance and understanding how changes in the selected parameters influence the predicted outcomes. Contour lines represent levels of constant predicted values, providing insights into the gradient and potential optima within the parameter space.
x1, x6 vs. hartmann6
The contour plot visualizes the predicted outcomes for hartmann6 across a two-dimensional parameter space, with other parameters held fixed at their status_quo value (or mean value if status_quo is unavailable). This plot helps in identifying regions of optimal performance and understanding how changes in the selected parameters influence the predicted outcomes. Contour lines represent levels of constant predicted values, providing insights into the gradient and potential optima within the parameter space.
x6 vs. hartmann6
The slice plot provides a one-dimensional view of predicted outcomes for hartmann6 as a function of a single parameter, while keeping all other parameters fixed at their status_quo value (or mean value if status_quo is unavailable). This visualization helps in understanding the sensitivity and impact of changes in the selected parameter on the predicted metric outcomes.
x4 vs. hartmann6
The slice plot provides a one-dimensional view of predicted outcomes for hartmann6 as a function of a single parameter, while keeping all other parameters fixed at their status_quo value (or mean value if status_quo is unavailable). This visualization helps in understanding the sensitivity and impact of changes in the selected parameter on the predicted metric outcomes.
x1 vs. hartmann6
The slice plot provides a one-dimensional view of predicted outcomes for hartmann6 as a function of a single parameter, while keeping all other parameters fixed at their status_quo value (or mean value if status_quo is unavailable). This visualization helps in understanding the sensitivity and impact of changes in the selected parameter on the predicted metric outcomes.
Cross Validation for hartmann6
The cross-validation plot displays the model fit for each metric in the experiment. It employs a leave-one-out approach, where the model is trained on all data except one sample, which is used for validation. The plot shows the predicted outcome for the validation set on the y-axis against its actual value on the x-axis. Points that align closely with the dotted diagonal line indicate a strong model fit, signifying accurate predictions. Additionally, the plot includes 95% confidence intervals that provide insight into the noise in observations and the uncertainty in model predictions. A horizontal, flat line of predictions indicates that the model has not picked up on sufficient signal in the data, and instead is just predicting the mean.
Conclusion
This tutorial demonstrates how to use Ax's Client for closed-loop optimization using
the Hartmann6 function as an example. This style of optimization is useful in scenarios
where trials are evaluated on some external system or when experimenters wish to take
advantage of parallel evaluation, trial failure handling, or simply to manage
long-running optimization tasks without human intervention. You can define your own
Runner and Metric classes to communicate with whatever external systems you wish to
interface with, and control optimization using the OrchestrationConfig.