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

[feat] GeneralBraOpKet and mutable tensors in GeneralState #165

Merged
merged 29 commits into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
e5e8872
Refactored GeneralState to use NetworkState
PabloAndresCQ Oct 16, 2024
03a0dc3
Completed refactor of GeneralState to use NetworkState
PabloAndresCQ Oct 16, 2024
432e7c4
Updated backend
PabloAndresCQ Oct 16, 2024
d205538
Cleaning up a bit
PabloAndresCQ Oct 16, 2024
535b4b2
Supporting parameters on GeneralState and Backend
PabloAndresCQ Oct 16, 2024
11c01d9
Adding get_amplitude
PabloAndresCQ Oct 21, 2024
5856f53
Linter
PabloAndresCQ Oct 21, 2024
3f94bfa
Fixed test
PabloAndresCQ Oct 21, 2024
c30efa8
Implemented GeneralBraOpKet to be used to compute arbitrary <bra|op|ket>
PabloAndresCQ Oct 22, 2024
4fe07bf
Addded support forparameterised circuits
PabloAndresCQ Oct 22, 2024
e26cb32
Pleasing linter
PabloAndresCQ Oct 22, 2024
7ad5fc2
Added support for RNG seeds
PabloAndresCQ Oct 23, 2024
7240e55
Fixed test with old configuration option
PabloAndresCQ Oct 23, 2024
13f74d8
GeneralState and GeneralBraOpKet as context managers
PabloAndresCQ Oct 23, 2024
e760ba1
Removed solved TODO comments
PabloAndresCQ Oct 23, 2024
35fee38
Updated docs
PabloAndresCQ Oct 23, 2024
ea12cbb
Fixed problems in docs
PabloAndresCQ Oct 23, 2024
beab861
More fixes to docs
PabloAndresCQ Oct 23, 2024
1c67792
Finished polishing docs
PabloAndresCQ Oct 23, 2024
3831911
Merge branch 'main' into feat/network_state
PabloAndresCQ Oct 23, 2024
f2f3e97
Merge branch 'main' into feat/network_state
PabloAndresCQ Oct 24, 2024
19344aa
Fixed a bug with parameterised circuits where the user does not provi…
PabloAndresCQ Oct 24, 2024
a522831
Added a notebook tutorial
PabloAndresCQ Oct 24, 2024
509e128
Linter
PabloAndresCQ Oct 24, 2024
e2d8d6c
Added notebooks to CI
PabloAndresCQ Oct 24, 2024
0bc00c4
Apply suggestions from code review
PabloAndresCQ Oct 24, 2024
61e2fcf
Linting
PabloAndresCQ Oct 24, 2024
c070d80
Migrate testing of example notebooks to nix and run them in CI on the…
jake-arkinstall Oct 24, 2024
ff5a88b
export LD_LIBRARY_PATH in examples test runner to expose cuda drivers
jake-arkinstall Oct 24, 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
5 changes: 0 additions & 5 deletions docs/api.rst
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
API documentation
-----------------

.. autoclass:: pytket.extensions.cutensornet.CuTensorNetHandle

.. automethod:: destroy


PabloAndresCQ marked this conversation as resolved.
Show resolved Hide resolved
.. toctree::
modules/general_state.rst
modules/structured_state.rst
9 changes: 9 additions & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@
Changelog
~~~~~~~~~

Unreleased
----------

* New API: ``GeneralBraOpKet`` for exact calculation of arbitrary ``<bra|op|ket>`` values. Can be used to calculate inner products, expectation values and arbitrary matrix elements.
* New feature: both ``GeneralState`` and ``GeneralBraOpKet`` admit circuits with parameterised gates.
* New feature: ``GeneralState`` has a new method ``get_amplitude`` to obtain the amplitude of computational basis states.
* New feature: ``GeneralState`` and ``CuTensorNetShotsBackend`` now support RNG seeds for sampling.
* Deprecated ``TensorNetwork`` object. It is still available for the sake of backwards compatibility, but it has been removed from doc pages.

0.9.0 (October 2024)
---------------------

Expand Down
23 changes: 5 additions & 18 deletions docs/modules/general_state.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,16 @@ General state (exact) simulation

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

.. automethod:: __init__
.. automethod:: sample
.. automethod:: get_amplitude
.. automethod:: get_statevector
.. automethod:: expectation_value
.. automethod:: sample
.. automethod:: destroy

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

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

.. autofunction:: pytket.extensions.cutensornet.general_state.get_operator_expectation_value

.. autofunction:: pytket.extensions.cutensornet.general_state.get_circuit_overlap
PabloAndresCQ marked this conversation as resolved.
Show resolved Hide resolved
.. autoclass:: pytket.extensions.cutensornet.general_state.GeneralBraOpKet()

.. automethod:: contract
.. automethod:: destroy

Pytket backend
~~~~~~~~~~~~~~
Expand Down
7 changes: 7 additions & 0 deletions docs/modules/structured_state.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ Structured state evolution

.. automodule:: pytket.extensions.cutensornet.structured_state

Library handle
~~~~~~~~~~~~~~

.. autoclass:: pytket.extensions.cutensornet.CuTensorNetHandle

.. automethod:: destroy


Simulation
~~~~~~~~~~
Expand Down
79 changes: 33 additions & 46 deletions pytket/extensions/cutensornet/backends/cutensornet_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
"""Methods to allow tket circuits to be run on the cuTensorNet simulator."""

from abc import abstractmethod
import warnings

from typing import List, Union, Optional, Sequence
from uuid import uuid4
Expand All @@ -24,7 +23,6 @@
from pytket.backends.backend import KwargTypes, Backend, BackendResult
from pytket.backends.backendinfo import BackendInfo
from pytket.backends.resulthandle import _ResultIdTuple
from pytket.extensions.cutensornet.general import CuTensorNetHandle
from pytket.extensions.cutensornet.general_state import (
GeneralState,
)
Expand All @@ -46,11 +44,6 @@
CustomPass,
)

