Hi! I am trying to get a snapshot of the density matrix before measuring a circuit run in a Hybrid CNN with tensorflow. However I am not able to achieve a good code behaviour. I used the fuctional Keras API to make the CNN work, i.e., I created a new class for the model where I defined the convolution circuit as:
# Create a quantum device
self.dev = qml.device(device, wires=n_qubits)
@tf.function(jit_compile=None)
@qml.qnode(self.dev)
def circuit(inputs, params):
# Apply trainable encoding operations on each qubit
for i in range(self.n_qubits):
qml.Rot(params[i] * inputs[i] + params[i + self.n_qubits],
params[i + 2 * self.n_qubits] * inputs[i] + params[i + 3 * self.n_qubits],
params[i + 4 * self.n_qubits] * inputs[i] + params[i + 5 * self.n_qubits],
wires=i)
# Apply circular entanglement
for i in range(self.n_qubits):
qml.CNOT(wires=[i, (i + 1) % self.n_qubits])
# Save state vector
qml.Snapshot()
# Measure all qubits
return [qml.expval(qml.PauliZ(i)) for i in range(self.n_qubits)]
self.circuit = circuit
Then I try to use the circuit here and get the state vector with qml.snapshots
:
for i in range(batch_size):
for j in range(0, self.image_height, self.stride):
for k in range(0, self.image_width, self.stride):
# Process a squared 2x2 region of the image with a quantum circuit
patch = tf.reshape(inputs[i, j:j+2, k:k+2, 0], [4])
result_dict = qml.snapshots(self.circuit)(patch, self.params)
measurement_expvals = result_dict['execution_results']
out[i][j // self.stride][k // self.stride] = measurement_expvals
# Get entanglement entropies from reduced density matrices
# density_matrix = qml.math.dm_from_state_vector(result_dict[0])
# qubits_idxs = list(range(self.n_qubits))
# for l in range(1, self.n_qubits//2+1):
# for m in itertools.combinations(qubits_idxs, l):
# qubits_to_keep = [q for q in qubits_idxs if q not in m]
# entanglement_entropies.append(qml.math.vn_entropy(density_matrix, qubits_to_keep, base=2))
However, when calling the model with some data, I get this error message:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[18], line 3
2 with tf.device('/CPU:0'):
----> 3 qccnn.call(tf.convert_to_tensor(train_images[:batch_size]))
File ~/.virtualenvs/qml/lib/python3.10/site-packages/keras/engine/sequential.py:425, in Sequential.call(self, inputs, training, mask)
422 if "training" in argspec:
423 kwargs["training"] = training
--> 425 outputs = layer(inputs, **kwargs)
427 if len(tf.nest.flatten(outputs)) != 1:
428 raise ValueError(SINGLE_LAYER_OUTPUT_ERROR_MSG)
File ~/.virtualenvs/qml/lib/python3.10/site-packages/keras/utils/traceback_utils.py:70, in filter_traceback.<locals>.error_handler(*args, **kwargs)
67 filtered_tb = _process_traceback_frames(e.__traceback__)
68 # To get the full stack trace, call:
69 # `tf.debugging.disable_traceback_filtering()`
---> 70 raise e.with_traceback(filtered_tb) from None
71 finally:
72 del filtered_tb
Cell In[15], line 111, in QuantumConv.call(self, inputs, **kwargs)
108 patch = tf.reshape(inputs[i, j:j+2, k:k+2, 0], [4])
--> 111 result_dict = qml.snapshots(self.circuit)(patch, self.params)
112 measurement_expvals = result_dict['execution_results']
File ~/.virtualenvs/qml/lib/python3.10/site-packages/pennylane/debugging.py:92, in snapshots.<locals>.get_snapshots(*args, **kwargs)
91 def get_snapshots(*args, **kwargs):
---> 92 old_interface = qnode.interface
93 if old_interface == "auto":
94 qnode.interface = qml.math.get_interface(*args, *list(kwargs.values()))
AttributeError: Exception encountered when calling layer "quantum_conv" " f"(type QuantumConv).
'Function' object has no attribute 'interface'
Call arguments received by layer "quantum_conv" " f"(type QuantumConv):
• inputs=tf.Tensor(shape=(8, 18, 12, 1), dtype=float32)
• kwargs={'training': 'None'}
If I remove the decorator @tf.function(jit_compile=None)
, then the code does not throw this error but it runs forever and never stops. OR if I don’t use the qml.snapshots
method then it does not throw any error.
Am I using an outdated method? How do I get the state density matrix before measuring the circuit?
Output of qml.about()
:
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.
Home-page: https://github.com/PennyLaneAI/pennylane
Author:
Author-email:
License: Apache License 2.0
Location: /qcfs/bravo/.virtualenvs/qml/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-Cirq, PennyLane-qiskit, PennyLane_Lightning, PennyLane_Lightning_GPU
Platform info: Linux-5.15.0-92-generic-x86_64-with-glibc2.35
Python version: 3.10.12
Numpy version: 1.23.5
Scipy version: 1.11.3
Installed devices:
- cirq.mixedsimulator (PennyLane-Cirq-0.34.0)
- cirq.pasqal (PennyLane-Cirq-0.34.0)
- cirq.qsim (PennyLane-Cirq-0.34.0)
- cirq.qsimh (PennyLane-Cirq-0.34.0)
- cirq.simulator (PennyLane-Cirq-0.34.0)
- lightning.qubit (PennyLane_Lightning-0.35.0)
- 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)
- default.qubit.tf (PennyLane-0.35.0)
- default.qubit.torch (PennyLane-0.35.0)
- default.qutrit (PennyLane-0.35.0)
- null.qubit (PennyLane-0.35.0)
- lightning.gpu (PennyLane_Lightning_GPU-0.35.0)
- qiskit.aer (PennyLane-qiskit-0.35.1)
- qiskit.basicaer (PennyLane-qiskit-0.35.1)
- qiskit.ibmq (PennyLane-qiskit-0.35.1)
- qiskit.ibmq.circuit_runner (PennyLane-qiskit-0.35.1)
- qiskit.ibmq.sampler (PennyLane-qiskit-0.35.1)
- qiskit.remote (PennyLane-qiskit-0.35.1)