It is possible to do automatic differentiation through a circuit with conditional gates. I mean variationally optimize the circuit with gates that are applied based on themed-circuit measurement.

Hi @REZA_HAGHSHENAS, welcome to the forum!

You can in fact differentiate circuits with mid-circuit measurements and conditional operations. You can learn more about this on our **Measurements** section of the documentation and on the documentation for the **cond()** function. Performing true mid-circuit measurements and conditional operations is dependent on the quantum hardware and PennyLane device capabilities though.

I hope this helps and please let us know if you run into any problems while implementing this!

Thanks for the reply. Is there any explicit example of a differentiate circuits with mid-circuit measurements and its performance?

Hi @REZA_HAGHSHENAS,

We don’t have a performance benchmark for this but the following is an example which shows differentiation for a circuit with conditional measurements. In this case I have used the autograd interface and the parameter-shift differentiation method but you can remove these 2 arguments and the differentiation still works.

```
import pennylane as qml
from pennylane import numpy as np
dev = qml.device('default.qubit',wires=2)
@qml.qnode(dev,interface='autograd',diff_method='parameter-shift')
@qml.defer_measurements
def qnode_conditional_op_on_zero(x, y):
qml.RY(x, wires=0)
qml.CNOT(wires=[0, 1])
m_0 = qml.measure(1)
qml.cond(m_0 == 0, qml.RY)(y, wires=0)
return qml.expval(qml.PauliZ(0))
pars = np.array([0.643, 0.246],requires_grad=True)
g = qml.grad(qnode_conditional_op_on_zero)
g(*pars)
```

As you can see at the end we get the gradient function **g** and we calculate the gradient for a set of parameters.

Please let me know if this helps!

That was quite helpful. I would like to know how to do a simple example of doing variational optimization by having mid-circuit measurement and conditional gates. I mean is it straightforward to do that and update parameters?

Is there any quantum tensor network example: my question is the pennyLane take into account light cone and smart contraction order?

Hello @REZA_HAGHSHENAS,

I would like to know how to do a simple example of doing variational optimization by having mid-circuit measurement and conditional gates.

The example that @CatalinaAlbornoz commented in this thread is a good example that just needs to be generalized to a problem that you’re trying to solve . Her code example just outlined taking the gradient of a quantum function containing a conditional mid-circuit measurement. To generalize it to a full-on optimization problem, check out this demo for inspiration!

Is there any quantum tensor network example:

Definitely! PennyLane has a tensor network ansatz template .