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

Fix some issues with QNN #184

Merged
merged 7 commits into from
Aug 14, 2024
Merged
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
3 changes: 1 addition & 2 deletions quafu/algorithms/estimator.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,7 @@ def __init__(
self._task = task
else:
self._task = Task()
self._task.config(backend=self._backend)
self._task.config(**task_options)
self._task.config(backend=self._backend, **task_options)

def _run_real_machine(self, observables: Hamiltonian):
"""Submit to quafu service"""
Expand Down
41 changes: 35 additions & 6 deletions quafu/tasks/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import numpy as np
from quafu.circuits.quantum_circuit import QuantumCircuit
from quafu.users.userapi import User
from requests import Response

from ..exceptions import CircuitError, UserError, validate_server_resp
from ..results.results import ExecResult, merge_measure
Expand Down Expand Up @@ -50,10 +51,14 @@ def __init__(self, user: Optional[User] = None):
self.priority = self.user.priority
self.runtime_job_id = ""
self.submit_history = {}
self._available_backends = self.user.get_available_backends(print_info=False)
self.backend = self._available_backends[
list(self._available_backends.keys())[0]
]
self._available_backends = {}
if self.user.backend_type == "quafu":
self._available_backends = self.user.get_available_backends(
print_info=False
)
self.backend = self._available_backends[
list(self._available_backends.keys())[0]
]

def config(
self,
Expand Down Expand Up @@ -165,7 +170,7 @@ def run(self, qc: QuantumCircuit, measure_base: List = None) -> ExecResult:
measure_base (list[str, list[int]]): measure base and its positions.
"""
if measure_base is None:
res = self.send(qc)
res = self.send(qc, wait=True)
res.measure_base = ""

else:
Expand All @@ -175,11 +180,28 @@ def run(self, qc: QuantumCircuit, measure_base: List = None) -> ExecResult:
elif base == "Y":
qc.rx(pos, np.pi / 2)

res = self.send(qc)
res = self.send(qc, wait=True)
res.measure_base = measure_base

return res

def _send_runtime(self, qc: QuantumCircuit, name: str = ""):
"""send task to runtime server"""
qc.to_openqasm()
data = {
"shots": self.shots,
"selected_server": 1,
"qtasm": qc.openqasm,
"compile": int(self.compile),
"priority": 1,
"task_name": name,
"task_id": "test",
}

headers = {"Content-Type": "application/json"}
url = User.url + User.exec_api
return ClientWrapper.post(url, headers=headers, json=data)

def send(
self, qc: QuantumCircuit, name: str = "", group: str = "", wait: bool = False
) -> ExecResult:
Expand All @@ -194,6 +216,10 @@ def send(
Returns:
ExecResult object that contain the dict return from quantum device.
"""
if User.backend_type == "runtime":
resp = self._send_runtime(qc, name=name)
return self._post_send(resp, group=group)

from quafu import get_version

version = get_version()
Expand Down Expand Up @@ -248,6 +274,9 @@ def send(
raise UserError("502 Bad Gateway response")
# FIXME: Maybe we need to delete above code

return self._post_send(response, group=group)

def _post_send(self, response: Response, group: str = ""):
res_dict = response.json() # type: dict
validate_server_resp(res_dict)

Expand Down
12 changes: 7 additions & 5 deletions quafu/users/userapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ def save_apitoken(self, apitoken=None):
Save the api-token of your Quafu account.
"""
if apitoken is not None:
import warnings

warnings.warn(
"The argument 'apitoken' in this function will be deprecated "
Expand All @@ -98,7 +97,11 @@ def save_apitoken(self, apitoken=None):
# if the configuration file exists
# only update api token
with open(file_path, "r") as f:
data = json.load(f)
try:
data = json.load(f)
except Exception as e:
warnings.warn(f"Jsonfy api file failed due to {type(e)}:{e}. overriding...")
data = {"url": self.url}
data["token"] = self.api_token
else:
# if the configuration file does not exist
Expand All @@ -112,9 +115,8 @@ def save_apitoken(self, apitoken=None):

def _load_account(self):
"""
Load Quafu account, only api at present.

TODO: expand to load more user information
Load Quafu account, if any configurable attribute present in
configuration file, we will override it
"""
file_dir = os.path.join(self.token_dir, "api")
attr_names = self.__class__.list_configurable_attributes()
Expand Down
7 changes: 1 addition & 6 deletions tests/quafu/algorithms/ansatz_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"""TODO: test of ansatz needs improvement once ansatz has more featuers"""

import numpy as np
from quafu.algorithms.ansatz import AlterLayeredAnsatz, QAOAAnsatz, QuantumNeuralNetwork
from quafu.algorithms.ansatz import AlterLayeredAnsatz, QAOAAnsatz
from quafu.algorithms.hamiltonian import Hamiltonian, PauliOp


Expand All @@ -37,8 +37,3 @@ def test_build(self):
circ = AlterLayeredAnsatz(4, 4)
# print("\n ::: testing ::: \n")
# circ.plot_circuit(save_path="TestAlterLayeredAnsatz.svg")


class TestQuantumNeuralNetwork:
def test_build(self):
circ = QuantumNeuralNetwork(2, [])
3 changes: 3 additions & 0 deletions tests/quafu/algorithms/construct_qlayers_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest

pytest.importorskip("torch")
import numpy as np
from quafu.algorithms import AmplitudeEmbedding, AngleEmbedding
from quafu.algorithms.ansatz import QuantumNeuralNetwork
Expand Down
2 changes: 2 additions & 0 deletions tests/quafu/algorithms/qnn_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
# limitations under the License.
import numpy as np
import pytest

pytest.importorskip("torch")
import torch
from quafu.algorithms.ansatz import QuantumNeuralNetwork
from quafu.algorithms.gradients import compute_vjp, jacobian
Expand Down
Loading