Sub topic 16
Ask-and-tell and enqueueing known trials
This chapter assumes you can write an objective function, define a search space with suggest_* methods, and run study.optimize. It covers two features that give you more control over how trials start and finish: the ask-and-tell interface and enqueue_trial.
Why `optimize` is sometimes not enough
study.optimize(objective, n_trials=...) owns the loop. Optuna creates the trial, calls your function, records the return value, and handles exceptions. That works when the whole evaluation fits in one Python function that Optuna can call.
Some workflows do not fit:
- The evaluation runs somewhere else, such as a job queue, a cluster scheduler, or a training service. The result arrives later and in a different process.
- You want to evaluate several candidates in one batch, for example on a GPU that trains many models at once.
- Your code already has its own loop or framework, and you cannot hand control to a callback.
- You already know some good configurations and want Optuna to try them first.
Ask-and-tell handles the first three. Enqueueing handles the last.
The ask-and-tell interface
Ask-and-tell splits optimize into two calls:
study.ask()creates a new trial and returns it. The sampler is consulted when you callsuggest_*on that trial.study.tell(trial, value)reports the final result for that trial.
Between the two calls, you can do anything: run code in a different place, wait, or evaluate other trials.
Here is the minimal form, using the same function as the first example in this tutorial:
import optuna
study = optuna.create_study(direction="minimize")
for _ in range(20):
trial = study.ask()
x = trial.suggest_float("x", -10, 10)
value = (x - 2) ** 2
study.tell(trial, value)
print(study.best_params)
print(study.best_value)The result is the same as with optimize, but you wrote the loop. The suggest_* calls work as before. Each call returns a value and records the parameter on the trial.
Defining the search space up front
With ask, you can pass a fixed search space instead of calling suggest_* inside your code. Use the fixed_distributions argument:
import optuna
from optuna.distributions import FloatDistribution, IntDistribution
study = optuna.create_study(direction="minimize")
space = {
"x": FloatDistribution(-10, 10),
"n": IntDistribution(1, 5),
}
trial = study.ask(fixed_distributions=space)
print(trial.params)
study.tell(trial, (trial.params["x"] - 2) ** 2 + trial.params["n"])All parameters are sampled when ask returns, so trial.params is already filled. This is useful when a different system consumes the parameters. It does not support conditional spaces, because every parameter in the dictionary is always sampled.
Reporting failures and pruned trials
tell accepts a state argument. A trial that crashes or is stopped should not stay in the running state forever.
import optuna
from optuna.trial import TrialState
study = optuna.create_study(direction="maximize")
trial = study.ask()
lr = trial.suggest_float("lr", 1e-5, 1e-1, log=True)
try:
score = 0.9 if lr < 0.05 else float("nan")
if score != score:
raise ValueError("training diverged")
study.tell(trial, score)
except ValueError:
study.tell(trial, state=TrialState.FAIL)Use TrialState.FAIL for errors and TrialState.PRUNED when you stopped the trial early. For a pruned trial, you can also pass the last intermediate value as values so the study keeps it. The tell method has a skip_if_finished option. Without it, telling a trial that is already finished raises an error.
Pruning with ask-and-tell
You can still prune. Call trial.report and trial.should_prune() in your loop. When it returns True, call study.tell(trial, state=TrialState.PRUNED) yourself. Raising optuna.TrialPruned has no effect here, because no optimize call is present to catch it.
Batch evaluation
A common use of ask-and-tell is to ask for several trials, evaluate them together, and tell the results in a batch.
import optuna
def evaluate_batch(xs):
# Stand-in for work that runs many candidates at once.
return [(x - 2) ** 2 for x in xs]
study = optuna.create_study(direction="minimize")
for _ in range(5):
trials = [study.ask() for _ in range(4)]
xs = [t.suggest_float("x", -10, 10) for t in trials]
values = evaluate_batch(xs)
for t, v in zip(trials, values):
study.tell(t, v)
print(study.best_value, len(study.trials))Asking for four trials before telling any result means those four proposals cannot learn from each other. The sampler sees the unfinished trials as running, and TPE treats them with a default strategy, so proposals within a batch may be similar. Smaller batches give the sampler more feedback. This is the same trade-off as in parallel optimisation.
Enqueueing known trials
Often you already know a configuration that works: the library default, last month's best result, or a value from a paper. Starting with it gives the sampler a useful reference point, and you get a guaranteed baseline in the study.
study.enqueue_trial(params) adds a configuration to a queue. The next trial, whether created by optimize or ask, takes its parameters from the queue instead of from the sampler.
import optuna
study = optuna.create_study(direction="minimize")
study.enqueue_trial({"x": 1.0})
trial = study.ask()
x = trial.suggest_float("x", -10, 10)
study.tell(trial, (x - 2) ** 2)
print(trial.params)The suggest_float("x", ...) call returns 1.0, the enqueued value. Your code does not change.
It also works with optimize:
import optuna
def objective(trial):
x = trial.suggest_float("x", -10, 10)
y = trial.suggest_int("y", 0, 5)
return (x - 2) ** 2 + y
study = optuna.create_study(direction="minimize")
study.enqueue_trial({"x": 2.0, "y": 0})
study.enqueue_trial({"x": 0.0, "y": 1})
study.optimize(objective, n_trials=10)
for t in study.trials[:2]:
print(t.number, t.params, t.value)The first two trials use the queued values in order. The remaining eight come from the sampler.
Rules and edge cases
- Queued trials count toward
n_trials. Ten trials with two enqueued means eight sampled ones. - Missing parameters are sampled normally. If you enqueue only
{"x": 1.0}and the objective also suggestsy, Optuna samplesywith the sampler. Passskip_if_exists=Trueto avoid adding a duplicate of an already-run configuration. - Values outside the range. If an enqueued value lies outside the distribution in
suggest_*, Optuna warns and the value is not used for that trial. Check ranges before enqueueing. - Conditional spaces. Enqueue the categorical choice and the parameters that follow from it. For the classifier example, use
{"classifier": "svc", "svc_c": 1.0}. - Storage. In a database-backed study, the queue is stored with the study. Another worker process picks up the queued trial. Each entry is used once.
- Sampler learning. Enqueued trials are finished like any other. The sampler uses them as observations, so TPE can build its model from your known points.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Calling `ask` and never calling `tell` | Trials stay in the `RUNNING` state, and the sampler gets no data from them | Always tell a value or a state, including on exceptions |
| Raising `TrialPruned` in an ask-and-tell loop | The exception is uncaught and stops your program | Call `tell` with `TrialState.PRUNED` |
| Asking for a large batch before any `tell` | Proposals ignore each other, so the search is closer to random | Use smaller batches or tell as results arrive |
| Enqueueing a value outside the range | The value is ignored with a warning | Check against the `suggest_*` bounds |
| Passing `fixed_distributions` for a conditional space | Parameters that should not exist get sampled | Use `suggest_*` calls in the code |
Exercise
You enqueue two configurations and call study.optimize(objective, n_trials=10). How many trials does the sampler choose, and what happens if one enqueued configuration has a value outside the range in suggest_float?
Show answer
The sampler chooses eight trials, because queued trials count toward n_trials. The out-of-range value is not used for that trial. Optuna warns, so you should check bounds before enqueueing.
Exercise
Your training job runs on a cluster and returns results an hour after submission. Why is ask-and-tell a better fit than study.optimize, and what must you do if a job crashes?
Show answer
optimize needs the objective to return in the same call, but ask-and-tell lets you ask for a trial, submit the job, and call tell when the result arrives, possibly in another process. If the job crashes, call study.tell(trial, state=TrialState.FAIL) so the trial does not remain in the running state.