I want to simulate an optical cavity interacting with a two-level system (a qubit) that depends on some parameters that I then want to optimize. My knowledge on Pennylane/StrawberryFields is very limited, so this is probably a very basic question.
I understand that I should instantiate two devices:
with which I should then create one (or two?) QNode(s). The qubit is prepared in a state that depends on some parameters. Then the qubit and the cavity interact according to a Jaynes-Cummings interaction for some time, after which the state of the cavity depends on the parameters with which the qubit was prepared. After this interaction, the qubit gets traced out and a loss function gets computed for the cavity.
My question is how to set up this optimization problem in such a way that I will be able to take gradients of a loss function in the cavity side that implicitly depends on the parameters of the qubit. Any help will be appreciated.
I’m not sure I understand the nuances of your problem. But, if there are any parameters in your circuit that you want to differentiate over, you can “flag” them to PennyLane as differentiable with requires_grad = True. For parameters that you don’t want to differentiate over, you would specify False instead. Here’s an example of a circuit with one qubit and two rotation gates, one of which I want to flag in order to take derivatives of.
import pennylane as qml
from pennylane import numpy as np
dev = qml.device("default.qubit", wires=1)
@qml.qnode(dev)
def circuit(angle1, angle2):
qml.RX(angle1, wires=0)
qml.RY(angle2, wires=0)
return qml.expval(qml.PauliX(0))
angle1 = np.array(np.pi/3, requires_grad=True) # Differentiate w.r.t. this angle
angle2 = np.array(np.pi/4, requires_grad=False) # will remain constant
angles = [angle1, angle2]
opt = qml.GradientDescentOptimizer(0.1)
for _ in range(3):
angles, loss = opt.step_and_cost(circuit, *angles)
print(angles)
'''output:
0.29.1
[tensor(1.10843479, requires_grad=True), tensor(0.78539816, requires_grad=False)]
[tensor(1.17172096, requires_grad=True), tensor(0.78539816, requires_grad=False)]
[tensor(1.23687525, requires_grad=True), tensor(0.78539816, requires_grad=False)]
'''
Note that angle1 changes, while angle2 does not!
I hope this helps, but if it doesn’t, please respond back with more questions!
Hi @isaacdevlugt ! Thanks for your answer
Unfortunately this wasn’t really my question. My question is more whether there is support for a qml.device that includes both a cavity (i.e. a quantum harmonic oscillator Hilbert space) and qubits, or whether there is a way to combine two different devices into a single device
@jolle ah! Thank you for clarifying . Unfortunately, no — there isn’t a way to do this in PennyLane currently. We are slowly extending the qubit framework to qutrits/qudits, but heterogeneous Hilbert spaces need some careful thought!