Gradient of circuit with `QubitUnitary`

Hi, I’ve been looking into some quantum machine learning examples and I would like to train on an arbitrary unitary, but an error is raised with QubitUnitary. Is QubitUnitary non-differentiable? :thinking:

For simplicity, including a minimal non-working example.

import pennylane as qml
from pennylane import numpy as np

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

U = np.array([[0, 1], [1, 0]], dtype=np.float64)

@qml.qnode(dev)
def c(U):
    qml.QubitUnitary(U, wires=0)
    return qml.expval(qml.PauliZ(0))

qml.grad(c)(U)

Hello @sam_allen! Thank you for your question.

QubitUnitary was initially created to allow non-differentiable numeric matrices only.

I will ask someone from the team to take a deeper look at this

Hi @sam_allen,

Thanks for catching that! As @Togan mentioned, the differentiability of qml.QubitUnitary may not be guaranteed for all devices. In the code that you’ve posted, the native Autograd version of the default.qubit device (default.qubit.autograd) will be used, so the differentiation of qml.QubitUnitary would be possible.

To allow your code to work, a small addition to PennyLane will be required. This can be found in the following branch: https://github.com/PennyLaneAI/pennylane/pull/1445.

Until it is incorporated, also the the ArbitraryUnitary template could be used.

Hi @Togan and @antalszava, thank you both for the info! Using the linked branch solved my problem. Cheers!

1 Like