Two quantum circuits containing parametric gates. The probabilities of the states in circuit 1 were measured. After some operations (due to I need nonlinear effects for machine learning ), the data was sent to circuit 2. Define the cost function, the results shown that only the parameters in circuit 2 were adjusted. The parameters in circuit 1 were belong to Autograd, however, the values were unchanged. I believe that the parameters in circuit 1 are differentiable. Is it possible to adjust the parameters in circuits and 1 and 2 simultaneously?
The following was simplified example:
import pennylane as qml
from pennylane import numpy as np
I tested the following script, and appeared the error message “State preparation operation QubitStateVector must occur prior to any quantum operations.”
Mean that the input of circuit 2 can not be from the output of circuit 1 or any quantum operations in Pennylane.
Is there any solution?
import pennylane as qml
from pennylane import numpy as np
dev=qml.device(“default.qubit”,wires=1)
@qml.qnode(dev)
def circ():
qml.RY(0,wires=0)
qml.QubitStateVector([0,1],wires=0)
qml.RY(0,wires=0)
pro=qml.probs(wires=[0])
return pro
The parameters in circuits 1 and 2 can be trained simultaneously in following script. However, what I want is to minimize the output of circuit 2, not the output of circuit 1 plus circuit 2.
import pennylane as qml
from pennylane import numpy as np
@qml.qnode(dev1)
def circ1(params):
qml.RY(params[0],wires=0)
pro=qml.probs(wires=[0])
return pro
@qml.qnode(dev2)
def circ2(params):
qml.templates.MottonenStatePreparation(state,wires=[0])
qml.RY(params[1],wires=0)
pro=qml.probs(wires=[0])
return pro
def Pro_State_Con(pro):
state=
for i in range (len(pro)):
state.append(qml.math.toarray(np.sqrt(pro[i])))
return state
def cost(params):
global state
pro=circ1(params)
state=Pro_State_Con(pro)
pro2=circ2(params)
print(pro[0],pro2[0],pro[0]+pro2[0])
return pro[1]+pro2[0]
opt=qml.GradientDescentOptimizer(stepsize=0.3)
for i in range(10):
params=opt.step(cost,params)
print(params)
I think that the problem is solved. Measure the probability of circuit 1, do some calculations, and input to the circuit 2. The parameters in circuits 1 and 2 can be trained simultaneously using Pennylane (see the appendix). The key point is “Autograd ArrayBox”.
I’m sorry we took long to answer, we were out on holidays.
I’m glad you could solve your problem.
The reason why you were getting the error “State preparation operation QubitStateVector must occur prior to any quantum operations” is because in your “circ” circuit you were first performing a Y rotation qml.RY(0,wires=0) and then you were preparing a state using qml.QubitStateVector([0,1],wires=0). If you want to prepare a state using QubitStateVector it needs to be the first thing you do in your circuit.
Please let me know if you still have any unresolved questions!