Finding density matrix for mutiple qubit for MBQC

Hi, I have been working with PennyLane for quite a while, but I recently faced an issue when trying to view the density matrix for all three qubits. I’m getting an error, even though it was working fine before.

# mbqc_dev = qml.device("default.qubit", wires=3)

# Define the QNode
@qml.qnode(mbqc_dev, interface="autograd")
def T_MBQC(input_state):
    qml.StatePrep(input_state, wires=0)


    # Create cluster state
    qml.Hadamard(wires=1)
    qml.Hadamard(wires=2)
    qml.CZ(wires=[0,1])
    qml.CZ(wires=[1,2])


    #measurement bases
    qml.RZ(theta,wires=0)
    qml.Hadamard(wires=0)
    m1 = qml.measure(wires=0)

    qml.Hadamard(wires=1)
    m2 = qml.measure(wires=1)

    qml.cond(m1 == 1,qml.PauliZ)(wires=2)
    qml.cond(m2 == 1, qml.PauliX)(wires=2)

    return qml.density_matrix(wires=[1,2])

Hi @Rayhan740, welcome back to the Forum!

The issue here is not with the density matrix, the problem is with your mid circuit measurements.

When using default.qubit the QNode will apply the defer_measurements() transform. I know it’s a bit hidden but in the docs for this transform you’ll see a note that says:

Devices that inherit from QubitDevice must be initialized with an additional wire for each mid-circuit measurement after which the measured wire is reused or reset for defer_measurements to transform the quantum tape correctly.

In this case the first mid-circuit measurement doesn’t cause any problem because after the measurement wire 0 is never used again (not even for the final readout measurement).
However, after the second mid-circuit-measurement, which occurs on wire 1, we do have a readout measurement.

All you need to avoid this issue now is set the device with 4 wires, or even better, no wires at all! If you use default.qubit without setting the number of wires it will automatically detect the number of wires it needs.

Option 1: mbqc_dev = qml.device("default.qubit", wires=4)
Option 2: mbqc_dev = qml.device("default.qubit")

Note: when you draw the circuit you will only see the wires that have actual gates on it, but as you now know, the circuit actually requires one extra wire per mid-circuit-measurement, unless the wire where we performed the measurement is left unused.

I hope this helps!