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

Mypy fix/exact state #123

Closed
wants to merge 56 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
56 commits
Select commit Hold shift + click to select a range
034af98
Moved modules dealing with exact TN circuit representation to s separ…
yapolyak Jan 26, 2024
0c05f1f
Started drafting `TensorNetworkState` constructor (converter).
yapolyak Jan 26, 2024
00c5b21
Finished drafting `TensorNetworkState` constructor (converter).
yapolyak Jan 30, 2024
acdf958
Subtle changes to CuTensorNetHandle (untested).
yapolyak Jan 31, 2024
657740a
Some refurbishment. Renamed `TensorNetworkState` into `GeneralState`.…
yapolyak Feb 2, 2024
73a0e20
Merged `develop` in.
yapolyak Feb 2, 2024
94d7019
Refactoring folder name: exact -> general_state
yapolyak Feb 2, 2024
3516303
Started drafting `GeneralOperator`.
yapolyak Feb 2, 2024
6695940
Finished drafting `GeneralOperator` class.
yapolyak Feb 5, 2024
2df1abb
Started drafting `GeneralExpectationValue` class.
yapolyak Feb 5, 2024
c670749
Finished drafting `GeneralExpectationValue` class.
yapolyak Feb 7, 2024
bce7c95
Added `.configure()`, `.prepare()` and drafted `compute()` in `Genera…
yapolyak Feb 7, 2024
8a6dccf
Imports additions/refactor.
yapolyak Feb 18, 2024
b1d7295
Fix in `cutn` attributes.
yapolyak Feb 18, 2024
c196e4d
Fix a bug in `GeneralState.configure()`.
yapolyak Feb 18, 2024
0faf65a
Handle device aliasing bug fix.
yapolyak Feb 18, 2024
e4defcd
Corrected `cutn.state_compute()` arguments list.
yapolyak Feb 20, 2024
4cdb622
Fixed `cutn.state_compute()`.
yapolyak Feb 23, 2024
9e64915
Factored our configure and prepare steps for `GeneralExpectationValue`.
yapolyak Feb 23, 2024
c5df6df
Fixes to `GeneralState` after debugging.
yapolyak Feb 29, 2024
5cd6936
Fixes to `GeneralOperator` after debugging.
yapolyak Feb 29, 2024
fb34305
Fixes to `GeneralExpectationValue` after debugging.
yapolyak Feb 29, 2024
1eb091f
Added `state` and `operator` properties to corresponding classes.
yapolyak Mar 1, 2024
71aff80
Enabled chaining of some methods.
yapolyak Mar 1, 2024
627d475
`GeneralOperator` now accepts `QubitPauliOperator` as parameter.
yapolyak Mar 4, 2024
106b87d
Added statevector test.
yapolyak Mar 4, 2024
3d12261
Added gate unitary transpose to account for the way cuTN stores tensors
yapolyak Mar 6, 2024
cf30aa3
Added overlap test.
yapolyak Mar 7, 2024
3d477ad
Added a toffoli box with implicit swaps test and corresponding fix to…
yapolyak Mar 7, 2024
5a0f418
Added `test_generalised_toffoli_box`.
yapolyak Mar 11, 2024
f6fce3b
A couple of bug fixes.
yapolyak Mar 11, 2024
1f35487
Merge branch 'develop' into feature/exact_state
yapolyak Mar 11, 2024
be22f4c
Updated public API docs.
yapolyak Mar 11, 2024
4d72fa1
Addressed some of mypy issues.
yapolyak Mar 11, 2024
61efd3b
Some more types fixes (some are backwards).
yapolyak Mar 11, 2024
93e8601
More mypy tweaks.
yapolyak Mar 11, 2024
4b60441
Attempt to silence pytket mypy complains.
yapolyak Mar 11, 2024
6f42404
Merge branch 'develop' into feature/exact_state
PabloAndresCQ May 29, 2024
74a1037
Removed duplicated definition of destroy
PabloAndresCQ May 29, 2024
61995ec
Fixed broken import
PabloAndresCQ Jun 4, 2024
7c46299
Applying changes from comments
PabloAndresCQ Jun 4, 2024
b2d65a4
Fixing slip-up
PabloAndresCQ Jun 4, 2024
53162e4
Removing type ignores from imports
PabloAndresCQ Jun 4, 2024
c6b1c72
Removing more type ignores from imports
PabloAndresCQ Jun 4, 2024
3954fec
Removed invalid import
PabloAndresCQ Jun 4, 2024
26f848a
Moving CuTensorNetHandle to the general.py at the root of the module
PabloAndresCQ Jun 4, 2024
6a46f2b
Attempting to pip install pytket before mypy runs
PabloAndresCQ Jun 4, 2024
6d24301
Trying with explicit scipy and ipython installations
PabloAndresCQ Jun 4, 2024
88e232a
Did I find it?
PabloAndresCQ Jun 4, 2024
87879a4
Exclude possibly offending file
PabloAndresCQ Jun 4, 2024
101c686
Restore mypy.ini file
PabloAndresCQ Jun 4, 2024
e09bc9b
Adding more ignores around Graph
PabloAndresCQ Jun 4, 2024
5dc339e
Ignoring everything in suspected file
PabloAndresCQ Jun 4, 2024
1988ee0
Reverting last commit
PabloAndresCQ Jun 4, 2024
aea8198
Removing sympy
PabloAndresCQ Jun 4, 2024
97bf3c1
Removing top init files
PabloAndresCQ Jun 4, 2024
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
1 change: 1 addition & 0 deletions .github/workflows/build-test
Original file line number Diff line number Diff line change
Expand Up @@ -61,5 +61,6 @@ fi

if [[ "${MYPY}" = "mypy" ]]
then
python -m pip install --pre -r ${GITHUB_WORKSPACE}/.github/workflows/mypy/requirements.txt
${GITHUB_WORKSPACE}/mypy-check ${GITHUB_WORKSPACE}
fi
3 changes: 3 additions & 0 deletions .github/workflows/mypy/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
scipy
ipython
pytket
2 changes: 1 addition & 1 deletion docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ API documentation
-----------------

.. toctree::
modules/fullTN.rst
modules/general_state.rst
modules/structured_state.rst
5 changes: 0 additions & 5 deletions docs/modules/fullTN.rst

This file was deleted.

32 changes: 32 additions & 0 deletions docs/modules/general_state.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
Full tensor network (general state) contraction
===============================================

.. automodule:: pytket.extensions.cutensornet.general_state

cuQuantum `contract` API interface
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. autoclass:: pytket.extensions.cutensornet.general_state.TensorNetwork

.. autoclass:: pytket.extensions.cutensornet.general_state.PauliOperatorTensorNetwork

.. autoclass:: pytket.extensions.cutensornet.general_state.ExpectationValueTensorNetwork

.. autofunction:: pytket.extensions.cutensornet.general_state.measure_qubits_state

.. autofunction:: pytket.extensions.cutensornet.general_state.tk_to_tensor_network

cuQuantum `high-level` API interface
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. autoclass:: pytket.extensions.cutensornet.general_state.GeneralState

.. autoclass:: pytket.extensions.cutensornet.general_state.GeneralOperator

.. autoclass:: pytket.extensions.cutensornet.general_state.GeneralExpectationValue

Pytket backend
~~~~~~~~~~~~~~

.. automodule:: pytket.extensions.cutensornet
:members: CuTensorNetBackend
15 changes: 3 additions & 12 deletions pytket/extensions/cutensornet/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,8 @@
# limitations under the License.
"""Module for conversion from tket primitives to cuQuantum primitives."""

# _metadata.py is copied to the folder after installation.
from ._metadata import __extension_version__, __extension_name__ # type: ignore

from .backends import CuTensorNetBackend
from .general import CuTensorNetHandle

from .tensor_network_convert import (
TensorNetwork,
PauliOperatorTensorNetwork,
ExpectationValueTensorNetwork,
tk_to_tensor_network,
measure_qubits_state,
)

from .utils import circuit_statevector_postselect
# _metadata.py is copied to the folder after installation.
from ._metadata import __extension_version__, __extension_name__ # type: ignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
from pytket.backends.backend import KwargTypes, Backend, BackendResult
from pytket.backends.backendinfo import BackendInfo
from pytket.backends.resulthandle import _ResultIdTuple
from pytket.extensions.cutensornet.tensor_network_convert import (
from pytket.extensions.cutensornet.general_state import (
TensorNetwork,
ExpectationValueTensorNetwork,
tk_to_tensor_network,
Expand Down
67 changes: 67 additions & 0 deletions pytket/extensions/cutensornet/general.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,76 @@
# 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.
from __future__ import annotations # type: ignore
import warnings
import logging
from logging import Logger

from typing import Any, Optional

try:
import cupy as cp # type: ignore
except ImportError:
warnings.warn("local settings failed to import cupy", ImportWarning)
try:
import cuquantum.cutensornet as cutn # type: ignore
except ImportError:
warnings.warn("local settings failed to import cutensornet", ImportWarning)


class CuTensorNetHandle:
"""Initialise the cuTensorNet library with automatic workspace memory
management.

Note:
Always use as ``with CuTensorNetHandle() as libhandle:`` so that cuTensorNet
handles are automatically destroyed at the end of execution.

Attributes:
handle (int): The cuTensorNet library handle created by this initialisation.
device_id (int): The ID of the device (GPU) where cuTensorNet is initialised.
If not provided, defaults to ``cp.cuda.Device()``.
"""

def __init__(self, device_id: Optional[int] = None):
self._is_destroyed = False

# Make sure CuPy uses the specified device
dev = cp.cuda.Device(device_id)
dev.use()

self.dev = dev
self.device_id = dev.id

self.handle = cutn.create()

def destroy(self) -> None:
"""Destroys the memory handle, releasing memory.

Only call this method if you are initialising a ``CuTensorNetHandle`` outside
a ``with CuTensorNetHandle() as libhandle`` statement.
"""
cutn.destroy(self.handle)
self._is_destroyed = True

def __enter__(self) -> CuTensorNetHandle:
return self

def __exit__(self, exc_type: Any, exc_value: Any, exc_tb: Any) -> None:
self.destroy()

def print_device_properties(self, logger: Logger) -> None:
"""Prints local GPU properties."""
device_props = cp.cuda.runtime.getDeviceProperties(self.dev.id)
logger.debug("===== device info ======")
logger.debug("GPU-name:", device_props["name"].decode())
logger.debug("GPU-clock:", device_props["clockRate"])
logger.debug("GPU-memoryClock:", device_props["memoryClockRate"])
logger.debug("GPU-nSM:", device_props["multiProcessorCount"])
logger.debug("GPU-major:", device_props["major"])
logger.debug("GPU-minor:", device_props["minor"])
logger.debug("========================")


def set_logger(
logger_name: str,
Expand Down
26 changes: 26 additions & 0 deletions pytket/extensions/cutensornet/general_state/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Copyright 2019-2024 Quantinuum
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# 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.
"""Module for conversion from tket primitives to cuQuantum primitives."""

from .utils import circuit_statevector_postselect

from .tensor_network_convert import (
TensorNetwork,
PauliOperatorTensorNetwork,
ExpectationValueTensorNetwork,
tk_to_tensor_network,
measure_qubits_state,
)

from .tensor_network_state import GeneralState, GeneralOperator, GeneralExpectationValue
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,9 @@
from networkx.classes.reportviews import OutMultiEdgeView, OutMultiEdgeDataView # type: ignore
import numpy as np
from numpy.typing import NDArray
from pytket import Qubit # type: ignore
from pytket.utils import Graph
from pytket.pauli import QubitPauliString # type: ignore
from pytket.circuit import Circuit, Qubit # type: ignore
from pytket.utils import Graph # type: ignore
from pytket.pauli import QubitPauliString
from pytket.circuit import Circuit, Qubit
from pytket.utils import permute_rows_cols_in_unitary
from pytket.extensions.cutensornet.general import set_logger

Expand Down Expand Up @@ -53,18 +52,18 @@ def __init__(
# self._circuit.replace_implicit_wire_swaps()
self._qubit_names_ilo = [str(q) for q in self._circuit.qubits]
self._logger.debug(f"ILO-ordered qubit names: {self._qubit_names_ilo}")
self._graph = Graph(self._circuit)
self._graph = Graph(self._circuit) # type: ignore
qname_to_q = {
qname: q for qname, q in zip(self._qubit_names_ilo, self._circuit.qubits)
}
self._output_index_to_qubit = {
oi: qname_to_q[qname] for oi, qname in self._graph.output_names.items()
oi: qname_to_q[qname] for oi, qname in self._graph.output_names.items() # type: ignore
}
self._logger.debug(
f"NX output index to (possibly re-labeled) qubit objects map: "
f"{self._output_index_to_qubit}"
)
self._network = self._graph.as_nx()
self._network = self._graph.as_nx() # type: ignore
self._node_tensors = self._assign_node_tensors(adj=adj)
self._node_tensor_indices, self.sticky_indices = self._get_tn_indices(
self._network, adj=adj
Expand Down Expand Up @@ -264,14 +263,14 @@ def _get_tn_indices(
nodes_out = self._output_nodes
# Re-order outward edges indices according to ILO
edges_out = [
edge for edge in net.edges() if edge[1] in self._graph.output_names
edge for edge in net.edges() if edge[1] in self._graph.output_names # type: ignore
]
eids = [
record[0][0] for key, record in edge_indices.items() if key in edges_out
]
eids_sorted = sorted(eids, key=abs)
qnames_graph_ordered = [qname for qname in self._graph.output_names.values()]
oids_graph_ordered = [oid for oid in self._graph.output_names.keys()]
qnames_graph_ordered = [qname for qname in self._graph.output_names.values()] # type: ignore
oids_graph_ordered = [oid for oid in self._graph.output_names.keys()] # type: ignore
eids_qubit_ordered = [
eids_sorted[qnames_graph_ordered.index(q)] for q in self._qubit_names_ilo
] # Order eid's in the same way as qnames_graph_ordered as compared to ILO
Expand Down
Loading
Loading