Aha lucky I asked! If I understand correctly, you want to draw single samples from an observable measurement. Of course, simulating the circuit 1000 times and using shots=1
is really wasteful. I doubt that any solution (besides maybe heavy parallelisation) will help here, instead, PennyLane should only simulate the circuit once.
Unfortunately, you are a victim here of our lower priority treatment of CV devices. I wonder if you could open an issue with a feature request on the pennylane-SF repo, if we see demand then it is easier to justify distributing resources!
For some context, in qubit-based devices what you want is a breeze:
You can either just use the sample()
measurement type:
n_wires = 3
n_shot = 1000
dev = qml.device("default.qubit", wires=n_wires, shots=1000)
@qml.qnode(dev)
def qnn():
qml.Hadamard(0)
return [qml.sample(qml.PauliX(i)) for i in range(n_wires)]
print(qnn())
# [[ 1 1 1 ... 1 1 1]
# [ 1 -1 1 ... 1 1 -1]
# [-1 -1 -1 ... 1 1 1]]
Note that, if I remember correctly, the samples are not trainable though, since gradients of samples are ill defined.
This leads to the second idea, which uses the fact that gradients of 1-shot estimated observables are well-defined (the gradients are just very crude estimates of the real gradients). Your code on a qubit device could be rewritten using shots batching, which simulates the circuit once, and instead of returning one set of measurement results it returns 1000 sets. Each set is still interpreted as a single-shot estimation of an expectation:
n_wires = 3
dev = qml.device("default.qubit", wires=n_wires, shots=[(1, 1000)])
# can also use `shots=[1]*1000`, but the above syntax is a bit faster for technical reasons
@qml.qnode(dev)
def qnn():
qml.Hadamard(0)
return [qml.expval(qml.PauliX(i)) for i in range(n_wires)]
print(qnn())
# [[ 1. 1. 1.]
# [ 1. 1. -1.]
# [ 1. 1. -1.]
# ...
# [ 1. 1. -1.]
# [ 1. -1. 1.]
# [ 1. 1. 1.]]
The difference between the two are subtle and very conceptual, but the latter should be trainable and resembles your example more.
I am not sure how easy the second one would be to support on CV devices, but if there is demand we will try it!