Question about torch autograd of a circuit returns a state

Hi everyone,
I am using Pennylane to run a quantum-classical hybrid structure, the quantum circuit returns a reduced density matrix, the quantum circuit is built by the following code:

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

def qnode(inputs, weights):
    qml.templates.AmplitudeEmbedding(features=inputs, wires=range(n_qubits), normalize=False)
    for i in range(n_qubits):
    qml.templates.BasicEntanglerLayers(weights, wires=range(n_qubits), rotation=qml.RY)
    return qml.density_matrix(wires=range(N_encode))

Then I transfer qnode to a PyTorch layer by:

qlayer = qml.qnn.TorchLayer(qnode, weight_shapes)

The output of qlayer is a density matrix, the matrix elements are flatterned and sent to a PyTorch Linear layer. After the network is built, the backward() raises an error:

RuntimeError: The jacobian method does not support circuits that return the state

Can anyone help me?

Hi @Xiao_Liang!

Currently, AmplitudeEmbedding does not support tape-mode, so I’m curious how you got it working that far! Could you post a small minimal code example, showing how you constructed the PyTorch model, and your inputs?

Regarding QNodes that return density matrices, unfortunately they do not support differentiation at the moment using PyTorch, hence the error you are currently getting. We are working to support this via two different pathways, however:

  1. By building a simulator that uses PyTorch as a backpropagation backend, we will be able to support differentiating such QNodes using backpropagation. See

  2. We also have a pathway towards supporting differentiating states on non-backpropagation compatible backends, by adding support for state differentiation gradient recipes.

In the meantime, you could try other return types (such as qml.probs()), and other embeddings (such as qml.templates.AngleEmbedding) that do support differentiation.

Hi, I commented the normalization part in the AmplitudeEmbedding source code, then the code does not raise Errors. Inputs are torch tensors.

Thanks for the reply.