I have a two-dimensional input data and I have created a quantum circuit to encode this type of input. Here is my code:
import pennylane as qml
import torch
class QuantumCircuit:
def __init__(self, n_wqubits, ch_in):
self.n_wqubits = n_wqubits
self.n_qubits = n_wqubits + 1
self.ch_in = ch_in
self.weight_shapes = {"weights": (self.n_qubits, self.ch_in)}
self.dev = qml.device('default.qubit', wires=self.n_qubits)
def quantum_circuit(self, inputs, weights):
qml.Hadamard(wires=0)
input = inputs.reshape(ch_in, n_wqubits)
for k in range(self.ch_in):
for i in range(self.n_wqubits):
qml.RX(input[k][i], wires=i + 1)
qml.Hadamard(wires=0)
return [qml.expval(qml.PauliZ(i)) for i in range(self.n_qubits)]
Test code is
QuantumCircuit1 = QuantumCircuit(n_wqubits=4, ch_in=2)
qnode = qml.QNode(QuantumCircuit1.quantum_circuit, QuantumCircuit1.dev, interface="torch", diff_method='best')
qnn_layer = qml.qnn.TorchLayer(qnode, QuantumCircuit1.weight_shapes)
# Single input data
inputs = torch.randn(2, 4)
output = qnn_layer(inputs)
print(output)
# Batch input data
inputs = torch.randn(8, 2, 4)
output = qnn_layer(inputs)
print(output)
# pennylane version 0.38.0
# torch-gpu version 2.5.1
When using single input data (e.g., [inputs = torch.randn(2, 4)]), the code runs fine. However, when using batch input data (e.g., [inputs = torch.randn(8, 2, 4)], it actually be automatically reshaped as torch.randn(16, 4) when using circuits), the code throws an error:
" RuntimeError: shape ‘[2, -1]’ is invalid for input of size 1 "