Share parameters between different qnodes

Hi, I want to define 2 different qnodes q_1, q_2, and share parameters between them. For example, q_1 involves parameters a and b; q_2 involves parameters a and c.

While according to the definition of KerasLayer, only the shape of parameters is required:

qlayer = qml.qnn.KerasLayer(q1, weight_shapes, output_dim=d)

So I don’t know how to input and share parameters between different devices. Besides, the documentation says QnodeCollection can share all parameters in different qnodes. However, I just want to share some parameters, so QnodeCollection seems don’t work. Is it possible in Pennylane?

Hi @Linty! Welcome! :wave:

In PennyLane you can indeed create models where a parameter is shared among different qnodes. This is as simple as just passing the same parameter as an argument to both qnode definitions. Here’s a simple example I just wrote to illustrate the functionality:

import pennylane as qml
import numpy as np

dev = qml.device("default.qubit", wires=1)

@qml.qnode(dev)
def circuit1(x, y):
    qml.RY(x, wires=0)
    qml.RZ(y, wires=0)
    return qml.expval(qml.PauliX(0))

@qml.qnode(dev)
def circuit2(y, z):
    qml.RX(y, wires=0)
    qml.RZ(z, wires=0)
    return qml.expval(qml.PauliY(0))


def cost(x, y, z):
    return circuit1(x, y) + circuit2(y, z)

opt = qml.GradientDescentOptimizer(stepsize=0.1)

x = 0.1
y = 0.2
z = -0.1

for i in range(10):
    x, y, z = opt.step(cost, x, y, z)
    print(x, y, z)

This same idea should work no matter how you construct the qnode, including using as KerasLayer.

Hope that helps!

Juan Miguel

I think I know how to build my model now.
Thank you so much!!!

1 Like