Module pennylane has no attribute Quadx

Greetings!

I am trying to run a time series through Pennylane based upon an example - code below.

  • is 100% self-contained — someone can copy-paste exactly what is here and run it to
    reproduce the behaviour you are observing
  • includes comments
# Put code here
import pennylane as qml
from pennylane import numpy as np
from pennylane.optimize import AdamOptimizer
dev = qml.device("strawberryfields.fock", wires=1, cutoff_dim=10)

def layer(v):
    # Matrix multiplication of input layer
    qml.Rotation(v[0], wires=0)
    qml.Squeezing(v[1], 0.0, wires=0)
    qml.Rotation(v[2], wires=0)

    # Bias
    qml.Displacement(v[3], 0.0, wires=0)

    # Element-wise nonlinear transformation
    qml.Kerr(v[4], wires=0)

@qml.qnode(dev)
def quantum_neural_net(var, x):
    # Encode input x into quantum state
    qml.Displacement(x, 0.0, wires=0)

    # "layer" subcircuits
    for v in var:
        layer(v)

    return qml.expval(qml.QuadX(0))

def square_loss(labels, predictions):
    loss = 0
    for l, p in zip(labels, predictions):
        loss = loss + (l - p) ** 2

    loss = loss / len(labels)
    return loss

def cost(var, features, labels):
    preds = [quantum_neural_net(var, x) for x in features]
    return square_loss(labels, preds)

np.random.seed(0)
num_layers = 4
var_init = 0.05 * np.random.randn(num_layers, 5, requires_grad=True)
print(var_init)

opt = AdamOptimizer(0.01, beta1=0.9, beta2=0.999)

var = var_init
for it in range(5):
    (var, _, _), _cost = opt.step_and_cost(cost, var, X, Y)
    print("Iter: {:5d} | Cost: {:0.7f} ".format(it, _cost))

If you want help with diagnosing an error, please put the full error message below:

# Put full error message here
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[125], line 5
      3 var = var_init
      4 for it in range(5):
----> 5     (var, _, _), _cost = opt.step_and_cost(cost, var, X, Y)
      6     print("Iter: {:5d} | Cost: {:0.7f} ".format(it, _cost))

File ~\AppData\Local\anaconda3\Lib\site-packages\pennylane\optimize\gradient_descent.py:59, in GradientDescentOptimizer.step_and_cost(self, objective_fn, grad_fn, *args, **kwargs)
     39 def step_and_cost(self, objective_fn, *args, grad_fn=None, **kwargs):
     40     """Update trainable arguments with one step of the optimizer and return the corresponding
     41     objective function value prior to the step.
     42 
   (...)
     56         If single arg is provided, list [array] is replaced by array.
     57     """
---> 59     g, forward = self.compute_grad(objective_fn, args, kwargs, grad_fn=grad_fn)
     60     new_args = self.apply_grad(g, args)
     62     if forward is None:

File ~\AppData\Local\anaconda3\Lib\site-packages\pennylane\optimize\gradient_descent.py:117, in GradientDescentOptimizer.compute_grad(objective_fn, args, kwargs, grad_fn)
     99 r"""Compute gradient of the objective function at the given point and return it along with
    100 the objective function forward pass (if available).
    101 
   (...)
    114     will not be evaluted and instead ``None`` will be returned.
    115 """
    116 g = get_gradient(objective_fn) if grad_fn is None else grad_fn
--> 117 grad = g(*args, **kwargs)
    118 forward = getattr(g, "forward", None)
    120 num_trainable_args = sum(getattr(arg, "requires_grad", False) for arg in args)

File ~\AppData\Local\anaconda3\Lib\site-packages\pennylane\_grad.py:115, in grad.__call__(self, *args, **kwargs)
    112     self._forward = self._fun(*args, **kwargs)
    113     return ()
--> 115 grad_value, ans = grad_fn(*args, **kwargs)
    116 self._forward = ans
    118 return grad_value

File ~\AppData\Local\anaconda3\Lib\site-packages\autograd\wrap_util.py:20, in unary_to_nary.<locals>.nary_operator.<locals>.nary_f(*args, **kwargs)
     18 else:
     19     x = tuple(args[i] for i in argnum)
---> 20 return unary_operator(unary_f, x, *nary_op_args, **nary_op_kwargs)

File ~\AppData\Local\anaconda3\Lib\site-packages\pennylane\_grad.py:133, in grad._grad_with_forward(fun, x)
    127 @staticmethod
    128 @unary_to_nary
    129 def _grad_with_forward(fun, x):
    130     """This function is a replica of ``autograd.grad``, with the only
    131     difference being that it returns both the gradient *and* the forward pass
    132     value."""
