Hello! I’m still quite new here and I hope I can get some help.
I’m trying to conduct a VQE algorithm on a numpy Hermition matrix. When runing with CPU, I used hermitian = qml.Hermitian(matrixReal, wires=range(qubits))
H = qml.Hamiltonian((1, ), (hermitian, ))
to convert the numpy matrixReal
to a Hamiltonian operator and use it to obtain the energy ``. It works.
However, when I try to use cuda for acceleration, it failed and put out an error sayinig
Can only compute sparse representation for tensors whose operations act on consecutive wires;
Here is my code. The error occurs on line loss = ansatz(params, H)
import numpy as np
import pennylane as qml
import matplotlib.pyplot as plt
import time
import torch
from torch.optim.lr_scheduler import StepLR
def qmlVQE(matrix, maxIter=800, rate=0.1, reps=60):
timeStart = time.time()
matrixReal = complexToRealMatrix(matrix)
qubits = round(np.log2(matrixReal.shape[0]))
dev = qml.device('default.qubit.torch', wires=qubits)
base = torch.tensor(np.random.random(size=qubits * 2 * reps), device='cuda')
base.requires_grad = True
@qml.qnode(dev, interface='torch')
def ansatz(params, H):
cnt = 0
for index in range(reps):
for i in range(qubits):
qml.RY(params[cnt], wires=[i])
cnt += 1
for i in range(qubits):
qml.RZ(params[cnt], wires=[i])
cnt += 1
for i in range(qubits-1)[(index%2)::2]:
qml.CNOT(wires=[i, i+1]);
qml.Barrier(wires=range(qubits))
return qml.expval(H)
def ansatzState(params):
cnt = 0
for index in range(reps):
for i in range(qubits):
qml.RY(params[cnt], wires=[i])
cnt += 1
for i in range(qubits):
qml.RZ(params[cnt], wires=[i])
cnt += 1
for i in range(qubits-1)[(index%2)::2]:
qml.CNOT(wires=[i, i+1]);
qml.Barrier(wires=range(qubits))
return qml.state()
history = []
plt.figure()
def callBack(energy):
plt.clf()
plt.ion()
history.append(energy)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(history)), history)
plt.axhline(y=energy, color='black', linestyle='--')
plt.text(0.8,0.2, f'Latest : {energy:.4f}', color='black', ha='center', transform=plt.gcf().transFigure)
plt.draw()
plt.pause(0.15)
hermitian = qml.Hermitian(matrixReal, wires=range(qubits))
H = qml.Hamiltonian((1, ), (hermitian, ))
def train(params):
opt = torch.optim.Adam([params], lr=rate)
scheduler = StepLR(opt, step_size=10, gamma=0.99)
def closure():
opt.zero_grad()
loss = ansatz(params, H)
loss.backward()
return loss
for n in range(maxIter):
l = opt.step(closure)
timeEnd = time.time()
value = l.item()
callBack(value)
print(f"Step = {n}, Value = {value:.8f}, Time = {(timeEnd - timeStart):.2f}")
scheduler.step()
return params
params = train(base)
psiQuantum = ansatzState(params)
psi = realToComplexEigen(psiQuantum.cpu().detach().numpy().reshape(-1, 1))
plt.ioff()
return psi
Thanks for any assistance!