Drawing qml.node with torch interface

Hello everyone, I tried to draw a circuit using the Pytorch interface. Here is my problem:

Qnode Code:

    @qml.qnode(device=dev, interface='torch')
    def circuit(inputs, weights):
        n_inputs = len(inputs)
     
        # Encoding 
        for j in range(n_inputs):
            qml.Hadamard(wires=j)
            qml.RY(inputs[j], wires=j)

        # Random quantum circuit
        RandomLayers(weights, wires=list(range(n_inputs)))

        # Measurement 
        return qml.expval(qml.PauliZ(0))

Drawing Code:

wires = 4
x = torch.from_numpy(np.zeros(wires))
print(qml.draw(self.circuit, show_matrices=True)(x))

Error

raise AttributeError("'{}' object has no attribute '{}'".format(
AttributeError: 'TorchLayer' object has no attribute 'construct'

Did I miss something? Wiss you can help me

Hi @Emmanuel_OM, welcome to the forum!

When you’re using the draw function you need to construct the circuit by passing the parameters to it. Here you’re passing ‘x’ which is the ‘inputs’ parameter of your circuit but you’re forgetting the ‘weights’ parameter. Here’s an example of how you could add the weights.

import pennylane as qml
import torch
import numpy as np
from pennylane.templates.layers import RandomLayers

wires = 4
dev = qml.device('default.qubit',wires = wires)
@qml.qnode(device=dev, interface='torch')
def circuit(inputs, weights):
    n_inputs = len(inputs)
    # Encoding 
    for j in range(n_inputs):
        qml.Hadamard(wires=j)
        qml.RY(inputs[j], wires=j)

    # Random quantum circuit
    RandomLayers(weights, wires=list(range(n_inputs)))

    # Measurement 
    return qml.expval(qml.PauliZ(0))

weights = np.array([[0.1, -2.1, 1.4]])
x = torch.from_numpy(np.zeros(wires))
print(qml.draw(circuit, show_matrices=True)(x,weights)) 

I also encourage you to try out the draw_mpl drawer. In the “usage details” section of the docs you will find examples of how to use it.

Please let me know if this solves your problem!

If it doesn’t fix your problem I encourage you to check that you’re using the latest version of PennyLane (v0.23.1 at the moment).

1 Like

Hi @CatalinaAlbornoz. I appreciate your help. It works like a charm.

Yes, I have updated my PennyLane to the latest version (from v0.18 to vo.23.1). I have noticed the changes and new features for drawing.

1 Like