Circuit Building vs Circuit Eval

In many other quantum languages(qiskit, cirq, etc) the circuit building and eval/simulation parts are separate.

This allows me as a user to define a large circuit only once, and simulate it multiple times.

It seems to me there is no way to achieve this in Pennylane. The common way of defining and simulating a circuit happen together.
In particular, running the code below will result in printing “Building the Circuit” 20 times.
Is there a way to avoid that?

import pennylane as qml
n = 10

dev = qml.device('lightning.qubit', wires=n, shots=None)
@qml.qnode(dev, diff_method='finite-diff')
def circuit():
	print("Building the Circuit")
	for i in range(n):
		qml.PauliX(wires=i)
		qml.PauliZ(wires=i)
	return qml.state()

for i in range(20):
	res = circuit()

Hey @Hayk_Tepanyan , I know this is just a toy example, but I think what you’re probably looking for is parameter broadcasting, which lets you iterate through a list of parameters inside of a circuit. :slight_smile:

For example, if you want to deal with a circuit that runs a few different parameters inside qml.RX (in addition to your original example), you could do this:

import pennylane as qml
from pennylane import broadcast
import numpy as np

n = 10
total_wires=list(range(n))
x = np.array([np.pi/9, np.pi/6, np.pi/3])

@qml.qnode(dev, diff_method='finite-diff')
def circuit():
    broadcast(unitary=qml.PauliX, pattern='single', wires=total_wires)
    broadcast(unitary=qml.PauliZ, pattern='single', wires=total_wires)
    qml.RX(x, wires=0)
    return qml.state()

Then you don’t have to fiddle with external for loops and you save on execution, too!
(I also shoved your iteration within the circuit into qml.broadcast. :wink:)

You can find the details on parameter broadcasting in the QNode documentation. Any chance this already helps? :slight_smile:

2 Likes