import sys
import os
import pennylane as qml
from pennylane import numpy as np
import tensorflow as tf
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Dense
from example_utils import get_parser
from importance_sampling.training import ConstantTimeImportanceTraining
重定向stdout以捕获打印输出
class Tee(object):
def init(self, *files):
self.files = files
def write(self, obj):
for f in self.files:
f.write(obj)
f.flush()
def flush(self):
for f in self.files:
f.flush()
for cv in control_values:
# 翻转控制比特为0的量子比特,以便使用受控RY门
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
# 对数据量子比特应用受控 RY 旋转,编码特征值和权重
for data_qubit, angle_value, angle_weight in zip(data_qubits, angle_values, angle_weights):
qml.ctrl(qml.RY, control=control_qubits)(angle_value, wires=data_qubit)
qml.ctrl(qml.RY, control=control_qubits)(angle_weight, wires=data_qubit)
# 恢复控制比特的原始状态
for qubit, val in zip(control_qubits, cv):
if val == 0:
qml.PauliX(wires=qubit)
上述是training.py文件
出现了报错Traceback (most recent call last):
File "G:\Hellyc\yuanweihua-NewQNN-default-layers=4_4feature _AngCode\examples\yuanweihua_renew_usesoftmax_NQNN_default_4feature_AngCode_Layers=5.py", line 301, in
history = wrapped_model.fit(
File "G:\Hellyc\yuanweihua-NewQNN-default-layers=4_4feature _AngCode\importance_sampling\training.py", line 132, in fit
return self.fit_dataset(
File "G:\Hellyc\yuanweihua-NewQNN-default-layers=4_4feature _AngCode\importance_sampling\training.py", line 304, in fit_dataset
val_loss, val_metrics = self.evaluate(dataset.test_data)
File "G:\Hellyc\yuanweihua-NewQNN-default-layers=4_4feature _AngCode\importance_sampling\training.py", line 399, in evaluate
y_pred = self.model.model.predict(x_test, batch_size=128)
File "G:\anaconda3\envs\pennylane2\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
raise e.with_traceback(filtered_tb) from None
File "G:\anaconda3\envs\pennylane2\lib\site-packages\tensorflow\python\framework\func_graph.py", line 1233, in autograph_handler
raise e.ag_error_metadata.to_exception(e)
tensorflow.python.framework.errors_impl.OperatorNotAllowedInGraphError: in user code:
File "G:\anaconda3\envs\pennylane2\lib\site-packages\keras\engine\training.py", line 2041, in predict_function *
return step_function(self, iterator)
File "G:\anaconda3\envs\pennylane2\lib\site-packages\keras\engine\training.py", line 2027, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "G:\anaconda3\envs\pennylane2\lib\site-packages\keras\engine\training.py", line 2015, in run_step **
outputs = model.predict_step(data)
File "G:\anaconda3\envs\pennylane2\lib\site-packages\keras\engine\training.py", line 1983, in predict_step
return self(x, training=False)
File "G:\anaconda3\envs\pennylane2\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
raise e.with_traceback(filtered_tb) from None
OperatorNotAllowedInGraphError: Exception encountered when calling layer "quantum_neural_network" " f"(type QuantumNeuralNetwork).
in user code:
File "G:\Hellyc\yuanweihua-NewQNN-default-layers=4_4feature _AngCode\examples\yuanweihua_renew_usesoftmax_NQNN_default_4feature_AngCode_Layers=5.py", line 246, in call *
q_output = self.quantum_layer(inputs)
File "G:\anaconda3\envs\pennylane2\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler **
raise e.with_traceback(filtered_tb) from None
OperatorNotAllowedInGraphError: Exception encountered when calling layer "quantum_neural_network_layer" " f"(type QuantumNeuralNetworkLayer).
in user code:
File "G:\Hellyc\yuanweihua-NewQNN-default-layers=4_4feature _AngCode\examples\yuanweihua_renew_usesoftmax_NQNN_default_4feature_AngCode_Layers=5.py", line 217, in apply_qnode *
result = quantum_neural_network(x, self.encoding_weights, self.rot_weights)
File "G:\anaconda3\envs\pennylane2\lib\site-packages\pennylane\qnode.py", line 552, in __call__ *
self.construct(args, kwargs)
File "G:\anaconda3\envs\pennylane2\lib\site-packages\pennylane\qnode.py", line 481, in construct *
self.qfunc_output = self.func(*args, **kwargs)
File "G:\Hellyc\yuanweihua-NewQNN-default-layers=4_4feature _AngCode\examples\yuanweihua_renew_usesoftmax_NQNN_default_4feature_AngCode_Layers=5.py", line 117, in quantum_neural_network *
encode_group(
File "G:\Hellyc\yuanweihua-NewQNN-default-layers=4_4feature _AngCode\examples\yuanweihua_renew_usesoftmax_NQNN_default_4feature_AngCode_Layers=5.py", line 76, in encode_group *
for data_qubit, angle_value, angle_weight in zip(data_qubits, angle_values, angle_weights):
OperatorNotAllowedInGraphError: Iterating over a symbolic `tf.Tensor` is not allowed: AutoGraph did convert this function. This might indicate you are trying to use an unsupported feature.
Call arguments received by layer "quantum_neural_network_layer" " f"(type QuantumNeuralNetworkLayer):
• inputs=tf.Tensor(shape=(None, 4), dtype=float32)
Call arguments received by layer "quantum_neural_network" " f"(type QuantumNeuralNetwork):
• inputs=tf.Tensor(shape=(None, 4), dtype=float32)
The error you're encountering stems from attempting to iterate over symbolic TensorFlow tensors within your PennyLane QNode. In TensorFlow's graph mode, operations must be compatible with the computational graph, and Pythonic loops over tensors are not allowed. Specifically, the encode_group function in your quantum_neural_network QNode is trying to perform Python for loops over TensorFlow tensors (angle_values and angle_weights), which leads to the OperatorNotAllowedInGraphError.
Understanding the Issue
Here's the critical part of the error traceback:
OperatorNotAllowedInGraphError: Iterating over a symbolic `tf.Tensor` is not allowed: AutoGraph did convert this function. This might indicate you are trying to use an unsupported feature.
This error indicates that within the QNode, the encode_group function is:
for data_qubit, angle_value, angle_weight in zip(data_qubits, angle_values, angle_weights):
qml.ctrl(qml.RY, control=control_qubits)(angle_value, wires=data_qubit)
qml.ctrl(qml.RY, control=control_qubits)(angle_weight, wires=data_qubit)
Here, angle_values and angle_weights are TensorFlow tensors when the QNode is executed within the TensorFlow graph. Python's for loop cannot handle symbolic tensors, causing the error.
Solution
To resolve this, you need to ensure that the encode_group function operates on concrete numerical values (e.g., NumPy arrays) rather than symbolic tensors. Here's how you can achieve this:
Convert TensorFlow Tensors to NumPy Arrays Within the QNode:
Modify the QNode to convert its TensorFlow tensor inputs to NumPy arrays before performing any Pythonic operations like loops. This ensures that the operations within encode_group are compatible with PennyLane.
Use TensorFlow's tf.py_function:
TensorFlow's tf.py_function allows you to wrap Python code that isn't compatible with TensorFlow's graph execution. However, using tf.py_function can complicate the gradient flow and might not be the most efficient approach.
Adjust the QNode Interface:
Instead of using interface='tf', consider using interface='autograd' or interface='numpy'. However, this might require more extensive changes to ensure compatibility with Keras.
Vectorize Operations:
Replace the Python loops with vectorized operations that are compatible with TensorFlow's computational graph. This can be complex, especially within the context of a quantum circuit, and might not always be feasible.
Given these options, the most straightforward solution is to convert the TensorFlow tensors to NumPy arrays within the QNode before performing Pythonic operations. Here's how you can implement this:
Implementing the Solution
Modify the QNode to Use NumPy Arrays:
Update the apply_qnode function within the QuantumNeuralNetworkLayer to ensure that the inputs to the QNode are NumPy arrays. This allows encode_group to operate on concrete numerical values.
Note: Accessing .numpy() is only possible if the tensors are executed eagerly. Ensure that TensorFlow's eager execution is enabled.
Enable Eager Execution:
TensorFlow 2.x has eager execution enabled by default. However, if it's disabled, you can enable it by adding the following at the beginning of your script:
import tensorflow as tf
tf.config.run_functions_eagerly(True)
Caution: Enabling eager execution can have performance implications, especially for large models.
Adjust the apply_qnode Function:
Ensure that apply_qnode converts its input to NumPy arrays before passing them to the QNode.
def apply_qnode(x):
x = x.numpy().astype(np.float32)
encoding_weights_np = self.encoding_weights.numpy().astype(np.float32)
rot_weights_np = self.rot_weights.numpy().astype(np.float32)
result = quantum_neural_network(x, encoding_weights_np, rot_weights_np)
return result.astype(np.float32)
Update the QuantumNeuralNetworkLayer Call Method:
Modify the call method to handle the conversion and ensure compatibility.
Eager Execution: Ensure that TensorFlow's eager execution is enabled to allow .numpy() conversions within the QNode.
Debugging: After making these changes, test the QNode independently to ensure it behaves as expected before integrating it into the larger model.
Performance Considerations: Be aware that converting tensors to NumPy arrays and enabling eager execution can impact performance. Profile your model to ensure that these changes don't introduce significant overhead.
Alternative Libraries: If integration issues persist, consider exploring other quantum machine learning libraries or frameworks that might offer better integration with TensorFlow/Keras.
Example Modified apply_qnode
Here's a modified version of your QuantumNeuralNetworkLayer with the suggested changes:
Integrating PennyLane with TensorFlow and Keras requires careful handling of tensor operations, especially when incorporating Pythonic loops within quantum circuits. By ensuring that your QNode operates on concrete numerical values (NumPy arrays) and avoiding iteration over symbolic tensors, you can resolve the OperatorNotAllowedInGraphError. Adjusting the interface and utilizing TensorFlow's eager execution are key steps in achieving compatibility between PennyLane and TensorFlow-based models.
If you continue to face issues, consider simplifying the quantum circuit or seeking alternative integration strategies that align more closely with both PennyLane's and TensorFlow's operational paradigms.