try:
from cuquantum.cutensornet import StateAttribute, SamplerAttribute # type: ignore
except ImportError:
warnings.warn("local settings failed to import cuquantum", ImportWarning)

from .._metadata import __extension_version__, __extension_name__


Expand Down Expand Up @@ -203,40 +196,39 @@ def process_circuits(
corresponding get_<data> method.

Note:
Any element from the ``StateAttribute`` enum (see NVIDIA's CuTensorNet
Any element from the ``TNConfig`` enum (see NVIDIA's CuTensorNet
API) can be provided as arguments to this method. For instance:
``process_circuits(..., CONFIG_NUM_HYPER_SAMPLES=100)``.
``process_circuits(..., tn_config={"num_hyper_samples": 100})``.

Args:
circuits: List of circuits to be submitted.
n_shots: Number of shots in case of shot-based calculation.
This should be ``None``, since this backend does not support shots.
valid_check: Whether to check for circuit correctness.
tnconfig: Optional. A dict of cuTensorNet ``TNConfig`` keys and
their values.
scratch_fraction: Optional. Fraction of free memory on GPU to allocate as
scratch space. Defaults to `0.75`.
scratch space; value between 0 and 1. Defaults to ``0.8``.

Returns:
Results handle objects.
"""
scratch_fraction = float(kwargs.get("scratch_fraction", 0.75)) # type: ignore
attributes = {
k: v for k, v in kwargs.items() if k in StateAttribute._member_names_
}
scratch_fraction = float(kwargs.get("scratch_fraction", 0.8)) # type: ignore
tnconfig = kwargs.get("tnconfig", dict()) # type: ignore

circuit_list = list(circuits)
if valid_check:
self._check_all_circuits(circuit_list)
handle_list = []
with CuTensorNetHandle() as libhandle:
for circuit in circuit_list:
tn = GeneralState(circuit, libhandle)
sv = tn.get_statevector(attributes, scratch_fraction)
res_qubits = [qb for qb in sorted(circuit.qubits)]
handle = ResultHandle(str(uuid4()))
self._cache[handle] = {
"result": BackendResult(q_bits=res_qubits, state=sv)
}
handle_list.append(handle)
for circuit in circuit_list:
with GeneralState(
circuit, attributes=tnconfig, scratch_fraction=scratch_fraction
) as tn:
sv = tn.get_statevector()
res_qubits = [qb for qb in sorted(circuit.qubits)]
handle = ResultHandle(str(uuid4()))
self._cache[handle] = {"result": BackendResult(q_bits=res_qubits, state=sv)}
handle_list.append(handle)
return handle_list


Expand Down Expand Up @@ -280,33 +272,29 @@ def process_circuits(
corresponding get_<data> method.

Note:
Any element from the ``SamplerAttribute`` enum (see NVIDIA's CuTensorNet
Any element from the ``TNConfig`` enum (see NVIDIA's CuTensorNet
API) can be provided as arguments to this method. For instance:
``process_circuits(..., CONFIG_NUM_HYPER_SAMPLES=100)``.
``process_circuits(..., tn_config={"num_hyper_samples": 100})``.

Args:
circuits: List of circuits to be submitted.
n_shots: Number of shots in case of shot-based calculation.
Optionally, this can be a list of shots specifying the number of shots
for each circuit separately.
valid_check: Whether to check for circuit correctness.
seed: An optional RNG seed. Different calls to ``process_circuits`` with the
same seed will generate the same list of shot outcomes.
tnconfig: Optional. A dict of cuTensorNet ``TNConfig`` keys and
their values.
scratch_fraction: Optional. Fraction of free memory on GPU to allocate as
scratch space. Defaults to `0.75`.
scratch space; value between 0 and 1. Defaults to ``0.8``.

Returns:
Results handle objects.
"""
scratch_fraction = float(kwargs.get("scratch_fraction", 0.75)) # type: ignore
attributes = {
k: v for k, v in kwargs.items() if k in SamplerAttribute._member_names_
}

if "seed" in kwargs and kwargs["seed"] is not None:
# Current CuTensorNet does not support seeds for Sampler. I created
# a feature request in their repository.
raise NotImplementedError(
"The backend does not currently support user-defined seeds."
)
scratch_fraction = float(kwargs.get("scratch_fraction", 0.8)) # type: ignore
tnconfig = kwargs.get("tnconfig", dict()) # type: ignore
seed = kwargs.get("seed", None)

if n_shots is None:
raise ValueError(
Expand All @@ -321,14 +309,13 @@ def process_circuits(
if valid_check:
self._check_all_circuits(circuit_list)
handle_list = []
with CuTensorNetHandle() as libhandle:
for circuit, circ_shots in zip(circuit_list, all_shots):
tn = GeneralState(circuit, libhandle)
handle = ResultHandle(str(uuid4()))
self._cache[handle] = {
"result": tn.sample(circ_shots, attributes, scratch_fraction)
}
handle_list.append(handle)
for circuit, circ_shots in zip(circuit_list, all_shots):
handle = ResultHandle(str(uuid4()))
with GeneralState(
circuit, attributes=tnconfig, scratch_fraction=scratch_fraction
) as tn:
self._cache[handle] = {"result": tn.sample(circ_shots, seed=seed)}
handle_list.append(handle)
return handle_list


Expand Down
2 changes: 1 addition & 1 deletion pytket/extensions/cutensornet/general_state/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@
get_circuit_overlap,
)

from .tensor_network_state import GeneralState
from .tensor_network_state import GeneralState, GeneralBraOpKet
Loading
Loading