Code works in some simulator and not working in others

Hi,

import pennylane as qml
from pennylane import numpy as np

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

def custom_observable(size):
    random_meas = torch.rand(size = size)
    obser = [a * qml.PauliX(0) + b * qml.PauliY(0) + c * qml.PauliZ(0) for a, b, c in random_meas]
    return [qml.expval(i) for i in obser]

@qml.qnode(dev)
def circuit(params):
    qml.RX(params[0], wires=0)
    qml.RY(params[1], wires=0)
    qml.RZ(params[2], wires=0)
    return custom_observable(size = (512, 3))

params = np.array([0.1, 0.2, 0.3, 1.0, 0.5, -0.5])

result = circuit(params)

print(len(result))

The code above works with simulator default.qubit but does not work in default.qubit.torch for some reason. Could someone check it for me? I think it is some bugs in the simulator. I prefer to use default.qubit.torch here as it runs the fastest among all simulators, but for some reason it does not work in this case.

Thanks,
Shuteng

Hi @Daniel_Wang,

I would recommend avoiding using default.qubit.torch. Instead it’s better to set interface='torch' when you create the QNode.

@qml.qnode(dev, interface='torch')
def circuit(params):
...

Also there are some important things to note here.

When you use NumPy imported from PennyLane you’re actually using Autograd which is another interface supported by PennyLane. So with your code PennyLane gets confused about whether it should use Autograd or Torch. To fix this you should do two things:

  1. All of your data and weights should be Torch tensors.
params = torch.tensor([0.1, 0.2, 0.3, 1.0, 0.5, -0.5], requires_grad=True)
  1. As much as possible all math should use methods from Torch, eg: torch.abs(circuit4(phi, theta) - 0.5)**2
  2. If you need to use NumPy (for example to calculate \pi) make sure to use vanilla numpy instead of PennyLane NumPy. Eg:
import numpy as np
np.pi

Make sure to check out our documentation about the Torch interface to learn more about it!

Specifically for your code the following should work:

import pennylane as qml
import torch

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

def custom_observable(size):
    random_meas = torch.rand(size = size)
    obser = [a * qml.PauliX(0) + b * qml.PauliY(0) + c * qml.PauliZ(0) for a, b, c in random_meas]
    return [qml.expval(i) for i in obser]

@qml.qnode(dev, interface='torch')
def circuit(params):
    qml.RX(params[0], wires=0)
    qml.RY(params[1], wires=0)
    qml.RZ(params[2], wires=0)
    return custom_observable(size = (512, 3))

params = torch.tensor([0.1, 0.2, 0.3, 1.0, 0.5, -0.5], requires_grad=True)

result = circuit(params)

print(len(result))

I hope this helps you!

One additional suggestion: if you want to use over 15 qubits you will see a performance improvement when using lightning.qubit instead of default.qubit.