Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add the support for tensor network benchmarking #43

Draft
wants to merge 14 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 44 additions & 2 deletions benchmarks/libraries/qibo.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,33 @@

class Qibo(abstract.AbstractBackend):

def __init__(self, max_qubits="0", backend="qibojit", platform=None, accelerators=""):
def __init__(self, max_qubits="0", backend="qibojit", platform=None, accelerators="",expectation=None,computation_settings=None):
import qibo
qibo.set_backend(backend=backend, platform=platform)

runcard=None

if computation_settings is not None:
import json

with open(computation_settings, 'r') as f:
runcard = json.load(f)

if runcard["expectation_enabled"]==True:
expectation = True

qibo.set_backend(backend=backend, platform=platform, runcard=runcard)
else:
qibo.set_backend(backend=backend, platform=platform)

from qibo import models
self.name = "qibo"
self.qibo = qibo
self.models = models
self.__version__ = qibo.__version__
self.max_qubits = int(max_qubits)
self.accelerators = self._parse_accelerators(accelerators)
self.expectation_flag = expectation
self.backend_name_str = backend

def from_qasm(self, qasm):
circuit = self.models.Circuit.from_qasm(qasm, accelerators=self.accelerators)
Expand All @@ -24,10 +41,35 @@ def from_qasm(self, qasm):
circuit = circuit.fuse()
return circuit

'''
def __call__(self, circuit):
# transfer final state to numpy array because that's what happens
# for all backends
return circuit().state(numpy=True)
'''
def __call__(self, circuit):
# transfer final state to numpy array because that's what happens
# for all backends
if self.backend_name_str == "qibojit" and self.expectation_flag is not None:
from qibo.symbols import X,Y,Z,I
from qibo.hamiltonians import SymbolicHamiltonian
import numpy as np
from qibo.backends import GlobalBackend
backend = GlobalBackend()
# self.expectation_flag must contain pauli string pattern for it to work
list_of_objects = []
gate_mapping = {"I": I, "X": X, "Y": Y, "Z": Z}

for i in range(circuit.nqubits):
gate = gate_mapping[self.expectation_flag[i % len(self.expectation_flag)]]
list_of_objects.append(gate(i))
obs = np.prod(list_of_objects)
obs = SymbolicHamiltonian(obs, backend=backend)

# Noise-free expected value
return obs.expectation(backend.execute_circuit(circuit).state())
else:
return circuit().state(numpy=True)

def transpose_state(self, x):
return x
Expand Down
112 changes: 111 additions & 1 deletion benchmarks/scripts.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import time
from benchmarks.logger import JsonLogger


def circuit_benchmark(nqubits, backend, circuit_name, circuit_options=None,
nreps=1, nshots=None, transfer=False,
precision="double", memory=None, threading=None,
Expand Down Expand Up @@ -133,6 +132,117 @@ def library_benchmark(nqubits, library, circuit_name, circuit_options=None,
logs.dump()
return logs

def qibotn_benchmark(nqubits, library, circuit_name, circuit_options=None,
library_options=None, precision=None, nreps=1,
filename=None):
"""Runs benchmark for different quantum simulation libraries.

See ``benchmarks/compare.py`` for documentation of each argument.
"""
from mpi4py import MPI # this line initializes MPI
import numpy as np
import cupy as cp

try:
# Try to create MPI.COMM_WORLD
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
except MPI.Exception:
# MPI is not available or not launched deliberately, set rank to 0
rank = 0

if rank == 0:
logs = JsonLogger(filename)
logs.log(nqubits=nqubits, nreps=nreps)

if rank == 0:
start_time = time.time()
from benchmarks import libraries
backend = libraries.get(library, library_options)
if rank == 0:
logs.log(import_time=time.time() - start_time)
logs.log(library_options=library_options)
if precision is not None:

backend.set_precision(precision)
backend.expectation_flag

if rank == 0:
logs.log(library=backend.name,
precision=backend.get_precision(),
device=backend.get_device(),
version=backend.__version__)

from benchmarks import circuits
gates = circuits.get(circuit_name, nqubits, circuit_options)
#gates = circuits.get(circuit_name, nqubits, circuit_options, True) #use qibo gate

if rank == 0:
logs.log(circuit=circuit_name, circuit_options=str(gates))
start_time = time.time()
circuit = backend.from_qasm(gates.to_qasm())

if rank == 0:
logs.log(creation_time=time.time() - start_time)

start_time = time.time()
result = backend(circuit)
if rank == 0:
logs.log(dry_run_time=time.time() - start_time)
dtype = str(result.dtype)
del(result)

if rank == 0:
simulation_times = []
if backend.expectation_flag is not None:
expectation_result = []
for _ in range(nreps):
if rank == 0:
start_time = time.time()
result = backend(circuit)
if isinstance(result, cp.ndarray):
result = cp.asnumpy(result)
else:
result = np.array([result])

if rank == 0:
simulation_times.append(time.time() - start_time)
#if _==0:
#modified_string = library_options.replace("=", "_")
#modified_string = modified_string.replace(",", "")
#filename = modified_string+str(circuit.nqubits)+".dat"
#np.savetxt(filename,result)
#print(result)
if backend.expectation_flag is not None:
magnitude = np.abs(result[0])
magnitude_list = magnitude.tolist()

expectation_result.append(magnitude_list)
'''
else:
components = library_options.split(',')

# Iterate through the components to find the one that starts with "platform="
for component in components:
if component.startswith("platform="):
# Extract the platform value
platform_value = component.split('=')[1]
print("Platform:", platform_value)
break
output_text = backend.name + '_' + circuit_name + '_' +platform_value + '_' +str(nqubits) + '.npz'
np.savez(output_text, result)
'''
del(result)

if rank == 0:
logs.log(dtype=dtype, simulation_times=simulation_times)
logs.average("simulation_times")
if backend.expectation_flag is not None:
logs.log(dtype=dtype, expectation_result=expectation_result)
logs.average("expectation_result")
logs.dump()
return logs


def evolution_benchmark(nqubits, dt, solver, backend, platform=None,
nreps=1, precision="double", dense=False,
Expand Down
Loading