Repository navigation
Closed
Labels
Description
I have a single threaded function which I want to optimise.
I'm trying to write a wrapper that would handle multiple runs at the same time, but I'm noticing considerable degradation in results as I increase the number of parallel evaluations.
Here is the rough logic of what I'm doing:
from __future__ import annotations
from pprint import pprint
from typing import Callable
import numpy as np
from bayes_opt.bayesian_optimization import BayesianOptimization
from bayes_opt.util import UtilityFunction
from tqdm import tqdm, trange
def multivariable_func(r: float, x: float, y: float, diff: float) -> float:
r = int(r)
diff = diff > 0.5
loss = (r - 5) ** 2
loss += (x**2 + y**2 - r) ** 2
loss += abs(x - y) * (-1) ** int(diff)
loss += 0.5 * x
loss += -0.25 * int(diff)
return -loss
def optimize(func: Callable[..., float], num_iter: int, bounds: dict[str, tuple[float, float]], num_workers=0):
init_samples = int(np.sqrt(num_iter))
optimizer = BayesianOptimization(f=None, pbounds=bounds, verbose=0)
init_kappa = 10
kappa_decay = (0.1 / init_kappa) ** (1 / (num_iter - init_samples))
utility = UtilityFunction(
kind="ucb", kappa=init_kappa, xi=0.0, kappa_decay=kappa_decay, kappa_decay_delay=init_samples
)
init_queue = [optimizer.suggest(utility) for _ in range(init_samples)]
result_queue = []
tbar = tqdm(total=num_iter, leave=False)
while len(optimizer.res) < num_iter:
sample = init_queue.pop(0) if init_queue else optimizer.suggest(utility)
loss = func(**sample)
result_queue.append((sample, loss))
if len(result_queue) >= num_workers:
try:
optimizer.register(*result_queue.pop(0))
utility.update_params()
tbar.update()
except KeyError:
pass
return optimizer.max
bounds = {"r": [-10, 10], "x": [-10, 10], "y": [-10, 10], "diff": [0, 1]}
all_results = {}
for num_workers in tqdm([1, 2, 4, 8], desc="Checking num_workers"):
results = []
for idx in trange(2, desc=f"Sampling with {num_workers=}"):
best = optimize(multivariable_func, 400, bounds, num_workers)
results.append(best["target"])
all_results[num_workers] = np.mean(results)
tqdm.write(f"Result for optimizing with {num_workers=}: {all_results[num_workers]}")
print("\n")
pprint(all_results)The result_queue variable is simulating evaluation across multiple processes.
Here are the results:
{1: 4.320798413579277,
2: 4.320676522735756,
4: 3.5379530743926133,
8: 2.175667857740832}
As can be seen, the more processes I use, the worse the final result is. I don't understand why that would happen, even if a couple fewer suggestions are evaluated properly, the results should not differ so much.
What am I missing?
Reacted by bwheelz36
Activity
bwheelz36 commentedon Aug 17, 2022
Hi
Just to make sure I understand: Essentially the goal is to collect
num_workersresults, then update the GP model with all collected results? And in this example, nothing is actually happening in parallel - but the point is it could be - is that correct?It appears to me that the issue arises when you register the results:
optimizer.register(*result_queue.pop(0))This line only registers one of the n_worker results? so essentially for four workers, you are throwing away 75% of the information...
you can check the registered data with
optimizer.resAlso, you seem to be using the kappa decay functionality to generate an
init_queueofinit_sampleslength - but since at this point there is no data I guess this is just generating random points? which is fine as long as you are aware of this! (actually, I quite like this approach of leveraging the kappa decay to generate multiple suggestions, relevant for #327 and #340)Apart from this - have you searched these issues for 'parallel'? I don't have much (well any) experience running this library in parallel but it appears that there are some other examples out there...
Rizhiy commentedon Aug 17, 2022
That is not exactly what is happening. Rather I have a pool of workers and when one of them finishes, I register its result and generate a new suggestion for it to evaluate. The number of suggestions is the same, but the registration is delayed by
num_workers.The loop depends on the number of registered results, so it always checks the same number of suggestions.
As explained in other issues, generating multiple suggestions at the same time doesn't work, since the algorithm is deterministic. That is why a new observation is always registered before asking for a new suggestion.
bwheelz36 commentedon Aug 18, 2022
This is correct if kappa doesn't change, but you can certainly obtain n suggestions with n different kappas.
Apologies, I misinterpreted your code.
I've had another look at this and I think the result you are seeing my actually be variation as the result of the random state not being set. can you try again with
optimizer = BayesianOptimization(f=None, pbounds=bounds, verbose=0, random_state=1)?I created a simplified version of your example, and I get consistent results when random_state is set:
Rizhiy commentedon Aug 18, 2022
I tried that, it doesn't make a difference. Moreover, I am not talking about consistent results, I'm talking about optimisation successfully finding the values close to global optimum. That should be the case no matter what the initial seed is. I'm also running it multiple times to remove the possibility of lucky guesses.
If you run the code you provided, then it is expected that you receive the same result since you fixed the seed and
n_workersis not being used.Also, it is not very close to global optimum with 100 iterations, I only get
-0.15534which is not satisfactory forrosen, it just found the valley.I also run a fixed version of your code, with
n_workersbeing used and results are as expected:bwheelz36 commentedon Aug 22, 2022
oops - good point - I was playing around with that and forgot to change it back.
I've had another look at this, again using the rosen function with the n_workers parameter fixed.
The below plot shows the true rosen function, the rosen function predicted by the gaussian process model after being trained for 200 iterations, the GP standard deviation, and the absolute difference between true and predicted. I'll post the code for this below, but note that in the valley region both uncertainty (SD) and absolute difference are low. You can do similar things for your multi variable function but obviously visualization is not as straightforward. The two points shown are the true maximum and the point found by the optimizer.
🤷♂️ this is with kappa=10, so the algorithm will tend to prioritize exploring over finding the global minimum. If you put the kappa decay back in I get 0.0096. But in general this algorithm is good at exploring and not getting stuck, but not necessarily as good at honing in on local minima.
Rizhiy commentedon Aug 22, 2022
OK, thank you. I've done some tests and here are the results for my example:
These are averaged over 10 runs with different seeds to remove the effect of lucky guesses.
In this toy example, I would say anything above 4.3 is satisfactory. 8 workers require 700 iterations instead of 500, which equates to 470% speed-up.
Currently, this is fine for me, so I will stop working on analysing this for now.
bwheelz36 commentedon Aug 23, 2022
One other thought - I'm not sure if this will help or not, but possibly a 'flatter' objective function (perhaps by taking the log or even just capping the minimum value) may perform better - the very large gradients involved with these high range objective functions might 'confuse' the algorithm. I'm not sure if that's the case or not but it's something you could check.
Rizhiy commentedon Sep 21, 2022
I might have an idea of why performance degrades. I think if there are too many points evaluated concurrently, the algorithm might propose a very similar point to one of those which are in queue. This will essentially reduce effective number of iterations.
I will run a few experiments to check if this is indeed the case.
Rizhiy commentedon Oct 10, 2022
I've finally run the experiments and the results are as I expected.

Here is the figure of samples with different number of workers:
As can be seen, when the number of workers increase, points start to clump together, effectively reducing real number of iterations.
Similarly, if we calculate average distance to the nearest point, it decreases:
To fix this, I suggest that when a sample is suggested and put into the queue the GP STD at that point is set to 0, so that it doesn't suggest new points around that value.
I guess this can be done by first registering a fake point and then replacing it with the real result, but I was wondering whether there is a better approach.
@bwheelz36 Any idea how this is best accomplished?
Rizhiy commentedon Oct 10, 2022
Here is the code I used for the experiment, just in case:
bwheelz36 commentedon Oct 10, 2022
Hey, thanks for following this up, I'll reopen this issue.
and then basically have each worker using a different kappa value or something like that?
Rizhiy commentedon Oct 11, 2022
I think the problem is that when using
ucb, there is likely a single point which satisfies the requirements. Unless a registered observation modifies the surface such that best-ucbchanges, a similar point will keep being suggested. From my understanding, for observation to have such effect, the result must be close to current best, which happens rarely.Ok, so is it possible to "de-register" an observation? I can quite easily register a dummy observation when a sample is suggested and then de-register, re-register once the actual result is available.
Might be a good alternative approach, but I would like to try improving the quality of suggestions first.
Rizhiy commentedon Oct 11, 2022
I looked at the code and it seems that it should be rather trivial to implement de-register/re-register functionality since GP is fitted anew for each suggestion. Will try to make an MR.
Rizhiy commentedon Oct 11, 2022
I think I have a working solution: #365
Testing code:
Results without change (
with_dummies=False):Results with change (
with_dummies=True):As can be seen there is quite a big improvement.
Although, it seems there are still a couple of problems:
bwheelz36 commentedon Oct 13, 2022
looks really promising! Sorry I think it is going to take me a few days to look at this properly though :-(
cestpasphoto commentedon Jan 23, 2024
Wouldn't it be better to set the target of dummy points to what regressor would expect?
I mean register_dummy() should use
optimizer._gp.predict(params)as target.t-muser commentedon Jan 23, 2024
@cestpasphoto shameless plug, but in PR #447 you can find this under the name
KrigingBelieverand the version proposed here under the nameConstantLiar. It's not merged currently, but you can install from my branch (if you do, please let me know if you have any feedback).That being said, during my limited testing I found both methods to work well, though I read in a paper that the lying seems to perform better, if you manage to choose a suitable value.