Skip to content

Commit

Permalink
feat: enabling sgd with and without shotnoise
Browse files Browse the repository at this point in the history
  • Loading branch information
MatteoRobbiati committed May 27, 2024
1 parent f9217e1 commit 0a9614d
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 35 deletions.
33 changes: 12 additions & 21 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,10 @@ def main(args):
qibo.set_backend(backend=args.backend)
args.platform = GlobalBackend().platform

if args.optimizer == "sgd":
options = {
"learning_rate": 0.1,
"nmessage": 1,
"nepochs": 100,
}
if args.optimizer_options is None:
opt_options = {}
else:
options = {}
opt_options = json.loads(args.optimizer_options)

# setup the results folder
logging.info("Set VQE")
Expand Down Expand Up @@ -113,14 +109,14 @@ def main(args):
niterations=args.boost_frequency,
nmessage=1,
loss=loss,
accuracy=args.accuracy,
training_options=options,
training_options=opt_options,
)
# append results to global lists
params_history[b] = np.array(partial_params_history)
loss_history[b] = np.array(partial_loss_history)
grads_history[b] = np.array(partial_grads_history)
fluctuations[b] = np.array(partial_fluctuations)
# this works with scipy.optimize.minimize only
if args.optimizer not in ["sgd", "cma"]:
fun_eval.append(int(partial_results[2].nfev))

Expand Down Expand Up @@ -178,32 +174,27 @@ def main(args):
initial_parameters = np.zeros(len(initial_parameters))
circ.set_parameters(initial_parameters)

if args.accuracy is None:
accuracy = "none"
else:
accuracy = str(args.accuracy)
best_loss = min(np.min(array) for array in loss_history.values())

opt_results = partial_results[2]
# save final results
output_dict = vars(args)
output_dict.update(
{
"true_ground_energy": target_energy,
"target_accuracy": str(accuracy),
"feval": list(fun_eval),
"energy": float(vqe.hamiltonian.expectation(zero_state)),
"fluctuations": float(vqe.hamiltonian.energy_fluctuation(zero_state)),
"reached_accuracy": float(np.abs(target_energy - best_loss)),
}
)
# this works only with scipy.optimize.minimize
if args.optimizer not in ["sgd", "cma"]:
output_dict.update(
{
"best_loss": float(opt_results.fun),
"success": bool(opt_results.success),
"message": opt_results.message,
"reached_accuracy": float(
np.abs(target_energy - float(opt_results.fun))
),
"feval": list(fun_eval),
}
)
Expand Down Expand Up @@ -265,12 +256,12 @@ def main(args):
"--optimizer", default="Powell", type=str, help="Optimizer used by VQE"
)
parser.add_argument(
"--tol", default=TOL, type=float, help="Absolute precision to stop VQE training"
"--optimizer_options",
type=str,
help="Options to customize the optimizer training",
)
parser.add_argument(
"--accuracy",
type=float,
help="Accuracy to be detected during the VQE training.",
"--tol", default=TOL, type=float, help="Absolute precision to stop VQE training"
)
parser.add_argument(
"--nqubits", default=6, type=int, help="Number of qubits for Hamiltonian / VQE"
Expand Down
24 changes: 24 additions & 0 deletions run_sgd.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#!/bin/bash
#SBATCH --job-name=boostvqe
#SBATCH --output=boostvqe.log

NQUBITS=4
NLAYERS=2

DBI_STEPS=2
NBOOST=2
BOOST_FREQUENCY=10

NSHOTS=10000
TOL=1e-8
ACC=0.5

OPTIMIZER="sgd"
BACKEND="tensorflow"
OPTIMIZER_OPTIONS="{ \"optimizer\": \"Adagrad\", \"learning_rate\": 0.1, \"nmessage\": 1, \"nepochs\": $BOOST_FREQUENCY }"

python main.py --nqubits $NQUBITS --nlayers $NLAYERS --optimizer $OPTIMIZER \
--output_folder results/debugging --backend $BACKEND --tol $TOL \
--dbi_step $DBI_STEPS --seed 42 \
--boost_frequency $BOOST_FREQUENCY --nboost $NBOOST \
--optimizer_options "$OPTIMIZER_OPTIONS"
3 changes: 2 additions & 1 deletion src/boostvqe/training_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def vqe_loss(params, circuit, hamiltonian, nshots=None, delta=0.5):
circ = circuit.copy(deep=True)
circ.set_parameters(params)

if isinstance(hamiltonian.backend, TensorflowBackend):
if isinstance(hamiltonian.backend, TensorflowBackend) and nshots is not None:
expectation_value = _exp_with_tf(circ, hamiltonian, nshots, delta)
elif nshots is None:
expectation_value = _exact(circ, hamiltonian)
Expand Down Expand Up @@ -76,6 +76,7 @@ def _exp_with_tf(circuit, hamiltonian, nshots=None, delta=0.5):
@tf.custom_gradient
def _expectation(params):
def grad(upstream):
print("with psr")
gradients = []
for p in range(nparams):
gradients.append(
Expand Down
13 changes: 0 additions & 13 deletions src/boostvqe/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ def train_vqe(
loss,
niterations=None,
nmessage=1,
accuracy=None,
training_options=None,
):
"""Helper function which trains the VQE according to `circ` and `ham`."""
Expand All @@ -92,11 +91,7 @@ def train_vqe(
else:
options = training_options

if accuracy is not None:
accuracy_tracker = True

circ.set_parameters(initial_parameters)
target_energy = np.real(np.min(np.asarray(ham.eigenvalues())))

vqe = VQE(
circuit=circ,
Expand Down Expand Up @@ -133,14 +128,6 @@ def callbacks(
if niterations is not None and iteration_count % nmessage == 0:
logging.info(f"Optimization iteration {iteration_count}/{niterations}")

if accuracy is not None:
if (
accuracy_tracker
and np.abs(target_energy - np.min(loss_list)) <= accuracy
):
accuracy_tracker = False
logging.info("Target accuracy is reaced here.")

callbacks(initial_parameters)
logging.info("Minimize the energy")

Expand Down

0 comments on commit 0a9614d

Please sign in to comment.