Repository navigation
Closed
Labels
Description
Bounds Transformer doesn't work after loading the logs
bayesian-optimization==1.5.0
High-level flow:
- Create `original_logger = JSONLogger(path="./original_logsr.json"), reset=True)
- Create
original_bounds_transformer = SequentialDomainReductionTransformer() - Create
original_optimizer = BayesianOptimization(... bounds_transformer=original_bounds_transformer) - Subscribe logger
original_optimizer.subscribe(Events.OPTIMIZATION_STEP, original_logger ) - Run optimization
original_optimizer .maximize(init_points=2, n_iter=10) - Create new
loaded_optimizerwith newloaded_bounds_transformerin the same way andload_logs(loaded_optimizer, logs=""./original_logsr.json"). - Call
maximize(n_iter=10)for both optimizers and compare their results + optimizers.
You will see thatloaded_optimizerhas wrong values like its bounds_transformer becomes "broken" or irresponsive.
The main goal of such flow is to have a "checkpoint" and continue optimization later.
P.S. I've tried many different options with dumping transformer content using pickle, updating it, transforming, etc without any luck
Note I carefully read whole documentation and followed most of examples., but was not able to find the proper way.
To Reproduce
## core idea described here: https://bayesian-optimization.github.io/BayesianOptimization/domain_reduction.html
import numpy as np
from bayes_opt import BayesianOptimization
from bayes_opt import SequentialDomainReductionTransformer
from bayes_opt.logger import JSONLogger
from bayes_opt.event import Events
from bayes_opt.util import load_logs
import matplotlib.pyplot as plt
pbounds = {'x': (-5, 5), 'y': (-5, 5)}
def ackley(**kwargs):
x = np.fromiter(kwargs.values(), dtype=float)
arg1 = -0.2 * np.sqrt(0.5 * (x[0] ** 2 + x[1] ** 2))
arg2 = 0.5 * (np.cos(2. * np.pi * x[0]) + np.cos(2. * np.pi * x[1]))
return -1.0 * (-20. * np.exp(arg1) - np.exp(arg2) + 20. + np.e)
# A. init logger, transformer and optimizer
orig_logger = JSONLogger(path="./orig_optimizer.json", reset=True)
orig_bounds_transformer = SequentialDomainReductionTransformer()
orig_optimizer = BayesianOptimization(
f=ackley,
pbounds=pbounds,
verbose=0,
random_state=1,
bounds_transformer=orig_bounds_transformer
)
orig_optimizer.subscribe(Events.OPTIMIZATION_STEP, orig_logger)
orig_optimizer.maximize(init_points=2, n_iter=20)
# B. create new optimizer, transformer and load logs there
loaded_bounds_transformer = SequentialDomainReductionTransformer()
loaded_optimizer = BayesianOptimization(
f=ackley,
pbounds=pbounds,
verbose=0,
random_state=1,
bounds_transformer=loaded_bounds_transformer
)
load_logs(loaded_optimizer, logs="./orig_optimizer.json")
# C. Let's continue optimization and compare the results. loaded_transformer become unresponsive or broken
loaded_optimizer.maximize(init_points=0, n_iter=20)
orig_optimizer.maximize(init_points=0, n_iter=20)
plt.plot(orig_optimizer.space.target, label='Original Optimizer')
plt.plot(loaded_optimizer.space.target, label='Loaded Optimizer')
plt.legend()
# D. We may compare transformers and see that loaded_one remains unchangedExpected behavior
After loading the logs loaded_bounds_transformer should continue updating its bounds and loaded_optimizer should find an optimal points in the already defined boundaries instead of starting whole flow from the beginning.
Environment (please complete the following information):
- OS: Windows 11
pythonVersion 3.12.3numpy1.26.4scipy1.13.0bayesian-optimization1.5.0

Activity
t-muser commentedon Jun 26, 2024
Hi @pawlissimo,
thanks for opening the issue and providing some code!
It doesn't look like you're loading anything for the bounds transformer, but in the original post you mentioned some sort of pickle/unpickle operation.
pawlissimo commentedon Jun 26, 2024
Hi @Till-M,
Here I just provided basic code and expected outcome without my workarounds.
I may extend it with them if needed.
I think, that underlying issue seems to be related to losing ability to dump/restore Transformer's data and then linking it again with loaded optimizer after
load_logs()commandP.S. pickle/unpickle just dumps binary object representation. And it's not 100% reliable in case I want to dump it on one machine and load on another machine
t-muser commentedon Jun 26, 2024
There's two things that you need to do:
There are still some slight differences in the plots, which I assume come due to randomness.
@bwheelz36 Nonetheless, I think we should work towards proper serialization, there's really only so far one can push
JSONlogging (see also e.g. #478).@pawlissimo let me know if this helps :)
pawlissimo commentedon Jun 26, 2024
Hi @Till-M ,
Thanks a lot for your suggestion. It really looks more promising now.
I see a few things here:
random_state=1and checked in BO code base to be sure, that GP and utility function produce exactly the same predictable results. So, for now I don't think differences related to some randomnessloaded_optimizer.set_bounds(loaded_bounds)seems a bit strange and not so obvious to me, since we already loaded logs. BTW, it seems strange why we do not callset_boundsduringload_logsautomatically?load_logs()in addition tooptimizer.register(...)we also need to update bounds for its transformer (if it exists).UPD. I'd like to avoid using pickle and dumping whole bynary object's context. It's better to understand what exact Transformer's params should be stored as json object. But my experiments were not successful due to lack of complete understanding on how it works
t-muser commentedon Jun 26, 2024
Hi @pawlissimo,
first of all, or 0.) Please consider that this loading from logs is a rather old functionality. Back when the optimization had fewer bells and whistles (e.g. no Domain Transformer, Constraints) it worked quite well. It hasn't really kept step with these additions, because most users don't really care about serialization. For constraints, I've tried to make it work, but it was also a suprisingly delicate process.
I do think we should have a better way of serializing the optimizer object (PRs are welcome, by the way 😉). When in doubt, I would recommend pickling, though I am aware it's inelegant and I understand why you'd rather not use it in this. Nonetheless, if you're wondering why some things behave weirdly, the reason is that the optimization object has become to complicated and stateful for such a simple state restoration method. There is a lot of value in having human-readable logs, but they're also very restrictive!
1.)
yes, you did fix the
random_state! The problem is, that therandom_statemutates as it is used. In a sense, it is really only consistent if you call the exact same code. This is necessary, as otherwise the state could only really return one random number. Since the random state is used during the initial maximization, it is modified for the original optimizer. However, when loading the logs, the random_state is not used and remains unchanged.consider the following code:
The random state exists to ensure that the same code executed twice can be made reproducible, not to align loaded optimizers, so I think this behaviour is fine. If you want the latter, you could manually reset/align all the states, which is however a bit messy:
As you can see, this does give you a consistent behaviour:
2.)
The bounds are mutate during
maximizeby the bounds transformer (that's in some sense entirely what the bounds transformer is supposed to). However, these mutated bounds are not stored in the logs (see point 0 as for why). This is also the reason why we can't callset_bounds.3.)
I'm not sure I understand what you're saying -- this is exactly the reason for point 2?
I hope this helps, don't hesitate to let me know if there are further questions.
Cheers,
Till
pawlissimo commentedon Jun 28, 2024
Hi @Till-M ,
Thx a lot for your time and suggestions! I spent 2 days to dive deeper and perform set of experiments + code analysis.
Based on my experiments, following code could work fine (moved core logic to
dump_optimizer_data()andload_optimizer_data():with 4 rows commented:

NOTE. I found ONE strange thing (check my comment at "# WARNING!"). Looks like there is something that I don't understand why GP's random state becomes changed at some point of time.
t-muser commentedon Jun 30, 2024
Hey @pawlissimo,
glad to hear you found a solution!
I'm honestly not entirely sure what's happening with the random state of the GP. As far as I can tell, the 4 lines you added should not do anything. Yet, I observe the same behaviour. For what it's worth, I'm pretty confident that this has nothing to do with this library and is more likely to be a problem of either sklearn or numpy.
Sorry I couldn't be of more help.
pawlissimo commentedon Jul 1, 2024
Hi @Till-M ,
Yes, you're right - there something strange inside GP that I couldn't understand after deeper analysis even. BTW was surprisingly difficult to find such workaround either.
But another core issue that my approach fixes is ability to continue optimization after some checkpoint. This is crucial in case of time/resource-consuming black-box functions and probably, this is only the option.
t-muser commentedon Jul 1, 2024
Glad to hear!
I will close this issue. Let us know if you need any other help. :)