Weights in qunatum layers

Hi there,

How can I set the weights of customized quantum layer (to be converted to keras layer later on), instead of using built-in templates.

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

@qml.qnode(dev, interface = "tf", diff_method="adjoint")
def qnode(inputs, w1):
    qml.templates.AmplitudeEmbedding(inputs, wires=range(n_qubits), pad_with=2,  normalize = True)
    for i in range(n_qubits):
        qml.RX(w1[i], i)
    return [qml.expval(qml.PauliZ(wires=[i])) for i in range(n_qubits)]

n_layers = 2
weight_shapes = {"w1":(1,n_qubits)}

when I convert the above qnode into Keras Layer following this template and later train the model, I get the following error:

InvalidArgumentError: Exception encountered when calling layer "keras_layer_4" (type KerasLayer).

slice index 1 of dimension 0 out of bounds. [Op:StridedSlice] name: model_4/keras_layer_4/strided_slice/

Any pointers to why is this the case would be appreciated…
Thanks

Hi @Muhammad_Kashif, unfortunately I’m not being able to reproduce your error. Could you please post a minimal non-working example of your code? Basically your full code but stripped off any elements that don’t contribute to you getting this error. Please include your data too so that I can run it and try to see what the problem may be.

Hi @CatalinaAlbornoz,

Thanks for looking into my query. Below is my code example:

imports

import pennylane as qml
from pennylane import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import datasets

dataset loading

x_train, x_test = datasets.load_digits().data, datasets.load_digits().target

splitting train and test data

x_train, x_test, y_train, y_test = train_test_split(
    x_train, x_test, test_size=0.25, random_state=42)

creating qnode

n_qubits = 6
dev = qml.device("default.qubit", wires=n_qubits)
@qml.qnode(dev)
def qnode(inputs, w1):
    qml.templates.AmplitudeEmbedding(inputs, wires=range(n_qubits), pad_with=2,  normalize = True)

    for i in range(n_qubits):
        qml.RY(w1[i], wires = i)
    return [qml.expval(qml.PauliZ(wires=i)) for i in range(n_qubits)]

defining weight shapes for quantum gates

weight_shapes = {"w1": (1,6)}

qnode to keras layer

qlayer = qml.qnn.KerasLayer(qnode, weight_shapes, output_dim=n_qubits)

creating a hybrid NN

clayer = tf.keras.layers.Dense(10, activation="softmax")
model = tf.keras.models.Sequential([qlayer, clayer])

compiling the NN model

opt = tf.keras.optimizers.SGD(learning_rate=0.2)
model.compile(opt, loss="sparse_categorical_crossentropy", metrics=["accuracy"])

start training the model

fitting = model.fit(x_train, y_train, epochs=1, batch_size=16, validation_data=(x_test, y_test))

The above results in the following error:
InvalidArgumentError: slice index 1 of dimension 0 out of bounds. [Op:StridedSlice] name: sequential_20/keras_layer_21/strided_slice/

Now the issue I am facing here is regarding the weight_shapes. since I am using single parametrized gate RY means it should have a single dimension weight (as per my understanding) and hence the first argument in weight_shapes dictionary is 1 and since I am using 6 qubits the second argument is 6. which means 6 weights of dimension 1 (correct me if I am wrong)? but it gives the error mentioned above.

If I set the weight_shapes = {"w1": (1)} and not use w1[i] in the qnode where I pass the weights to RY the code works fine but in that case, I think we are only training the 6 RY gates with same weights which is, in a way, same like training a single weight or single RY gate, whereas all 6 RY gates should have different weights, right?
I hope I made my question clear. Any help would be appreciated.
Thanks

Hi @Muhammad_Kashif,

I was able to reproduce your error now. Your error is effectively in the weight shapes. You want it to be a vector of size 6. This means that the weights shape should be: weight_shapes = {"w1": (6)}

This has solved the problem on my end. Please let me know if it works for you too!

Hi @CatalinaAlbornoz,

It works.
Thanks for the help…!!

I asked a query here few days back. Any update on this so far?

Thanks

Hi @Muhammad_Kashif,

I’m glad this solved your issue!

Regarding the other query I will give you an answer there.