Unexpected behaviour with qml.QubitUnitary

Hi @ARO-GZ ,

Welcome to the Forum and thank you for your excellent post! The way you wrote it helped me a lot to find the issue.

I’ll start with a short answer and the fix for your problem, followed by a detailed explanation.

Short answer:
You’re accidentally adding gates to your circuit in Case II.
You can fix it with one line of code!
with qml.QueuingManager.stop_recording():

See how to use it below:

dev = qml.device('default.qubit',wires=5)

@qml.qnode(dev)
def EM_circuit():
    with qml.QueuingManager.stop_recording():
      U = embedding_matrix(image_test,3+2)
    qml.QubitUnitary(U,wires=range(5))
    return qml.state()

print(EM_circuit())

Detailed explanation:

PennyLane works by queuing up all quantum operations in a tape that then runs them on the device of your choice. This is what allows you to create sub-circuits outside of your QNode (such as layers) and then easily add them to your circuit.

Example: In the example below, I’m creating a function called layer which allows me to define the layer once and then call it within my QNode as many times as I want.

In this example we get the layers of Hadamard gates properly added to the circuit.

n_wires = 5
dev = qml.device('default.qubit',wires=n_wires)

def layer(n_wires):
  for w in range(n_wires):
    qml.Hadamard(wires=w)

@qml.qnode(dev)
def circuit(n_layers):
    for i in range(n_layers):
      layer(n_wires)
    return qml.probs()

n_layers = 3
qml.draw_mpl(circuit, style='pennylane')(n_layers);

The issue in your case is that you have qml.RY within your functions R_R, R_G, and R_B so they’re getting added to the circuit without you realizing it.

I hope this helps you move along with your project and prevent this from causing issues in your code again!

PS: we’ve now released version v0.37.0 of PennyLane! I recommend that you always keep your code updated to run with the latest version :smiley: