Printing a statevector

Hi! I am trying to print out the statevector of certain system and I was trying to use “pennylane.qnodes import PassthruQNode”
(Using the state vector directly), and I’m have two troubles:

  1. The error message says “Cannot convert value <bound method DefaultTensor._state of <DefaultTensorTF device (wires=2, shots=1000) at 0x217a9d8d760>> to a TensorFlow DType” for the line of “grad = tape.gradient(state, params)” in your example code on that discussion link.

  2. How can I actually print out the state? It kept showing “<bound method DefaultTensor._state of <DefaultTensorTF device (wires=2, shots=1000) at 0x217a9d46a90>>” even if I put print statement.

Hi @Leeseok_Kim,

I was facing a similar issue with device However, using instead solves the problem and everything works fine! Just replace your device name with keeping everything else as it is. I hope this helps.

Note: The latest Pennylane 0.11.0 documentation contains and not

I do not know the reason why/how this works, the developers might answer ‘how’. :slight_smile:

Hey @Leeseok_Kim!

This can be fixed by adding an open and closing brackets at the end of dev._state, i.e., getting dev._state().

Thanks @Vineesha for the additional answer, which should also work! The difference between the two devices is that has _state simply as an attribute while defines a _state() method - practically this means we just need to add those brackets for the device.

We’re also in the process of making it easier to work with the state without having to worry about these details!

Also, @Leeseok_Kim, you might have to make a few tweaks to get that code-block to work nicely. For example:

import tensorflow as tf
import pennylane as qml
from pennylane.qnodes import PassthruQNode

dev = qml.device('', wires=2)

def circuit(params):
    qml.RX(params[0], wires=0)
    qml.RX(params[1], wires=1)
    qml.CNOT(wires=[0, 1])
    return qml.expval(qml.PauliZ(0))

qnode = PassthruQNode(circuit, dev)
params = tf.Variable([0.3, 0.1], dtype=tf.complex128)

with tf.GradientTape() as tape:
    state = dev._state()

grad = tape.jacobian(state, params)

print("State:", state)
print("Gradient:", grad)

Enabling return state() in the most commonly used default.qubit would be really helpful! Glad to know about it, thank you!

1 Like