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

Rename: OneMinusFidelity(...) -> MaximizeStateFidelity(...).loss_function #35

Draft
wants to merge 1 commit 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
2 changes: 1 addition & 1 deletion docs/apidocs/objective.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ Objective function(s) (:mod:`qiskit_addon_aqc_tensor.objective`)

.. currentmodule:: qiskit_addon_aqc_tensor.objective

.. autoclass:: OneMinusFidelity
.. autoclass:: MaximizeStateFidelity
:special-members: __call__
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@
# ----------------------------------------------------------------------------------

_inlined_apis = [
("qiskit_addon_aqc_tensor.objective", "OneMinusFidelity"),
("qiskit_addon_aqc_tensor.objective", "MaximizeStateFidelity"),
("qiskit_addon_aqc_tensor.simulation", "TensorNetworkState"),
("qiskit_addon_aqc_tensor.simulation", "TensorNetworkSimulationSettings"),
("qiskit_addon_aqc_tensor.simulation", "tensornetwork_from_circuit"),
Expand Down
2 changes: 1 addition & 1 deletion docs/explanation/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ For this reason, if you are attempting to experiment with AQC-Tensor on a toy pr
Objective function
~~~~~~~~~~~~~~~~~~

Currently, this addon provides one very simple objective function, :class:`.OneMinusFidelity`, which is equivalent to Eq. (7) in Ref. [1]_. When an object of this class is called with an array of parameters, it will return both the value and the gradient of that objective function at that point in parameter space.
Currently, this addon provides one very simple objective function, :class:`.MaximizeStateFidelity`, whose loss function is equivalent to Eq. (7) in Ref. [1]_. When an object of this class is called with an array of parameters, it will return both the value and the gradient of that objective function at that point in parameter space.

Gradient
~~~~~~~~
Expand Down
4 changes: 2 additions & 2 deletions docs/how-tos/01_quimb_tnoptimizer.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,9 @@
"metadata": {},
"outputs": [],
"source": [
"from qiskit_addon_aqc_tensor.objective import OneMinusFidelity\n",
"from qiskit_addon_aqc_tensor.objective import MaximizeStateFidelity\n",
"\n",
"objective = OneMinusFidelity(target_tns, None, None)"
"objective = MaximizeStateFidelity(target_tns, None, None)"
]
},
{
Expand Down
8 changes: 4 additions & 4 deletions docs/tutorials/01_initial_state_aqc.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@
"source": [
"### Optimize the parameters of the ansatz using MPS calculations\n",
"\n",
"Here, we minimize the simplest possible cost function, `OneMinusFidelity`, by using the L-BFGS optimizer from scipy.\n",
"Here, we minimize the simplest possible cost function, `MaximizeStateFidelity`, by using the L-BFGS optimizer from scipy.\n",
"\n",
"We choose a stopping point for the fidelity such that it will be above what the comparison circuit would have been, without using AQC. Once this is reached, the compressed circuit has less Trotter error _and_ less depth than the original circuit. Given more processing time, further optimization steps can be performed to bring the fidelity even higher."
]
Expand Down Expand Up @@ -417,9 +417,9 @@
"source": [
"from scipy.optimize import OptimizeResult, minimize\n",
"\n",
"from qiskit_addon_aqc_tensor.objective import OneMinusFidelity\n",
"from qiskit_addon_aqc_tensor.objective import MaximizeStateFidelity\n",
"\n",
"objective = OneMinusFidelity(aqc_target_mps, aqc_ansatz, simulator_settings)\n",
"objective = MaximizeStateFidelity(aqc_target_mps, aqc_ansatz, simulator_settings)\n",
"\n",
"stopping_point = 1 - comparison_fidelity\n",
"\n",
Expand All @@ -432,7 +432,7 @@
"\n",
"\n",
"result = minimize(\n",
" objective,\n",
" objective.loss_function,\n",
" aqc_initial_parameters,\n",
" method=\"L-BFGS-B\",\n",
" jac=True,\n",
Expand Down
13 changes: 9 additions & 4 deletions qiskit_addon_aqc_tensor/objective.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

"""Code for building and evaluating objective functions used for AQC parameter optimization.

Currently, this module provides the simplest possible objective function, :class:`.OneMinusFidelity`.
Currently, this module provides the simplest possible objective function, :class:`.MaximizeStateFidelity`.
"""

from __future__ import annotations
Expand All @@ -29,7 +29,7 @@
)


class OneMinusFidelity:
class MaximizeStateFidelity:
r"""Simplest possible objective function for use with AQC-Tensor.

Its definition is given by Eq. (7) in `arXiv:2301.08609v6 <https://arxiv.org/abs/2301.08609v6>`__:
Expand Down Expand Up @@ -71,14 +71,19 @@ def __init__(

self._preprocessed = _preprocess_for_gradient(self, settings)

def __call__(self, x: np.ndarray) -> tuple[float, np.ndarray]:
def loss_function(self, x: np.ndarray) -> tuple[float, np.ndarray]:
"""Evaluate ``(objective_value, gradient)`` of function at point ``x``."""
from .simulation.abstract import _compute_objective_and_gradient

return _compute_objective_and_gradient(
self, self._simulation_settings, self._preprocessed, x
)

# FIXME: deprecate
def __call__(self, x: np.ndarray) -> tuple[float, np.ndarray]:
"""Evaluate ``(objective_value, gradient)`` of function at point ``x``."""
return self.loss_function(x)

@property
def target(self) -> TensorNetworkState:
"""Target tensor network."""
Expand All @@ -87,5 +92,5 @@ def target(self) -> TensorNetworkState:

# Reminder: update the RST file in docs/apidocs when adding new interfaces.
__all__ = [
"OneMinusFidelity",
"MaximizeStateFidelity",
]
4 changes: 2 additions & 2 deletions qiskit_addon_aqc_tensor/simulation/aer/gradient.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
QuantumCircuit,
)

from ...objective import OneMinusFidelity
from ...objective import MaximizeStateFidelity
from ..abstract import (
apply_circuit_to_state,
compute_overlap,
Expand All @@ -44,7 +44,7 @@ def _preprocess_for_gradient(objective, settings: Union[QiskitAerSimulationSetti

@dispatch
def _compute_objective_and_gradient(
objective: OneMinusFidelity,
objective: MaximizeStateFidelity,
settings: Union[QiskitAerSimulationSettings, AerSimulator],
preprocess_info,
x: np.ndarray,
Expand Down
12 changes: 6 additions & 6 deletions qiskit_addon_aqc_tensor/simulation/quimb/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
from wrapt import register_post_import_hook

from ...ansatz_generation import AnsatzBlock
from ...objective import OneMinusFidelity
from ...objective import MaximizeStateFidelity
from ..abstract import TensorNetworkSimulationSettings
from ..explicit_gradient import (
compute_gradient_of_tensornetwork_overlap,
Expand Down Expand Up @@ -309,7 +309,7 @@ def __init__(self, objective, settings):

@dispatch
def _compute_objective_and_gradient(
objective: OneMinusFidelity,
objective: MaximizeStateFidelity,
settings: QuimbSimulator,
preprocess_info: _ExplicitGradientContext,
x: np.ndarray,
Expand Down Expand Up @@ -347,7 +347,7 @@ def __init__(self, objective, settings):

@dispatch
def _compute_objective_and_gradient(
_: OneMinusFidelity,
_: MaximizeStateFidelity,
__: QuimbSimulator,
preprocess_info: _QuimbGradientContext,
qiskit_parameter_values: np.ndarray,
Expand All @@ -371,7 +371,7 @@ def _compute_objective_and_gradient(


@dispatch
def tnoptimizer_objective_kwargs(objective: OneMinusFidelity, /) -> dict[str, Any]:
def tnoptimizer_objective_kwargs(objective: MaximizeStateFidelity, /) -> dict[str, Any]:
"""Return keyword arguments for use with :func:`~quimb.tensor.TNOptimizer`.

- ``loss_fn``
Expand All @@ -383,12 +383,12 @@ def tnoptimizer_objective_kwargs(objective: OneMinusFidelity, /) -> dict[str, An
if isinstance(target, qtn.Circuit):
target = target.psi
return {
"loss_fn": oneminusfidelity_loss_fn,
"loss_fn": maximize_state_fidelity_loss_function,
"loss_kwargs": {"target": target},
}


def oneminusfidelity_loss_fn(
def maximize_state_fidelity_loss_function(
circ: quimb.tensor.Circuit, /, *, target: quimb.tensor.TensorNetworkGenVector
):
"""Loss function for use with Quimb, compatible with automatic differentiation.
Expand Down
4 changes: 2 additions & 2 deletions test/simulation/test_gradient.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from qiskit.circuit import Parameter
from qiskit.circuit.library import EfficientSU2, TwoLocal

from qiskit_addon_aqc_tensor.objective import OneMinusFidelity
from qiskit_addon_aqc_tensor.objective import MaximizeStateFidelity
from qiskit_addon_aqc_tensor.simulation import (
apply_circuit_to_state,
compute_overlap,
Expand Down Expand Up @@ -108,7 +108,7 @@ def vdagger_rhs(thetas):
bound_qc = qc.assign_parameters(thetas)
return apply_circuit_to_state(bound_qc.inverse(), rhs_mps, settings)

objective = OneMinusFidelity(rhs_mps, qc, settings)
objective = MaximizeStateFidelity(rhs_mps, qc, settings)
preprocess_info = _preprocess_for_gradient(objective, settings)
_, grad = _compute_objective_and_gradient(objective, settings, preprocess_info, thetas)

Expand Down
6 changes: 3 additions & 3 deletions test/test_aqc_workflows.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
AnsatzBlock,
generate_ansatz_from_circuit,
)
from qiskit_addon_aqc_tensor.objective import OneMinusFidelity
from qiskit_addon_aqc_tensor.objective import MaximizeStateFidelity
from qiskit_addon_aqc_tensor.simulation import (
compute_overlap,
tensornetwork_from_circuit,
Expand Down Expand Up @@ -55,9 +55,9 @@ def test_basic_workflow(available_backend_fixture, circuit_pair):
ansatz, initial_parameters = generate_ansatz_from_circuit(
good_circuit, qubits_initially_zero=True
)
objective = OneMinusFidelity(target_mps, ansatz, simulator_settings)
objective = MaximizeStateFidelity(target_mps, ansatz, simulator_settings)
result = minimize(
objective,
objective.loss_function,
initial_parameters,
method="L-BFGS-B",
jac=True,
Expand Down
2 changes: 1 addition & 1 deletion test/test_star_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def test_star_imports():
assert generate_ansatz_from_circuit.__name__ == "generate_ansatz_from_circuit"
assert KAK.__name__ == "KAK"
assert preprocess_circuit_for_backtracking.__name__ == "preprocess_circuit_for_backtracking"
assert OneMinusFidelity.__name__ == "OneMinusFidelity"
assert MaximizeStateFidelity.__name__ == "MaximizeStateFidelity"
assert TensorNetworkState.__name__ == "TensorNetworkState"
assert QiskitAerMPS.__name__ == "QiskitAerMPS"
assert QuimbSimulator.__name__ == "QuimbSimulator"