--> 133     vjp, ans = _make_vjp(fun, x)
    135     if not vspace(ans).size == 1:
    136         raise TypeError(
    137             "Grad only applies to real scalar-output functions. "
    138             "Try jacobian, elementwise_grad or holomorphic_grad."
    139         )

File ~\AppData\Local\anaconda3\Lib\site-packages\autograd\core.py:10, in make_vjp(fun, x)
      8 def make_vjp(fun, x):
      9     start_node = VJPNode.new_root()
---> 10     end_value, end_node =  trace(start_node, fun, x)
     11     if end_node is None:
     12         def vjp(g): return vspace(x).zeros()

File ~\AppData\Local\anaconda3\Lib\site-packages\autograd\tracer.py:10, in trace(start_node, fun, x)
      8 with trace_stack.new_trace() as t:
      9     start_box = new_box(x, t, start_node)
---> 10     end_box = fun(start_box)
     11     if isbox(end_box) and end_box._trace == start_box._trace:
     12         return end_box._value, end_box._node

File ~\AppData\Local\anaconda3\Lib\site-packages\autograd\wrap_util.py:15, in unary_to_nary.<locals>.nary_operator.<locals>.nary_f.<locals>.unary_f(x)
     13 else:
     14     subargs = subvals(args, zip(argnum, x))
---> 15 return fun(*subargs, **kwargs)

Cell In[114], line 2, in cost(var, features, labels)
      1 def cost(var, features, labels):
----> 2     preds = [quantum_neural_net(var, x) for x in features]
      3     return square_loss(labels, preds)

Cell In[114], line 2, in <listcomp>(.0)
      1 def cost(var, features, labels):
----> 2     preds = [quantum_neural_net(var, x) for x in features]
      3     return square_loss(labels, preds)

File ~\AppData\Local\anaconda3\Lib\site-packages\pennylane\qnode.py:842, in QNode.__call__(self, *args, **kwargs)
    839         set_shots(self._original_device, override_shots)(self._update_gradient_fn)()
    841 # construct the tape
--> 842 self.construct(args, kwargs)
    844 cache = self.execute_kwargs.get("cache", False)
    845 using_custom_cache = (
    846     hasattr(cache, "__getitem__")
    847     and hasattr(cache, "__setitem__")
    848     and hasattr(cache, "__delitem__")
    849 )

File ~\AppData\Local\anaconda3\Lib\site-packages\pennylane\qnode.py:751, in QNode.construct(self, args, kwargs)
    748 if old_interface == "auto":
    749     self.interface = qml.math.get_interface(*args, *list(kwargs.values()))
--> 751 self._tape = make_qscript(self.func)(*args, **kwargs)
    752 self._qfunc_output = self.tape._qfunc_output
    754 params = self.tape.get_parameters(trainable_only=False)

File ~\AppData\Local\anaconda3\Lib\site-packages\pennylane\tape\qscript.py:1371, in make_qscript.<locals>.wrapper(*args, **kwargs)
   1369 def wrapper(*args, **kwargs):
   1370     with AnnotatedQueue() as q:
-> 1371         result = fn(*args, **kwargs)
   1373     qscript = QuantumScript.from_queue(q)
   1374     qscript._qfunc_output = result

Cell In[112], line 10, in quantum_neural_net(var, x)
      7 for v in var:
      8     layer(v)
---> 10 return qml.expval(qml.QuadX(0))

File ~\AppData\Local\anaconda3\Lib\site-packages\pennylane\__init__.py:358, in __getattr__(name)
    355     import pennylane.grouping as grouping  # pylint:disable=import-outside-toplevel,consider-using-from-import
    357     return grouping
--> 358 raise AttributeError(f"Module {__name__} has no attribute {name}")

AttributeError: Module pennylane has no attribute QuadX

And, finally, make sure to include the versions of your packages. Specifically, show us the output of qml.about().
Name: PennyLane
Version: 0.33.1
Summary: PennyLane is a Python quantum machine learning library by Xanadu Inc.
Home-page: GitHub - PennyLaneAI/pennylane: PennyLane is a cross-platform Python library for differentiable programming of quantum computers. Train a quantum computer the same way as a neural network.
Author:
Author-email:
License: Apache License 2.0
Location: C:\Users\gz129d\AppData\Local\anaconda3\Lib\site-packages
Requires: appdirs, autograd, autoray, cachetools, networkx, numpy, pennylane-lightning, requests, rustworkx, scipy, semantic-version, toml, typing-extensions
Required-by: PennyLane-Lightning, PennyLane-SF

