You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
import os
import pickle
import tarfile
from tqdm import tqdm
import matplotlib
import numpy as np
import pyqpanda as pq
import pyvqnet.nn as nn
from keras.utils import to_categorical
import tensorflow as tf
from pyvqnet.data.data import data_generator
from pyvqnet.nn.linear import Linear
from pyvqnet.nn.loss import CrossEntropyLoss
from pyvqnet.nn.module import Module
from pyvqnet.optim.adam import Adam
from pyvqnet.qnn.measure import expval
from pyvqnet.qnn.quantumlayer import QuantumLayerMultiProcess
from pyvqnet.tensor.tensor import QTensor
import keras
from pyvqnet import DEV_GPU_0
from pyvqnet.tensor import *
from pyvqnet.tensor import tensor
import warnings
warnings.filterwarnings('ignore')
try:
matplotlib.use("TkAgg")
except: # pylint:disable=bare-except
print("Can not use matplot TkAgg")
try:
import urllib.request
except ImportError:
raise ImportError("You should use Python 3.x")
def load_local_cifar10(path):
with tarfile.open(path, 'r:gz') as tar:
tar.extractall()
data_dir = './cifar-10-batches-py'
x_train, y_train, x_test, y_test = [], [], [], []
if isinstance(para, QTensor):
para = QTensor._to_numpy(para)
if para.ndim > 1:
raise ValueError(" dim of paramters in Rot should be 1")
if para.shape[0] != 3:
raise ValueError(" numbers of paramters in Rot should be 3")
cir = pq.QCircuit()
cir.insert(pq.RZ(qlist, para[2]))
cir.insert(pq.RY(qlist, para[1]))
cir.insert(pq.RZ(qlist, para[0]))
return cir
我的代码是上面这个,但是报了tensor存在不同的device
Traceback (most recent call last):
File "/data3/gaolanmei_2024/AutoPET/AutoPET/data/main.py", line 386, in
vqnet_test_QMLPModel()
File "/data3/gaolanmei_2024/AutoPET/AutoPET/data/main.py", line 364, in vqnet_test_QMLPModel
output = model(x)
File "pyvqnet/nn/module.py", line 613, in pyvqnet.nn.module.Module.call
File "/data3/gaolanmei_2024/AutoPET/AutoPET/data/main.py", line 313, in forward
result = self.linear(quanutum_result)
File "pyvqnet/nn/module.py", line 613, in pyvqnet.nn.module.Module.call
File "pyvqnet/nn/linear.py", line 106, in pyvqnet.nn.linear.Linear.forward
RuntimeError: VQNet runtimeError: Tensors in different devices ( FILE: /root/yxy/vqnet2.0.8/package/1016-linux/py39/vqnet/src/tensor/tensor_utils.cpp. LINE: 3153. FUNC: mult2D_templates
The text was updated successfully, but these errors were encountered:
import os
import pickle
import tarfile
from tqdm import tqdm
import matplotlib
import numpy as np
import pyqpanda as pq
import pyvqnet.nn as nn
from keras.utils import to_categorical
import tensorflow as tf
from pyvqnet.data.data import data_generator
from pyvqnet.nn.linear import Linear
from pyvqnet.nn.loss import CrossEntropyLoss
from pyvqnet.nn.module import Module
from pyvqnet.optim.adam import Adam
from pyvqnet.qnn.measure import expval
from pyvqnet.qnn.quantumlayer import QuantumLayerMultiProcess
from pyvqnet.tensor.tensor import QTensor
import keras
from pyvqnet import DEV_GPU_0
from pyvqnet.tensor import *
from pyvqnet.tensor import tensor
import warnings
warnings.filterwarnings('ignore')
try:
matplotlib.use("TkAgg")
except: # pylint:disable=bare-except
print("Can not use matplot TkAgg")
try:
import urllib.request
except ImportError:
raise ImportError("You should use Python 3.x")
def load_local_cifar10(path):
with tarfile.open(path, 'r:gz') as tar:
tar.extractall()
data_dir = './cifar-10-batches-py'
x_train, y_train, x_test, y_test = [], [], [], []
def RotCircuit(para, qlist):
def build_RotCircuit(qubits, weights):
cir = pq.QCircuit()
cir.insert(RotCircuit(weights[0:3], qubits[0]))
cir.insert(RotCircuit(weights[3:6], qubits[1]))
cir.insert(RotCircuit(weights[6:9], qubits[2]))
cir.insert(RotCircuit(weights[9:12], qubits[3]))
cir.insert(RotCircuit(weights[12:15], qubits[4]))
cir.insert(RotCircuit(weights[15:18], qubits[5]))
cir.insert(RotCircuit(weights[18:21], qubits[6]))
cir.insert(RotCircuit(weights[21:24], qubits[7]))
cir.insert(RotCircuit(weights[24:27], qubits[8]))
cir.insert(RotCircuit(weights[27:30], qubits[9]))
cir.insert(RotCircuit(weights[30:33], qubits[10]))
cir.insert(RotCircuit(weights[33:36], qubits[11]))
cir.insert(RotCircuit(weights[36:39], qubits[12]))
cir.insert(RotCircuit(weights[39:42], qubits[13]))
cir.insert(RotCircuit(weights[42:45], qubits[14]))
cir.insert(RotCircuit(weights[45:48], qubits[15]))
def CRXCircuit(para, control_qlists, rot_qlists):
cir = pq.QCircuit()
cir.insert(pq.RX(rot_qlists, para))
cir.set_control(control_qlists)
return cir
def build_CRotCircuit(qubits, weights):
cir = pq.QCircuit()
cir.insert(CRXCircuit(weights[0], qubits[0], qubits[1]))
cir.insert(CRXCircuit(weights[1], qubits[1], qubits[2]))
cir.insert(CRXCircuit(weights[2], qubits[2], qubits[3]))
cir.insert(CRXCircuit(weights[3], qubits[3], qubits[4]))
cir.insert(CRXCircuit(weights[4], qubits[4], qubits[5]))
cir.insert(CRXCircuit(weights[5], qubits[5], qubits[6]))
cir.insert(CRXCircuit(weights[6], qubits[6], qubits[7]))
cir.insert(CRXCircuit(weights[7], qubits[7], qubits[8]))
cir.insert(CRXCircuit(weights[8], qubits[8], qubits[9]))
cir.insert(CRXCircuit(weights[9], qubits[9], qubits[10]))
cir.insert(CRXCircuit(weights[10], qubits[10], qubits[11]))
cir.insert(CRXCircuit(weights[11], qubits[11], qubits[12]))
cir.insert(CRXCircuit(weights[12], qubits[12], qubits[13]))
cir.insert(CRXCircuit(weights[13], qubits[13], qubits[14]))
cir.insert(CRXCircuit(weights[14], qubits[14], qubits[15]))
cir.insert(CRXCircuit(weights[15], qubits[15], qubits[0]))
def build_qmlp_circuit(x, weights, qubits, clist, machine):
cir = pq.QCircuit()
num_qubits = len(qubits)
for i in range(num_qubits):
cir.insert(pq.RX(qubits[i], x[i]))
def build_multiprocess_qmlp_circuit(x, weights, num_qubits, num_clist):
machine = pq.CPUQVM()
machine.init_qvm()
qubits = machine.qAlloc_many(num_qubits)
cir = pq.QCircuit()
for i in range(num_qubits):
cir.insert(pq.RX(qubits[i], x[i]))
class QMLPModel(Module):
def init(self):
super(QMLPModel, self).init()
self.ave_pool2d = AvgPool2D([7, 7], [7, 7], "valid")
# self.quantum_circuit = QuantumLayer(build_qmlp_circuit, 128, "CPU", 16, diff_method="finite_diff")
self.quantum_circuit = QuantumLayerMultiProcess(build_multiprocess_qmlp_circuit, 128,
16, 1, diff_method="finite_diff")
self.linear = Linear(16, 10)
def forward(self, x):
bsz = x.shape[0]
x = self.ave_pool2d(x)
input_data = x.reshape([bsz, 16])
quanutum_result = self.quantum_circuit(input_data)
result = self.linear(quanutum_result)
return result
class QMLPModel(Module):
def init(self):
super(QMLPModel, self).init()
# 添加一个简单的CNN来降维并抽取特征
self.ave_pool2d = nn.AvgPool2D([7, 7], [7, 7], "valid")
self.cnn_layers = nn.Sequential(
# 假设输入为CIFAR图像:[batch_size, 3, 32, 32]
nn.Conv2D(3, 16, kernel_size=(3,3)),
nn.ReLu(),
nn.MaxPool2D([2,2],[2,2]),
# 现在尺寸是:[batch_size, 16, 16, 16]
nn.Conv2D(16, 8, kernel_size=(3,3)),
nn.ReLu(),
nn.MaxPool2D([2,2],[2,2]),
# 最终尺寸是:[batch_size, 8, 8, 8]
)
# 确保修改量子电路或其他模型结构以适应新的输入尺寸
self.quantum_circuit = QuantumLayerMultiProcess(build_multiprocess_qmlp_circuit, 128, 16, 1, diff_method="finite_diff")
# 经过量子层后,再连接到最终的分类层
self.linear = Linear(16, 10)
def forward(self, x):
bsz = x.shape[0]
x = self.ave_pool2d(x)
# 此处你可能需要根据量子电路的输入要求进一步处理x
input_data = x.reshape([bsz, 16]) # 确保这一步匹配量子电路的期待输入格式
quantum_result = self.quantum_circuit(input_data)
result = self.linear(quantum_result)
return result
class QMLPModel(nn.Module):
def init(self):
super(QMLPModel, self).init()
# 假设输入是经过适当预处理的CIFAR图像:[batch_size, channels, height, width]
self.ave_pool2d = nn.AvgPool2D([3, 3], [1, 1], "valid")
self.cnn_layers = nn.Sequential(
nn.Conv2D(3, 16, kernel_size=(3, 3), stride=(1, 1), padding='same'),
nn.ReLu(),
nn.AvgPool2D(kernel=[2, 2], stride=[2, 2]),
# 由于使用'same' padding和stride=2,现在尺寸是:[batch_size, 16, 16, 16]
nn.Conv2D(16, 8, kernel_size=(3, 3), stride=(1, 1), padding='same'),
nn.ReLu(),
nn.AvgPool2D(kernel=[2, 2], stride=[2, 2]),
# 再次使用'same' padding和stride=2,现在尺寸是:[batch_size, 8, 8, 8]
)
# 需调整QuantumLayerMultiProcess参数来适配CNN层的输出
self.quantum_circuit = QuantumLayerMultiProcess(build_multiprocess_qmlp_circuit, 128, 16, 1, diff_method="finite_diff")
# 假定我们展平了CNN层的输出,并适配到了量子层
self.linear = nn.Linear(16, 10) # 输出10个类别
def forward(self, x):
# x = self.cnn_layers(x)
# # 展平特征以适配量子层
# x = x.view(x.size(0), -1)
# quanutum_result = self.quantum_circuit(x)
# result = self.linear(quanutum_result)
# return result
bsz = x.shape[0]
x = self.ave_pool2d(x)
input_data = x.reshape([bsz, 2700])
quanutum_result = self.quantum_circuit(input_data)
result = self.linear(quanutum_result)
return result
class QMLPModel(Module):
def init(self):
super(QMLPModel, self).init()
self.ave_pool2d = nn.AvgPool2D([7, 7], [7, 7], "valid")
# self.quantum_circuit = QuantumLayer(build_qmlp_circuit, 128, "CPU", 16, diff_method="finite_diff")
self.quantum_circuit = QuantumLayerMultiProcess(build_multiprocess_qmlp_circuit, 128,
16, 1, diff_method="finite_diff")
self.linear = Linear(16, 10)
def vqnet_test_QMLPModel():
# 设置训练集和验证集大小
# train_size = 5000
# eval_size = 1000
if name == "main":
vqnet_test_QMLPModel()
我的代码是上面这个,但是报了tensor存在不同的device
Traceback (most recent call last):
File "/data3/gaolanmei_2024/AutoPET/AutoPET/data/main.py", line 386, in
vqnet_test_QMLPModel()
File "/data3/gaolanmei_2024/AutoPET/AutoPET/data/main.py", line 364, in vqnet_test_QMLPModel
output = model(x)
File "pyvqnet/nn/module.py", line 613, in pyvqnet.nn.module.Module.call
File "/data3/gaolanmei_2024/AutoPET/AutoPET/data/main.py", line 313, in forward
result = self.linear(quanutum_result)
File "pyvqnet/nn/module.py", line 613, in pyvqnet.nn.module.Module.call
File "pyvqnet/nn/linear.py", line 106, in pyvqnet.nn.linear.Linear.forward
RuntimeError: VQNet runtimeError: Tensors in different devices ( FILE: /root/yxy/vqnet2.0.8/package/1016-linux/py39/vqnet/src/tensor/tensor_utils.cpp. LINE: 3153. FUNC: mult2D_templates
The text was updated successfully, but these errors were encountered: