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

Interface to "high-level" API (State, NetworkOperator and Expectation) #84

Merged
merged 68 commits into from
Jun 26, 2024
Merged
Show file tree
Hide file tree
Changes from 57 commits
Commits
Show all changes
68 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
600568d
Fixing mypy complaints: removing top level init files
PabloAndresCQ Jun 4, 2024
7fc94cc
Made use of library handler safer
PabloAndresCQ Jun 4, 2024
f749bfd
Renamed test file
PabloAndresCQ Jun 4, 2024
074192c
Made changes on test
PabloAndresCQ Jun 4, 2024
ee64c55
Removing dead code from example
PabloAndresCQ Jun 4, 2024
1c6f5c9
Removed outdated comment
PabloAndresCQ Jun 5, 2024
2b12bce
Refactor of GeneralState so that it adheres to the upcoming format of…
PabloAndresCQ Jun 6, 2024
0e9526b
Fixed small bugs
PabloAndresCQ Jun 6, 2024
1ab3fe6
Removed _scratch_space and _work_desc attributes from GeneralState, b…
PabloAndresCQ Jun 6, 2024
301c9f0
Updated tests so that libhandle is reused and state.destroy() is call…
PabloAndresCQ Jun 6, 2024
b6108f3
Merge pull request #126 from CQCL/refactor/exact_state
PabloAndresCQ Jun 6, 2024
b8b713c
Applying overall phase on state vector. Copying circuit when passed t…
PabloAndresCQ Jun 7, 2024
9867c46
Fixing bug due to not using local copy of circuit
PabloAndresCQ Jun 7, 2024
d2b6e25
Adding more tests and fixing some issues
PabloAndresCQ Jun 7, 2024
4aeb976
Added a test for expectation values. Changed the name of some tests
PabloAndresCQ Jun 7, 2024
44f7d6b
Allowing complex expectation value
PabloAndresCQ Jun 7, 2024
bd8d512
Updated docs
PabloAndresCQ Jun 7, 2024
608df86
Fixing a complaint from pylint
PabloAndresCQ Jun 7, 2024
dfcdcf3
Updated changelog
PabloAndresCQ Jun 7, 2024
704c9dc
Removed default choice of NUM_HYPER_SAMPLES
PabloAndresCQ Jun 7, 2024
5ef76f5
Adding copyright notice to new files
PabloAndresCQ Jun 7, 2024
7186c63
Adding error message if circuit contains non-unitary gates
PabloAndresCQ Jun 7, 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
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
PabloAndresCQ marked this conversation as resolved.
Show resolved Hide resolved
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
76 changes: 76 additions & 0 deletions pytket/extensions/cutensornet/general.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,85 @@
# 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()

@property
def handle(self) -> Any:
if self._is_destroyed:
raise RuntimeError(
"The cuTensorNet library handle is out of scope.",
"See the documentation of CuTensorNetHandle.",
)
return self._handle

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
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.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
Loading
Loading