Skip to content

Ask and tell

Normally solve calls your objective function itself. Ask and tell turns this around: the algorithm asks you for the values of a batch of solutions, you compute them any way you like, and you tell it the results. Use it when solve cannot call the objective: a lab experiment, a cluster job, or a simulator that runs on its own.

The example below minimizes the sum of squares of 5 real variables with PSO. The problem has objective=None, and the loop evaluates each batch itself until the budget of 500 evaluations (max_nfe, the number of objective function evaluations) is used.

import numpy as np
import ypea

# objective=None: the solutions are evaluated outside the toolbox
problem = ypea.Problem(
    ypea.Real("x", shape=5, lb=-10, ub=10),
    objective=None,
    name="outside",
)

run = ypea.PSO(max_nfe=500).ask_tell(problem, seed=0)
while not run.done:
    solutions = run.ask()  # decoded solutions, as the objective would get them
    values = []
    for sol in solutions:
        values.append(np.sum(sol.x**2))  # evaluate them anywhere
    run.tell(values)  # one value per solution, in the same order
result = run.result()
print(result.nfe, result.stop_reason)
500 max_nfe

Differs from Python: a problem with no objective omits objective=.

% no objective: the solutions are evaluated outside the toolbox
problem = ypea.Problem( ...
    vars=ypea.Real("x", shape=5, lb=-10, ub=10), ...
    name="outside");

run = ypea.PSO(max_nfe=500).ask_tell(problem, seed=0);
while ~run.done
    solutions = run.ask();  % decoded solutions, as the objective would get them
    values = zeros(numel(solutions), 1);
    for i = 1:numel(solutions)
        values(i) = sum(solutions(i).x.^2);  % evaluate them anywhere
    end
    run.tell(values);  % one value per solution, in the same order
end
result = run.result();
fprintf("%d %s\n", result.nfe, result.stop_reason);
500 max_nfe

The output shows the number of evaluations used and why the run stopped.

Told the true values, a run gives exactly the Result of solve with the same seed, for every algorithm and also with ypea.StudioRng.

sequenceDiagram
    participant You
    participant Run as ask_tell run
    participant Alg as Algorithm (background thread)
    You->>Run: ask()
    Run->>Alg: next batch?
    Alg-->>Run: solutions to evaluate
    Run-->>You: decoded solutions
    Note over You: evaluate them anywhere
    You->>Run: tell(values)
    Run->>Alg: values
    Note over Alg: update the best, iterate
    You->>Run: result()
    Run-->>You: Result

What ask gives and tell takes

ask() returns the batch as the objective would get it: a list of Solution objects, or for a vectorized problem one Solution with a leading batch axis. run.codes holds the codes, shape (n, code_size).

tell(values) takes what the objective would return, in the same order: f, (f, g) or (f, g, h) per solution (see Objectives and constraints), or the arrays of the whole batch for a vectorized problem. With several objectives, f is a list or array (shape (n, m) when vectorized).

This example has a constraint and a vectorized objective, so each ask() gives one Solution whose x holds the whole batch, and tell takes the arrays of objective values and constraint values. The best solution lies on the line x + y = 2, with the value 0.5.

import ypea


def design(sol):
    # minimize (x - 2)^2 + (y - 1)^2 subject to x + y <= 2
    x, y = sol.x[..., 0], sol.x[..., 1]
    return (x - 2) ** 2 + (y - 1) ** 2, x + y - 2


problem = ypea.Problem(
    ypea.Real("x", shape=2, lb=-5, ub=5),
    objective=None,
    vectorized=True,
)
run = ypea.DE(max_nfe=1000, pop_size=20).ask_tell(problem, seed=1)
while not run.done:
    batch = run.ask()
    run.tell(design(batch))  # arrays for the whole batch
result = run.result()
print(round(result.best.obj_value, 3))
0.5

Differs from Python: tell takes the outputs as separate arguments, run.tell(f, g).

problem = ypea.Problem( ...
    vars=ypea.Real("x", shape=2, lb=-5, ub=5), ...
    vectorized=true);
run = ypea.DE(max_nfe=1000, pop_size=20).ask_tell(problem, seed=1);
while ~run.done
    batch = run.ask();
    [f, g] = design(batch);
    run.tell(f, g);  % arrays for the whole batch
end
result = run.result();
disp(round(result.best.obj_value, 3))

function [f, g] = design(sol)
% minimize (x - 2)^2 + (y - 1)^2 subject to x + y <= 2
x = sol.x(:, 1);
y = sol.x(:, 2);
f = (x - 2).^2 + (y - 1).^2;
g = x + y - 2;
end
    0.5000

The batch size varies. Population methods usually ask for a whole population, and Nelder-Mead asks for one solution at a time after its first simplex. The last batch may be smaller so the run stays within max_nfe. On a constrained problem whose first batch has fewer than 20 solutions, the next batch holds random solutions used to scale the constraints.

ask_tell(problem, seed=..., keep_evaluations=True) keeps every told value in result().evaluations. A problem may still have an objective, so you can evaluate some solutions with it and others elsewhere. With objective=None, solve raises an error.

Stopping early

run.stop() ends the run and returns its result, with the stop reason "stopped" or the one you give. Here GA is stopped after 5 batches, for example because the lab time ran out:

import numpy as np
import ypea

problem = ypea.Problem(ypea.Real("x", shape=5, lb=-10, ub=10), objective=None)
run = ypea.GA(max_iter=100, pop_size=20).ask_tell(problem, seed=0)
for _ in range(5):
    solutions = run.ask()
    values = []
    for sol in solutions:
        values.append(np.sum(sol.x**2))
    run.tell(values)
result = run.stop("out of lab time")
print(result.nfe, result.stop_reason)
60 out of lab time
problem = ypea.Problem(vars=ypea.Real("x", shape=5, lb=-10, ub=10));
run = ypea.GA(max_iter=100, pop_size=20).ask_tell(problem, seed=0);
for step = 1:5
    solutions = run.ask();
    values = zeros(numel(solutions), 1);
    for i = 1:numel(solutions)
        values(i) = sum(solutions(i).x.^2);
    end
    run.tell(values);
end
result = run.stop("out of lab time");
fprintf("%d %s\n", result.nfe, result.stop_reason);
60 out of lab time

A batch asked for but not told is not counted. Before the first tell, there is no result and stop() raises an error. The usual stopping rules, callbacks and request_stop also apply, and max_time includes the time you spend evaluating.

Errors

  • tell() before ask(), or ask() twice in a row, raises a RuntimeError.
  • tell() with the wrong number of values raises a ValueError, and the run waits for the right values.
  • An exception in the algorithm or a callback is raised by tell(), and the run is then done.

How it works

The algorithm runs its normal loop on a copy of itself in a background thread, and pauses whenever it needs values. Callbacks run in that thread, between tell() and the next batch. run.algorithm is the running copy, so you can read run.algorithm.iter or run.algorithm.best between batches.