Platform info: Windows-10-10.0.19045-SP0
Python version: 3.11.5
Numpy version: 1.23.5
Scipy version: 1.11.1
Installed devices:

  • default.gaussian (PennyLane-0.29.1)
  • default.mixed (PennyLane-0.29.1)
  • default.qubit (PennyLane-0.29.1)
  • default.qubit.autograd (PennyLane-0.29.1)
  • default.qubit.jax (PennyLane-0.29.1)
  • default.qubit.tf (PennyLane-0.29.1)
  • default.qubit.torch (PennyLane-0.29.1)
  • default.qutrit (PennyLane-0.29.1)
  • null.qubit (PennyLane-0.29.1)
  • lightning.qubit (PennyLane-Lightning-0.30.0)
  • strawberryfields.fock (PennyLane-SF-0.29.1)
  • strawberryfields.gaussian (PennyLane-SF-0.29.1)
  • strawberryfields.gbs (PennyLane-SF-0.29.1)
  • strawberryfields.remote (PennyLane-SF-0.29.1)
  • strawberryfields.tf (PennyLane-SF-0.29.1)

I have tried PL 0.29 as PL SF but encountered the same error: Module pennylane has no attribute Quadx. PL 0.33 leads to the same error.

May I please request any feedback regarding this Quadx attribute?

Added Note: Strawberry Fields indicate it needs PL < 0.30 - same result though with 0.29.

Thanks

Hey @mas0047, welcome back!

I’m a little confused with your qml.about() output :thinking:. Indeed, QuadX should be available in v0.33 (this is from our deprecations page: Deprecations — PennyLane 0.33.0 documentation):

The CV observables qml.X and qml.P have been removed. Use qml.QuadX and qml.QuadP instead (Deprecated in v0.32, removed in v0.33)

But your devices are all on PennyLane v0.29. Just to take all variables out of the equation here, I recommend creating a virtual environment and installing a fresh copy of PennyLane. It looks like you’re using conda, so you can create a virtual environment like this:

conda create -n <name of virtual environment> python=3.11

Then you can activate the virtual environment like so:

conda activate <name of virtual environment>

And install pennylane:

python -m pip install pennylane

Try running your code in a new virtual environment and let me know if that helps :slight_smile:

Many thanks, Isaac!

Created new virtual environment and installed pennylane per instructions in your message.

import pennylane as qml
from pennylane import numpy as np
from pennylane.optimize import AdamOptimizer
# All goes well upto this point
dev = qml.device("strawberryfields.fock", wires=1, cutoff_dim=10)
# leads to the following error:
---------------------------------------------------------------------------
DeviceError                               Traceback (most recent call last)
Cell In[2], line 1
----> 1 dev = qml.device("strawberryfields.fock", wires=1, cutoff_dim=10)

File ~\AppData\Local\anaconda3\envs\pl\Lib\site-packages\pennylane\__init__.py:377, in device(name, *args, **kwargs)
    373             dev.preprocess = custom_decomp_preprocess
    375     return dev
--> 377 raise DeviceError(f"Device {name} does not exist. Make sure the required plugin is installed.")

DeviceError: Device strawberryfields.fock does not exist. Make sure the required plugin is installed.

The current Pennylane version is 0.33. If I were to install pennylane-SF, it will display a message saying SF needs PL < 0.30 such as 0.29.

May I please find out how to proceed with Strawberry Fields plug in installation in this case? (to set up/ run the following command, with PL 0.33 installed)

dev = qml.device("strawberryfields.fock", wires=1, cutoff_dim=10)

Thanks

Hey @mas0047,

Ah! I understand the issue better now. If you want to use the pennylane-strawberryfields plugin, then indeed you’ll have to have pennylane==0.29 to ensure that nothing weird happens. With that version of pennylane, QuadX and QuadP are actually named X and P. Those were their original names — deprecated as of a couple releases ago:

  • The CV observables qml.X and qml.P have been removed. Use qml.QuadX and qml.QuadP instead. (* Deprecated in v0.32 * Removed in v0.33)

I think all you need to do is just change to qml.X and qml.P when using pennylane==0.29 and you should be good to go. Let me know if that helps!

Many thanks, Isaac.

" I think all you need to do is just change to qml.X and qml.P when using pennylane==0.29" - I apologize for the inconvenience first of all.
May I please find out exactly which files to change these names in? (or) how to locate files with these variables?
Trying to make the changes accurately.
Look forward to hearing from you.

Many thanks!

Hey @mas0047,

I’m not sure I understand, but if you use the correct pennylane version than all should be well and you don’t need to change anything :slight_smile:.