Skip to content

Commit

Permalink
fix: Proper callback for CMA
Browse files Browse the repository at this point in the history
  • Loading branch information
andrea-pasquale committed Jun 5, 2024
1 parent cb87952 commit 0858afd
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 11 deletions.
18 changes: 14 additions & 4 deletions src/qibo/optimizers.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,10 +133,20 @@ def cmaes(loss, initial_parameters, args=(), callback=None, options=None):
"""
import cma

r = cma.fmin2(
loss, initial_parameters, 1.7, options=options, args=args, callback=callback
)
return r[1].result.fbest, r[1].result.xbest, r
es = cma.CMAEvolutionStrategy(initial_parameters, sigma0=1.7, inopts=options)

if callback is not None:
while not es.stop():
solutions = es.ask()
objective_values = [loss(x, *args) for x in solutions]
for solution in solutions:
callback(solution)
es.tell(solutions, objective_values)
es.logger.add()
else:
es.optimize(loss, args=args)

return es.result.fbest, es.result.xbest, es.result


def newtonian(
Expand Down
9 changes: 2 additions & 7 deletions tests/test_models_variational.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def myloss(parameters, circuit, target):
("BFGS", {"maxiter": 1}, False, "vqe_bfgs.out"),
("parallel_L-BFGS-B", {"maxiter": 1}, True, None),
("parallel_L-BFGS-B", {"maxiter": 1}, False, None),
("cma", {"maxfevals": 2}, False, None),
("cma", {"maxiter": 1}, False, None),
("sgd", {"nepochs": 5}, False, None),
("sgd", {"nepochs": 5}, True, None),
]
Expand Down Expand Up @@ -132,10 +132,6 @@ def test_vqe(backend, method, options, compile, filename):
loss_values = []

def callback(parameters, loss_values=loss_values, vqe=v):
# cma callback takes as input a CMAEvolutionStrategy class
# which keeps track of the best current solution into its .best.x
if method == "cma":
parameters = parameters.best.x
vqe.circuit.set_parameters(parameters)
loss_values.append(vqe.hamiltonian.expectation(vqe.circuit().state()))

Expand All @@ -153,7 +149,6 @@ def callback(parameters, loss_values=loss_values, vqe=v):
shutil.rmtree("outcmaes")
if filename is not None:
assert_regression_fixture(backend, params, filename)

assert best == min(loss_values)

# test energy fluctuation
Expand Down Expand Up @@ -316,7 +311,7 @@ def __call__(self, x):
test_names = "method,options,compile,filename"
test_values = [
("BFGS", {"maxiter": 1}, False, "aavqe_bfgs.out"),
("cma", {"maxfevals": 2}, False, None),
("cma", {"maxiter": 1}, False, None),
("parallel_L-BFGS-B", {"maxiter": 1}, False, None),
]

Expand Down

0 comments on commit 0858afd

Please sign in to comment.