import contextlib
import io
import logging29.3 Asynchronous Random Search
As we have seen in the previous Section 29.2, we might have to wait hours or even days before random search returns a good hyperparameter configuration, because of the expensive evaluation of hyperparameter configurations. In practice, we have often access to a pool of resources such as multiple GPUs on the same machine or multiple machines with a single GPU. This begs the question: How do we efficiently distribute random search?
In general, we distinguish between synchronous and asynchronous parallel hyperparameter optimization (see Figure 29.3.1). In the synchronous setting, we wait for all concurrently running trials to finish, before we start the next batch. Consider configuration spaces that contain hyperparameters such as the number of filters or number of layers of a deep neural network. Hyperparameter configurations that contain a larger number of layers of filters will naturally take more time to finish, and all other trials in the same batch will have to wait at synchronization points (grey area in Figure 29.3.1) before we can continue the optimization process.
In the asynchronous setting we immediately schedule a new trial as soon as resources become available. This will optimally exploit our resources, since we can avoid any synchronization overhead. For random search, each new hyperparameter configuration is chosen independently of all others, and in particular without exploiting observations from any prior evaluation. This means we can trivially parallelize random search asynchronously. This is not straightforward with more sophisticated methods that make decision based on previous observations (see Section 29.5). While we need access to more resources than in the sequential setting, asynchronous random search exhibits a linear speed-up, in that a certain performance is reached \(K\) times faster if \(K\) trials can be run in parallel.
In this section, we will look at asynchronous random search where trials are executed in multiple python processes on the same machine. Distributed job scheduling and execution is difficult to implement from scratch. We will use Syne Tune (Salinas et al. 2022), which provides us with a simple interface for asynchronous HPO. Syne Tune is designed to be run with different execution back-ends, and the interested reader is invited to study its simple APIs in order to learn more about distributed HPO.
# Use INFO level so the periodic Syne Tune tuning-status table appears,
# but use a clean format that drops the "INFO:syne_tune.tuner:" prefix.
logging.basicConfig(level=logging.INFO, format="%(message)s", force=True)
# Silence Syne Tune's import-time chatter about optional AWS dependencies
# (sagemaker, s3fs) and Ray Tune. We use the local PythonBackend, so those
# are not needed. Suppress both print() and logging.info() during imports.
_root = logging.getLogger()
_prev_level = _root.level
_root.setLevel(logging.WARNING)
try:
with contextlib.redirect_stdout(io.StringIO()):
from syne_tune.config_space import loguniform, randint
from syne_tune.backend.python_backend.python_backend import PythonBackend
from syne_tune.optimizer.baselines import RandomSearch
from syne_tune import Tuner, StoppingCriterion
from syne_tune.experiments import load_experiment
finally:
_root.setLevel(_prev_level)
# Silence the per-trial subprocess-command spam from local_backend and
# drop the per-trial scheduling / completion lines from the tuner logger.
# Keep the periodic "tuning status (last metric is reported)" updates so
# the reader can still see progress over time.
class _DropPerTrialNoise(logging.Filter):
_DROP = (
"results of trials will be saved",
"scheduled ",
"Trial trial_id ",
)
def filter(self, record):
msg = record.getMessage()
return not any(s in msg for s in self._DROP)
logging.getLogger("syne_tune.backend.local_backend").setLevel(logging.WARNING)
logging.getLogger("syne_tune.tuner").addFilter(_DropPerTrialNoise())29.3.1 Objective Function
First, we have to define a new objective function such that it now returns the performance back to Syne Tune via the report callback.
def hpo_objective_lenet_synetune(learning_rate, batch_size, max_epochs):
from d2l import torch as d2l
from syne_tune import Reporter
model = d2l.LeNet(lr=learning_rate, num_classes=10)
trainer = d2l.HPOTrainer(max_epochs=1, num_gpus=1)
data = d2l.FashionMNIST(batch_size=batch_size)
model.apply_init([next(iter(data.get_dataloader(True)))[0]], d2l.init_cnn)
report = Reporter()
for epoch in range(1, max_epochs + 1):
if epoch == 1:
# Initialize the state of Trainer
trainer.fit(model=model, data=data)
else:
trainer.fit_epoch()
validation_error = trainer.validation_error()
report(epoch=epoch, validation_error=validation_error)Note that the PythonBackend of Syne Tune requires dependencies to be imported inside the function definition.
29.3.2 Asynchronous Scheduler
First, we define the number of workers that evaluate trials concurrently. We also need to specify how long we want to run random search, by defining an upper limit on the total wall-clock time.
# Each LeNet trial fits in well under 7 GB of GPU memory, so we can pack
# multiple trials per device. `PythonBackend(rotate_gpus=True)` (the
# default) round-robins trials across detected GPUs and falls back to
# sharing when `n_workers > num_gpus`. Allocate 7 GB per slot — this
# yields 3 slots on a 24 GB card and 4 slots on a 32 GB card after
# driver overhead, e.g. 4×24 GB → 12 slots; 2×32 GB → 8.
import torch
_GB = 1024 ** 3
n_workers = sum(
torch.cuda.get_device_properties(i).total_memory // (7 * _GB)
for i in range(torch.cuda.device_count())
) or 1
max_wallclock_time = 15 * 60 # 15 minutesNext, we state which metric we want to optimize and whether we want to minimize or maximize this metric. Namely, metric needs to correspond to the argument name passed to the report callback.
mode = "min"
metric = "validation_error"We use the configuration space from our previous example. In Syne Tune, this dictionary can also be used to pass constant attributes to the training script. We make use of this feature in order to pass max_epochs. Moreover, we specify the first configuration to be evaluated in initial_config.
config_space = {
"learning_rate": loguniform(1e-2, 1),
"batch_size": randint(32, 256),
"max_epochs": 10,
}
initial_config = {
"learning_rate": 0.1,
"batch_size": 128,
}Next, we need to specify the back-end for job executions. Here we just consider the distribution on a local machine where parallel jobs are executed as sub-processes. However, for large scale HPO, we could run this also on a cluster or cloud environment, where each trial consumes a full instance.
trial_backend = PythonBackend(
tune_function=hpo_objective_lenet_synetune,
config_space=config_space,
)We can now create the scheduler for asynchronous random search, which is similar in behaviour to our BasicScheduler from Section 29.2.
scheduler = RandomSearch(
config_space,
metric=metric,
mode=mode,
points_to_evaluate=[initial_config],
)max_resource_level = 10, as inferred from config_space
Master random_seed = 1262744123
Syne Tune also features a Tuner, where the main experiment loop and bookkeeping is centralized, and interactions between scheduler and back-end are mediated.
stop_criterion = StoppingCriterion(max_wallclock_time=max_wallclock_time)
tuner = Tuner(
trial_backend=trial_backend,
scheduler=scheduler,
stop_criterion=stop_criterion,
n_workers=n_workers,
print_update_interval=int(max_wallclock_time * 0.6),
)Let us run our distributed HPO experiment. According to our stopping criterion, it will run for about 15 minutes.
tuner.run()tuning status (last metric is reported)
trial_id status iter learning_rate batch_size max_epochs epoch validation_error worker-time
0 Completed 10 0.100000 128 10 10 0.2923 24.180624
1 Completed 10 0.082763 113 10 10 0.2644 24.934025
2 Completed 10 0.080930 145 10 10 0.3151 22.784514
3 Completed 10 0.322440 221 10 10 0.2375 19.111622
4 Completed 10 0.068737 79 10 10 0.2696 31.304927
5 Completed 10 0.873000 45 10 10 0.1271 50.856921
6 Completed 10 0.291003 131 10 10 0.2747 22.858455
7 Completed 10 0.043908 70 10 10 0.3156 35.170509
8 Completed 10 0.038462 220 10 10 0.9000 19.027683
9 Completed 10 0.172284 36 10 10 0.1557 61.369803
10 Completed 10 0.024483 189 10 10 0.9000 20.478797
11 Completed 10 0.020956 108 10 10 0.9000 26.251260
12 Completed 10 0.048887 125 10 10 0.3936 20.209591
13 Completed 10 0.564286 41 10 10 0.1407 58.065812
14 Completed 10 0.011830 147 10 10 0.9000 21.675855
15 Completed 10 0.014536 195 10 10 0.9000 20.842799
16 Completed 10 0.025178 194 10 10 0.9000 20.872876
17 Completed 10 0.749182 229 10 10 0.3169 19.869571
18 Completed 10 0.140481 61 10 10 0.2102 40.129471
19 Completed 10 0.082477 155 10 10 0.3306 23.295283
20 Completed 10 0.046206 84 10 10 0.3166 31.231847
21 Completed 10 0.472420 236 10 10 0.3068 19.213980
22 Completed 10 0.392082 181 10 10 0.2116 20.849619
23 Completed 10 0.208072 150 10 10 0.2631 19.606782
24 Completed 10 0.532188 240 10 10 0.2020 17.290536
25 Completed 10 0.013032 137 10 10 0.9000 22.963058
26 Completed 10 0.880009 157 10 10 0.1678 21.478394
27 Completed 10 0.381799 48 10 10 0.1408 45.632828
28 Completed 10 0.024110 238 10 10 0.9000 18.564641
29 Completed 10 0.011689 118 10 10 0.9000 24.454123
30 Completed 10 0.270845 50 10 10 0.1605 45.937312
31 Completed 10 0.117845 153 10 10 0.2748 21.869672
32 Completed 10 0.281127 161 10 10 0.2239 21.272990
33 Completed 10 0.559356 120 10 10 0.1561 24.321344
34 Completed 10 0.022221 60 10 10 0.3719 37.052592
35 Completed 10 0.201594 227 10 10 0.2625 18.939422
36 Completed 10 0.567425 132 10 10 0.1620 22.784191
37 Completed 10 0.010470 137 10 10 0.9000 22.976642
38 Completed 10 0.011697 56 10 10 0.7861 42.085130
39 Completed 10 0.016733 135 10 10 0.9000 23.487937
40 Completed 10 0.017474 106 10 10 0.9000 26.340064
41 InProgress 8 0.075841 32 10 8 0.2012 52.196238
42 Completed 10 0.108654 140 10 10 0.2660 23.484949
43 Completed 10 0.365593 210 10 10 0.2109 19.878235
44 InProgress 8 0.031624 202 10 8 0.9000 16.066794
45 InProgress 2 0.281488 147 10 2 0.7502 9.374961
3 trials running, 43 finished (43 until the end), 542.43s wallclock-time
reaching max wallclock time (900), stopping there.
Stopping trials that may still be running.
Tuning finished, results of trials can be found on syne-tune/python-entrypoint-2026-11-23-15-46-59-384
--------------------
Resource summary (last result is reported):
trial_id status iter learning_rate batch_size max_epochs epoch validation_error worker-time
0 Completed 10 0.100000 128 10 10.0 0.2923 24.180624
1 Completed 10 0.082763 113 10 10.0 0.2644 24.934025
2 Completed 10 0.080930 145 10 10.0 0.3151 22.784514
3 Completed 10 0.322440 221 10 10.0 0.2375 19.111622
4 Completed 10 0.068737 79 10 10.0 0.2696 31.304927
5 Completed 10 0.873000 45 10 10.0 0.1271 50.856921
6 Completed 10 0.291003 131 10 10.0 0.2747 22.858455
7 Completed 10 0.043908 70 10 10.0 0.3156 35.170509
8 Completed 10 0.038462 220 10 10.0 0.9000 19.027683
9 Completed 10 0.172284 36 10 10.0 0.1557 61.369803
10 Completed 10 0.024483 189 10 10.0 0.9000 20.478797
11 Completed 10 0.020956 108 10 10.0 0.9000 26.251260
12 Completed 10 0.048887 125 10 10.0 0.3936 20.209591
13 Completed 10 0.564286 41 10 10.0 0.1407 58.065812
14 Completed 10 0.011830 147 10 10.0 0.9000 21.675855
15 Completed 10 0.014536 195 10 10.0 0.9000 20.842799
16 Completed 10 0.025178 194 10 10.0 0.9000 20.872876
17 Completed 10 0.749182 229 10 10.0 0.3169 19.869571
18 Completed 10 0.140481 61 10 10.0 0.2102 40.129471
19 Completed 10 0.082477 155 10 10.0 0.3306 23.295283
20 Completed 10 0.046206 84 10 10.0 0.3166 31.231847
21 Completed 10 0.472420 236 10 10.0 0.3068 19.213980
22 Completed 10 0.392082 181 10 10.0 0.2116 20.849619
23 Completed 10 0.208072 150 10 10.0 0.2631 19.606782
24 Completed 10 0.532188 240 10 10.0 0.2020 17.290536
25 Completed 10 0.013032 137 10 10.0 0.9000 22.963058
26 Completed 10 0.880009 157 10 10.0 0.1678 21.478394
27 Completed 10 0.381799 48 10 10.0 0.1408 45.632828
28 Completed 10 0.024110 238 10 10.0 0.9000 18.564641
29 Completed 10 0.011689 118 10 10.0 0.9000 24.454123
30 Completed 10 0.270845 50 10 10.0 0.1605 45.937312
31 Completed 10 0.117845 153 10 10.0 0.2748 21.869672
32 Completed 10 0.281127 161 10 10.0 0.2239 21.272990
33 Completed 10 0.559356 120 10 10.0 0.1561 24.321344
34 Completed 10 0.022221 60 10 10.0 0.3719 37.052592
35 Completed 10 0.201594 227 10 10.0 0.2625 18.939422
36 Completed 10 0.567425 132 10 10.0 0.1620 22.784191
37 Completed 10 0.010470 137 10 10.0 0.9000 22.976642
38 Completed 10 0.011697 56 10 10.0 0.7861 42.085130
39 Completed 10 0.016733 135 10 10.0 0.9000 23.487937
40 Completed 10 0.017474 106 10 10.0 0.9000 26.340064
41 Completed 10 0.075841 32 10 10.0 0.1832 64.374522
42 Completed 10 0.108654 140 10 10.0 0.2660 23.484949
43 Completed 10 0.365593 210 10 10.0 0.2109 19.878235
44 Completed 10 0.031624 202 10 10.0 0.9000 18.761118
45 Completed 10 0.281488 147 10 10.0 0.2361 23.991795
46 Completed 10 0.190532 153 10 10.0 0.2482 21.258431
47 Completed 10 0.325170 132 10 10.0 0.2217 22.704106
48 Completed 10 0.188011 169 10 10.0 0.3072 20.850336
49 Completed 10 0.327813 247 10 10.0 0.2401 17.456901
50 Completed 10 0.011011 129 10 10.0 0.9000 23.416682
51 Completed 10 0.132417 130 10 10.0 0.2599 23.082384
52 Completed 10 0.344099 228 10 10.0 0.2314 18.955932
53 Completed 10 0.036199 222 10 10.0 0.9000 19.796364
54 Completed 10 0.016494 77 10 10.0 0.9000 33.558630
55 Completed 10 0.032111 146 10 10.0 0.7620 22.493467
56 Completed 10 0.021413 59 10 10.0 0.4491 40.675814
57 Completed 10 0.493991 222 10 10.0 0.2692 18.877239
58 Completed 10 0.300193 137 10 10.0 0.2070 23.010715
59 Completed 10 0.504640 64 10 10.0 0.1503 35.827627
60 Completed 10 0.131998 213 10 10.0 0.2927 20.928028
61 Completed 10 0.038048 221 10 10.0 0.9000 18.682233
62 Completed 10 0.087245 108 10 10.0 0.2637 25.803040
63 Completed 10 0.013621 40 10 10.0 0.3979 51.572155
64 Completed 10 0.053028 102 10 10.0 0.3449 26.897252
65 Completed 10 0.011252 60 10 10.0 0.8099 37.590135
66 Completed 10 0.534070 159 10 10.0 0.2422 21.234338
67 Completed 10 0.070105 133 10 10.0 0.3313 22.401041
68 Completed 10 0.018105 192 10 10.0 0.9000 20.837920
69 Completed 10 0.364682 229 10 10.0 0.5061 18.501669
70 Completed 10 0.038400 93 10 10.0 0.3607 29.295407
71 Completed 10 0.233651 154 10 10.0 0.2252 21.028871
72 Completed 10 0.020867 169 10 10.0 0.9000 21.482733
73 Completed 10 0.650215 97 10 10.0 0.1634 27.433886
74 Completed 10 0.291165 219 10 10.0 0.2304 19.184455
75 Completed 10 0.019935 137 10 10.0 0.7915 22.716616
76 InProgress 3 0.169711 67 10 3.0 0.2811 14.930157
77 InProgress 7 0.021791 216 10 7.0 0.9000 15.219226
78 InProgress 0 0.245067 33 10 - - -
3 trials running, 76 finished (76 until the end), 900.27s wallclock-time
validation_error: best 0.1271 for trial-id 5
--------------------
The logs of all evaluated hyperparameter configurations are stored for further analysis. At any time during the tuning job, we can easily get the results obtained so far and plot the incumbent trajectory.
d2l.set_figsize()
tuning_experiment = load_experiment(tuner.name)
tuning_experiment.plot()29.3.3 Visualize the Asynchronous Optimization Process
Below we visualize how the learning curves of every trial (each color in the plot represents a trial) evolve during the asynchronous optimization process. At any point in time, there are as many trials running concurrently as we have workers. Once a trial finishes, we immediately start the next trial, without waiting for the other trials to finish. Idle time of workers is reduced to a minimum with asynchronous scheduling.
d2l.set_figsize([6, 2.5])
results = tuning_experiment.results
for trial_id in results.trial_id.unique():
df = results[results["trial_id"] == trial_id]
d2l.plt.plot(
df["st_tuner_time"],
df["validation_error"],
marker="o"
)
d2l.plt.xlabel("wall-clock time")
d2l.plt.ylabel("objective function")Text(0, 0.5, 'objective function')
29.3.4 Summary
We can reduce the waiting time for random search substantially by distributing trials across parallel resources. In general, we distinguish between synchronous scheduling and asynchronous scheduling. Synchronous scheduling means that we sample a new batch of hyperparameter configurations once the previous batch finished. If we have stragglers - trials that take more time to finish than other trials - our workers need to wait at synchronization points. Asynchronous scheduling evaluates new hyperparameter configurations as soon as resources become available, and, hence, ensures that all workers are busy at any point in time. While random search is easy to distribute asynchronously and does not require any change of the actual algorithm, other methods require some additional modifications.
29.3.5 Exercises
- Suppose that \(K\) workers run trials whose durations are independent of the configuration and of each other.
- Synchronous scheduling starts \(K\) trials together and waits for the slowest one. Show that if the durations are exponentially distributed with mean \(\mu\), a batch takes \(\mu H_K\) in expectation, where \(H_K = 1 + 1/2 + \cdots + 1/K\), so that the workers are busy for a fraction \(1/H_K\) of the time. Evaluate this fraction for \(K = 4\) and \(K = 12\).
- Repeat the calculation for durations that are uniformly distributed on \([T, 2T]\). Why does the busy fraction of synchronous scheduling go to zero as \(K\) grows in the first case but not in the second?
- Measure how well the run in this section used its workers, using
tuning_experiment.results.- For each trial, take the last reported value of
st_worker_time, the number of seconds since the trial created itsReporter. Divide the sum of these values byn_workers * max_wallclock_timeand report the result. Find the work thathpo_objective_lenet_synetunedoes before it creates theReporter, and name the other overheads that keep this fraction below 1. - Measure the runtime of one 10-epoch trial with batch size 128 under the sequential
HPOTunerof Section 29.2, and compare it withst_worker_timeof trials with similar batch sizes in this run. What speed-up over sequential random search did then_workersworkers achieve? Why is it smaller thann_workerswhen several workers share one GPU?
- For each trial, take the last reported value of
- A searcher that learns from earlier results, such as Bayesian optimization, faces a problem under asynchronous scheduling that random search does not: when a worker becomes free, other trials are still running. Suppose that the searcher fits a Gaussian process regression model (Chapter 28) to the validation errors observed so far, and proposes the configuration that minimizes an acquisition function.
- If the acquisition function is the posterior mean \(\mu(\mathbf{x})\), explain why several workers that become free before any new result arrives all receive the same configuration.
- A common remedy treats every pending configuration \(\mathbf{x}_p\) as if it had been observed with value \(\mu(\mathbf{x}_p)\). Show, using the posterior update for one additional observation, that this leaves the posterior mean unchanged everywhere and reduces the posterior variance near \(\mathbf{x}_p\).
- Does the remedy help a searcher that minimizes \(\mu(\mathbf{x})\)? Does it help one that minimizes \(\mu(\mathbf{x}) - \kappa \sigma(\mathbf{x})\) for some \(\kappa > 0\), where \(\sigma(\mathbf{x})\) is the posterior standard deviation?
- Consider the
DropoutMLPmodel implemented in Section 4.6, and used in Exercise 1 of Section 29.2.- Implement an objective function
hpo_objective_dropoutmlp_synetuneto be used with Syne Tune. Make sure that your function reports the validation error after every epoch. - Using the setup of Exercise 1 in Section 29.2, compare random search to Bayesian optimization. If you use SageMaker, feel free to use Syne Tune’s benchmarking facilities in order to run experiments in parallel. Hint: Bayesian optimization is provided as
syne_tune.optimizer.baselines.BayesianOptimization. - For this exercise, you need to run on an instance with at least 4 CPU cores. For one of the methods used above (random search, Bayesian optimization), run experiments with
n_workers=1,n_workers=2,n_workers=4, and compare results (incumbent trajectories). At least for random search, you should observe linear scaling with respect to the number of workers. Hint: For robust results, you may have to average over several repetitions each.
- Implement an objective function
- Advanced. The goal of this exercise is to implement a new scheduler in Syne Tune.
- Create a virtual environment containing both the d2lbook and syne-tune sources.
- Implement the
LocalSearcherfrom Exercise 2 in Section 29.2 as a new searcher in Syne Tune. Hint: Read this tutorial. Alternatively, you may follow this example. - Compare your new
LocalSearcherwithRandomSearchon theDropoutMLPbenchmark.