Skip to content

Bounds Transformer doesn't work after loading the logs #486

Closed

Description

@pawlissimo

Bounds Transformer doesn't work after loading the logs
bayesian-optimization==1.5.0

High-level flow:

  1. Create `original_logger = JSONLogger(path="./original_logsr.json"), reset=True)
  2. Create original_bounds_transformer = SequentialDomainReductionTransformer()
  3. Create original_optimizer = BayesianOptimization(... bounds_transformer=original_bounds_transformer)
  4. Subscribe logger original_optimizer.subscribe(Events.OPTIMIZATION_STEP, original_logger )
  5. Run optimization original_optimizer .maximize(init_points=2, n_iter=10)
  6. Create new loaded_optimizer with new loaded_bounds_transformer in the same way and load_logs(loaded_optimizer, logs=""./original_logsr.json").
  7. Call maximize(n_iter=10) for both optimizers and compare their results + optimizers.
    You will see that loaded_optimizer has 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 unchanged

Expected 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.

Screenshots
image

Environment (please complete the following information):

  • OS: Windows 11
  • python Version 3.12.3
  • numpy 1.26.4
  • scipy 1.13.0
  • bayesian-optimization 1.5.0

Activity

  1. t-muser commented on Jun 26, 2024

    @t-muser
    Member

    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.

  2. pawlissimo commented on Jun 26, 2024

    @pawlissimo
    Author

    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() command

    P.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

  3. t-muser commented on Jun 26, 2024

    @t-muser
    Member

    There's two things that you need to do:

    1. Somehow restore the state of the bounds transformer, as it has some parameters (e.g. via pickle, as done below)
    2. Restore the bounds, which have already been shrunk (also e.g. via pickle)

    There are still some slight differences in the plots, which I assume come due to randomness.

    ## 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
    
    import pickle
    
    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)
    with open('orig_transformer.pkl', 'wb') as f:
        pickle.dump((orig_bounds_transformer, orig_optimizer.space.array_to_params(orig_optimizer.space.bounds)), f)
    
    with open('orig_transformer.pkl', 'rb') as f:
        loaded_bounds_transformer, loaded_bounds = pickle.load(f)
    
    # B. create new optimizer, transformer and load logs there
    loaded_optimizer = BayesianOptimization(
        f=ackley,
        pbounds=pbounds,
        verbose=0,
        random_state=1,
        bounds_transformer=SequentialDomainReductionTransformer()
    )
    
    load_logs(loaded_optimizer, logs="./orig_optimizer.json")
    loaded_optimizer._bounds_transformer = loaded_bounds_transformer
    loaded_optimizer.set_bounds(loaded_bounds)
    
    # 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 unchanged

    image

    @bwheelz36 Nonetheless, I think we should work towards proper serialization, there's really only so far one can push JSON logging (see also e.g. #478).

    @pawlissimo let me know if this helps :)

  4. pawlissimo commented on Jun 26, 2024

    @pawlissimo
    Author

    Hi @Till-M ,
    Thanks a lot for your suggestion. It really looks more promising now.

    I see a few things here:

    1. I fixed randomness as random_state=1 and 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 randomness
    2. Loading bounds to the already loaded optimizer like loaded_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 call set_bounds during load_logs automatically?
    3. My general understanding is that during load_logs() in addition to optimizer.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

  5. t-muser commented on Jun 26, 2024

    @t-muser
    Member

    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 the random_state mutates 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:

    from bayes_opt.util import ensure_rng
    
    state1 = ensure_rng(42)
    state2 = ensure_rng(42)
    
    print(state1.rand()) # something like this happens during the suggest step
    print(state1.rand()) # the mutated state is called again and returns a different value
    print(state2.rand()) # this is the loaded optimizer state, which was not mutated and returns the initial value

    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:

    ## 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, ensure_rng
    import matplotlib.pyplot as plt
    
    import pickle
    
    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)
    with open('orig_transformer.pkl', 'wb') as f:
        pickle.dump((orig_bounds_transformer, orig_optimizer.space.array_to_params(orig_optimizer.space.bounds)), f)
    
    with open('orig_transformer.pkl', 'rb') as f:
        loaded_bounds_transformer, loaded_bounds = pickle.load(f)
    
    # B. create new optimizer, transformer and load logs there
    loaded_optimizer = BayesianOptimization(
        f=ackley,
        pbounds=pbounds,
        verbose=0,
        random_state=1,
        bounds_transformer=SequentialDomainReductionTransformer()
    )
    
    load_logs(loaded_optimizer, logs="./orig_optimizer.json")
    loaded_optimizer._bounds_transformer = loaded_bounds_transformer
    loaded_optimizer.set_bounds(loaded_bounds)
    
    # Align random states
    orig_optimizer._random_state = ensure_rng(42)
    loaded_optimizer._random_state = ensure_rng(42)
    orig_optimizer._gp.set_params(random_state=ensure_rng(42))
    loaded_optimizer._gp.set_params(random_state=ensure_rng(42))
    orig_optimizer._space.random_state = ensure_rng(42)
    loaded_optimizer._space.random_state = ensure_rng(42)
    
    
    # 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 unchanged

    As you can see, this does give you a consistent behaviour:

    image

    2.)

    The bounds are mutate during maximize by 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 call set_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

  6. pawlissimo commented on Jun 28, 2024

    @pawlissimo
    Author

    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() and load_optimizer_data():

    # 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
    import pickle
    
    def dump_optimizer_data(optimizer, file_path):
        """
        Dumps content of bounds transformer and optimizer's bounds on disk.
        Such data may be loaded using load_bounds_transformer_data()
        
        Args:
            optimizer (BayesianOptimization): current optimizer (we will use its bounds for dumping)
            file_path (str): target file path
        """
        with open(file_path, 'wb') as f:
            pickle.dump(
                (optimizer._bounds_transformer,
                 optimizer.space.array_to_params(optimizer.space.bounds),
                 optimizer._random_state.get_state(legacy=False),
                 optimizer._space.random_state.get_state(legacy=False),
                 optimizer._gp.get_params()["random_state"].get_state(legacy=False)
                 ),
                f)
    
    def load_optimizer_data(optimizer, optimizer_log_path, optimizer_data_path):
        """
        Loads optimizer with its data (bounds transformer, random states etc.
        Args:
            optimizer (BayesianOptimization)
            optimizer_log_path (str): path to the optimizer logs
            optimizer_data_path (str): path to the optimizer data (dump)
        """
        load_logs(optimizer, logs=optimizer_log_path)
        
        try:
            with open(optimizer_data_path, 'rb') as f:
                loaded_transformer, loaded_bounds, rnd_state_main, rnd_state_space, rnd_state_gp = pickle.load(f)
        except FileNotFoundError:
            raise ValueError(f"File not found: {optimizer_data_path}")
        
        # we have to load bounds_transformer data AFTER loading logs into optimizer!
        optimizer._bounds_transformer = loaded_transformer
        optimizer.set_bounds(loaded_bounds)
        
        # update random states after logs loading to continue optimization from the same point
        optimizer._random_state.set_state(rnd_state_main)
        optimizer._space.random_state.set_state(rnd_state_space)
        random_state_gp = np.random.RandomState()
        random_state_gp.set_state(rnd_state_gp)    
        optimizer._gp.set_params(random_state=random_state_gp)
    
    
    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
    )
    
    
    # C. Dump and load optimizer's data
    dump_optimizer_data(orig_optimizer, './orig_optimizer.data')
    load_optimizer_data(loaded_optimizer,  optimizer_log_path='./orig_optimizer.json', optimizer_data_path='./orig_optimizer.data')
    loaded_bounds_transformer = loaded_optimizer._bounds_transformer
    
    # WARNING! Very strange thing, because GP's random state remains the same after below steps. BUT will NOT produce the same results if you skip below steps (you may try to comment following 4 rows to verify it) 
    original_random_state_gp = orig_optimizer._gp.get_params()["random_state"].get_state(legacy=False)
    random_state_gp = np.random.RandomState()
    random_state_gp.set_state(original_random_state_gp)
    orig_optimizer._gp.set_params(random_state=random_state_gp)
    
    
    # D. 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()

    image

    with 4 rows commented:
    image

    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.

  7. t-muser commented on Jun 30, 2024

    @t-muser
    Member

    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.

  8. pawlissimo commented on Jul 1, 2024

    @pawlissimo
    Author

    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.

  9. t-muser commented on Jul 1, 2024

    @t-muser
    Member

    Glad to hear!

    I will close this issue. Let us know if you need any other help. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions