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.

# Automatic differentiation through a circuit with condition

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!