KerasLayer error parameter dynamic: True


Recently, one of my students reached out to me with an error using KerasLayer. After a brief discussion, I tried her code and got the same error. I updated PennyLane to version 0.35, but there is still the same error.
I took a look at the class using


In a notebook, I tested the code provided in the class description. See above:

import pennylane as qml
import tensorflow as tf
import sklearn.datasets

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

def qnode(inputs, weights):
    qml.templates.AngleEmbedding(inputs, wires=range(n_qubits))
    qml.templates.StronglyEntanglingLayers(weights, wires=range(n_qubits))
    return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))

weight_shapes = {"weights": (3, n_qubits, 3)}

qlayer = qml.qnn.KerasLayer(qnode, weight_shapes, output_dim=2)
clayer1 = tf.keras.layers.Dense(2)
clayer2 = tf.keras.layers.Dense(2, activation="softmax")
model = tf.keras.models.Sequential([clayer1, qlayer, clayer2])

data = sklearn.datasets.make_moons()
X = tf.constant(data[0])
Y = tf.one_hot(data[1], depth=2)

opt = tf.keras.optimizers.SGD(learning_rate=0.5)
model.compile(opt, loss='mae')

And I obtained the same error as my student. The parameter dynamic: True. It’s strange because this parameter doesn’t appear in the class. My intuition is around a version problem, but I’m not sure. KerasLayer isn’t in my toolbox, but it’s the first time I’ve used it. Here is the full output message:

ValueError                                Traceback (most recent call last)
Cell In[9], line 16
     12     return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))
     14 weight_shapes = {"weights": (3, n_qubits, 3)}
---> 16 qlayer = qml.qnn.KerasLayer(qnode, weight_shapes, output_dim=2)
     17 clayer1 = tf.keras.layers.Dense(2)
     18 clayer2 = tf.keras.layers.Dense(2, activation="softmax")

File ~/Concordia/lib/python3.10/site-packages/pennylane/qnn/, in KerasLayer.__init__(self, qnode, weight_shapes, output_dim, weight_specs, **kwargs)
    320 self.weight_specs = weight_specs if weight_specs is not None else {}
    322 self.qnode_weights = {}
--> 324 super().__init__(dynamic=True, **kwargs)
    326 # no point in delaying the initialization of weights, since we already know their shapes

File ~/Concordia/lib/python3.10/site-packages/keras/src/layers/, in Layer.__init__(self, activity_regularizer, trainable, dtype, autocast, name, **kwargs)
    263     self._input_shape_arg = input_shape_arg
    264 if kwargs:
--> 265     raise ValueError(
    266         "Unrecognized keyword arguments "
    267         f"passed to {self.__class__.__name__}: {kwargs}"
    268     )
    270 self.built = False
    271 self.dtype_policy = dtype_policies.get(dtype)

ValueError: Unrecognized keyword arguments passed to KerasLayer: {'dynamic': True}

We are not even trying to train the model… Any clue?
My version packages:

Name: PennyLane
Version: 0.35.0
Summary: PennyLane is a cross-platform Python library for quantum computing, quantum machine learning, and quantum chemistry. Train a quantum computer the same way as a neural network.
License: Apache License 2.0
Location: /home/ubuntu/Concordia/lib/python3.10/site-packages
Requires: appdirs, autograd, autoray, cachetools, networkx, numpy, pennylane-lightning, requests, rustworkx, scipy, semantic-version, toml, typing-extensions
Required-by: PennyLane_Lightning

Platform info:           Linux-5.15.0-89-generic-x86_64-with-glibc2.35
Python version:          3.10.9
Numpy version:           1.26.0
Scipy version:           1.11.3
Installed devices:
- default.clifford (PennyLane-0.35.0)
- default.gaussian (PennyLane-0.35.0)
- default.mixed (PennyLane-0.35.0)
- default.qubit (PennyLane-0.35.0)
- default.qubit.autograd (PennyLane-0.35.0)
- default.qubit.jax (PennyLane-0.35.0)
- default.qubit.legacy (PennyLane-0.35.0)
- (PennyLane-0.35.0)
- default.qubit.torch (PennyLane-0.35.0)
- default.qutrit (PennyLane-0.35.0)
- null.qubit (PennyLane-0.35.0)
- lightning.qubit (PennyLane_Lightning-0.35.0)

Thanks for your time.

Hey @Christophe_Pere,

Very strange! I’m not able to replicate this on my machine; I copy-pasted your code and was able to run it just fine. I’m using an M1 Mac with tensorflow-macos==2.15.0 and pennylane==0.35.0. Usually when stuff like this happens, I suggest the “turn off and back on” approach of creating a fresh virtual environment, installing the packages you need, and trying it again. On Linux, simply open a terminal and do the following:

$ python -m venv <path to virtual environment>
$ source <path to virtual environment>/bin/activate
$ python -m pip install pennylane tensorflow scikit-learn
$ python -m <your python file>

Let me know if this helps!

Hi @isaacdevlugt,

Thanks a lot. In fact, I think the problem comes from the version of tensorflow. I used the version 2.16.1 and got the error. You used 2.15.0, and it was ok. So I tested with another environment where tensorflow==2.14.0 is installed, and it works. So it seems to provide an incompatibility with the latest version of tensorflow.

Ah! Interesting. I’ll make sure to raise this to our dev team :slightly_smiling_face:. Glad I could help!

1 Like

Hello All,
I also faced the same issue, but I used below version
I think the issue is due to new versions of Pennylane and Tensorflow compatibility. but the above is working.

Hey @arthiudayak! Welcome to the forum :slight_smile:

I would make sure to create a fresh virtual environment, install the proper package versions, and make sure you use that environment when you try to execute your code. If that doesn’t work, can you please attach your full code so that I can try to replicate the issue on my side?