Skip to content

Commit

Permalink
ready for qpu
Browse files Browse the repository at this point in the history
  • Loading branch information
acse-b99192e1 committed Aug 9, 2023
1 parent 6461242 commit c17681f
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 19 deletions.
5 changes: 2 additions & 3 deletions src/qibo/derivative.py
Original file line number Diff line number Diff line change
Expand Up @@ -521,13 +521,12 @@ def execute_circuit(
initial_state=None,
cdr_params=None,
calibration=None,
precise=True,
precise=False,
):
"""Probabilistic circuit execution with possibilities for error mitigation"""
if precise:
state = c().state()
res = obs.expectation(state)
print(res)
return res

# retrieve state
Expand Down Expand Up @@ -623,7 +622,7 @@ def generate_fubini(
ps = scale_factors[p]
ts = scale_factors[t]
val = ps * ts * (result - result**2)
fubini[p, t] = val if val > 1e-3 else 1e-3
fubini[p, t] = val if val > 1e-6 else 1e-6

return fubini

Expand Down
24 changes: 15 additions & 9 deletions src/qibo/optimizers.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def set_options(self, updates):
self.options.update(updates)

def fun(self, x):
val = self.loss_function(x, *self.args)
val = self.loss_function(x, self.args)
self.etime = time.time()
duration = self.etime - self.ftime
self.ftime = self.etime
Expand Down Expand Up @@ -173,6 +173,8 @@ def __init__(
)

def _get_paramInit(self):
"""Retrieve parameter values or objects directly from gates"""

params = []
for gate in self._circuit.queue:
if isinstance(gate, gates._Rn_):
Expand All @@ -184,9 +186,15 @@ def _get_paramInit(self):
return params

def _get_params(self, feature=None):
"""Creates an array with the trainable parameters"""
"""Retrieve gate parameters
Args:
feature: input feature if embedded in Parameter lambda function"""

# for array
if isinstance(self.paramInputs, np.ndarray):
return self.paramInputs

# for Parameter objects
else:
params = []
count = 0
Expand Down Expand Up @@ -232,7 +240,6 @@ def run_circuit(self, feature):
# set parameters
parameters = self._get_params(feature=feature)
self._circuit.set_parameters(parameters)
print("RUN", parameters, self.hamiltonian[0].matrix)

# run circuit
if isinstance(self.hamiltonian, list):
Expand Down Expand Up @@ -332,8 +339,7 @@ def dloss(self, features, labels):
) # separate pull request

# gradient average
print("HERE", results, labels)
loss = self.loss_function(results, labels, *self.args)
loss = self.loss_function(results, labels, self.args)
loss_gradients = circ_grads

# Fubini-Study Metric renormalisation
Expand Down Expand Up @@ -371,11 +377,10 @@ def AdamDescent(
Returns: np.float new values of momentum and velocity
"""
grads, loss = self.dloss(features, labels)
print("after", self.params, self.paramInputs)

if self.save:
self.file.write(
f"Grads (absolute value: {np.linalg.norm(grads)}): {grads.tolist()}\nParams {self.params}\n"
f"Grads (absolute value: {np.linalg.norm(grads)}): {grads.tolist()}\nParams {self.params.tolist()}\n"
)

if self.options["adam"]:
Expand Down Expand Up @@ -480,7 +485,8 @@ def sgd(self, options):
plot(self, self.features, self.labels, epoch, this_loss)

if self.save:
self.file.write(f"Params {self.params}\n")
self.file.write(f"Params {self.params.tolist()}\n")
self.file.write(f"Best J: {min(losses)}\n")
self.cleanup()

return losses
Expand Down Expand Up @@ -734,7 +740,7 @@ def plot(optimizer, xtrain, ytrain, epoch, loss):
cols = yprediction.shape[1]
# new plot
fig, ax = plt.subplots(nrows=1, ncols=cols, figsize=(8, 6))
# fig.suptitle(f"Epoch {epoch}, J={loss[0]:.4}")
fig.suptitle(f"Epoch {epoch}, J={loss:.4}")
# ax.set(title=f'$\chi^2 = $ {chi2:.2f}', xlabel='x', ylabel='PDF',
# xscale='log')

Expand Down
31 changes: 24 additions & 7 deletions tests/test_derivative.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import math

import numpy as np
import pennylane as qml
import pytest
Expand Down Expand Up @@ -30,19 +32,19 @@ def ansatz_pdf(layers, params, feature):
for i in range(layers):
qml.Hadamard(wires=i)

qml.RZ(params[12 * i + 0] * feature, wires=i)
qml.RZ(params[12 * i + 0] * math.log(feature), wires=i)
qml.RZ(params[12 * i + 1], wires=i)

qml.RY(params[12 * i + 2] * feature, wires=i)
qml.RY(params[12 * i + 3], wires=i)

qml.RZ(params[12 * i + 4] * feature, wires=i)
qml.RZ(params[12 * i + 4] * math.log(feature), wires=i)
qml.RZ(params[12 * i + 5], wires=i)

qml.RY(params[12 * i + 6] * feature, wires=i)
qml.RY(params[12 * i + 7], wires=i)

qml.RZ(params[12 * i + 8] * feature, wires=i)
qml.RZ(params[12 * i + 8] * math.log(feature), wires=i)
qml.RZ(params[12 * i + 9], wires=i)

qml.RY(params[12 * i + 10] * feature, wires=i)
Expand All @@ -65,9 +67,21 @@ def ansatz(layers, nqubits):
c.add(qibo.gates.H(q=qubit))

for _ in range(layers):
c.add(
qibo.gates.RZ(
q=qubit,
theta=Parameter(
lambda x, th1: th1 * sp.log(x), [0.1], featurep=[0.1]
),
)
)
c.add(qibo.gates.RZ(q=qubit, theta=Parameter(lambda th1: th1, [0.1])))
c.add(qibo.gates.RZ(q=qubit, theta=Parameter(lambda th1: th1, [0.1])))
c.add(qibo.gates.RY(q=qubit, theta=Parameter(lambda th1: th1, [0.1])))
c.add(
qibo.gates.RY(
q=qubit,
theta=Parameter(lambda x, th1: th1 * x, [0.1], featurep=[0.1]),
)
)
c.add(qibo.gates.RY(q=qubit, theta=Parameter(lambda th1: th1, [0.1])))

c.add(qibo.gates.M(qubit))
Expand Down Expand Up @@ -433,8 +447,10 @@ def test_natural_gradient():

assert np.allclose(optimiser.params, params)

metric_tensor = qml.metric_tensor(ansatz_pdf, approx="diag")(1, params, 1.0)
metric_tensor = qml.metric_tensor(ansatz_pdf, approx="diag")(1, params, 0.1)
print(metric_tensor)

print(fubini)
assert np.allclose(fubini, metric_tensor)
assert np.allclose(fubini2, metric_tensor)

Expand Down Expand Up @@ -481,4 +497,5 @@ def test_multiqubit_natural_gradient():
# test_multiqubit_natural_gradient()
# test_parameter()
# test_psr_commuting_gate()
test_spsr_non_commuting_gates()
# test_spsr_non_commuting_gates()
test_natural_gradient()

0 comments on commit c17681f

Please sign in to comment.