Skip to content

Commit

Permalink
Support for V2 primitives (#843)
Browse files Browse the repository at this point in the history
* Update README.md

* Generalize the Einstein summation signature

* Add reno

* Update Copyright

* Rename and add test

* Update Copyright

* Add docstring for `test_get_einsum_signature`

* Correct spelling

* Disable spellcheck for comments

* Add `docstring` in pylint dict

* Delete example in docstring

* Add Einstein in pylint dict

* Add full use case in einsum dict

* Spelling and type ignore

* Spelling and type ignore

* Spelling and type ignore

* Spelling and type ignore

* Spelling and type ignore

* Remove for loop in einsum function and remove Literal arguments (1/2)

* Remove for loop in einsum function and remove Literal arguments (1/2)

* Remove for loop in einsum function and remove Literal arguments (2/2)

* Update RuntimeError msg

* Update RuntimeError msg - line too long

* Trigger CI

* Merge algos, globals.random to fix

* Fixed `algorithms_globals`

* Import /tests and run CI locally

* Fix copyrights and some spellings

* Ignore mypy in 8 instances

* Merge spell dicts

* Black reformatting

* Black reformatting

* Add reno

* Lint sanitize

* Pylint

* Pylint

* Pylint

* Pylint

* Fix relative imports in tutorials

* Fix relative imports in tutorials

* Remove algorithms from Jupyter magic methods

* Temporarily disable "Run stable tutorials" tests

* Change the docstrings with imports from qiskit_algorithms

* Styling

* Update qiskit_machine_learning/optimizers/gradient_descent.py

Co-authored-by: Declan Millar <[email protected]>

* Update qiskit_machine_learning/optimizers/optimizer_utils/learning_rate.py

Co-authored-by: Declan Millar <[email protected]>

* Add more tests for utils

* Add more tests for optimizers: adam, bobyqa, gsls and imfil

* Fix random seed for volatile optimizers

* Fix random seed for volatile optimizers

* Add more tests

* Pylint dict

* Activate scikit-quant-0.8.2

* Remove scikit-quant methods

* Remove scikit-quant methods (2)

* Edit the release notes and Qiskit version 1+

* Edit the release notes and Qiskit version 1+

* Add Qiskit 1.0 upgrade in reno

* Add Qiskit 1.0 upgrade in reno

* Add Qiskit 1.0 upgrade in reno

* Apply line breaks

* Restructure line breaks

* Added support for SamplerV2 primitives (#49)

* Migrating `qiskit_algorithms` (#817)

* Update README.md

* Generalize the Einstein summation signature

* Add reno

* Update Copyright

* Rename and add test

* Update Copyright

* Add docstring for `test_get_einsum_signature`

* Correct spelling

* Disable spellcheck for comments

* Add `docstring` in pylint dict

* Delete example in docstring

* Add Einstein in pylint dict

* Add full use case in einsum dict

* Spelling and type ignore

* Spelling and type ignore

* Spelling and type ignore

* Spelling and type ignore

* Spelling and type ignore

* Remove for loop in einsum function and remove Literal arguments (1/2)

* Remove for loop in einsum function and remove Literal arguments (1/2)

* Remove for loop in einsum function and remove Literal arguments (2/2)

* Update RuntimeError msg

* Update RuntimeError msg - line too long

* Trigger CI

* Merge algos, globals.random to fix

* Fixed `algorithms_globals`

* Import /tests and run CI locally

* Fix copyrights and some spellings

* Ignore mypy in 8 instances

* Merge spell dicts

* Black reformatting

* Black reformatting

* Add reno

* Lint sanitize

* Pylint

* Pylint

* Pylint

* Pylint

* Fix relative imports in tutorials

* Fix relative imports in tutorials

* Remove algorithms from Jupyter magic methods

* Temporarily disable "Run stable tutorials" tests

* Change the docstrings with imports from qiskit_algorithms

* Styling

* Update qiskit_machine_learning/optimizers/gradient_descent.py

Co-authored-by: Declan Millar <[email protected]>

* Update qiskit_machine_learning/optimizers/optimizer_utils/learning_rate.py

Co-authored-by: Declan Millar <[email protected]>

* Add more tests for utils

* Add more tests for optimizers: adam, bobyqa, gsls and imfil

* Fix random seed for volatile optimizers

* Fix random seed for volatile optimizers

* Add more tests

* Pylint dict

* Activate scikit-quant-0.8.2

* Remove scikit-quant methods

* Remove scikit-quant methods (2)

* Edit the release notes and Qiskit version 1+

* Edit the release notes and Qiskit version 1+

* Add Qiskit 1.0 upgrade in reno

* Add Qiskit 1.0 upgrade in reno

* Add Qiskit 1.0 upgrade in reno

* Apply line breaks

* Restructure line breaks

---------

Co-authored-by: FrancescaSchiav <[email protected]>
Co-authored-by: M. Emre Sahin <[email protected]>
Co-authored-by: Declan Millar <[email protected]>

* Revamp readme pt2 (#822)

* Restructure README.md
---------

Co-authored-by: Steve Wood <[email protected]>

* V2 Primitive Support for SamplerQNN and Gradients

* Update base_sampler_gradient.py

* Update qiskit_machine_learning/gradients/param_shift/param_shift_sampler_gradient.py

Co-authored-by: Edoardo Altamura <[email protected]>

* Update qiskit_machine_learning/gradients/spsa/spsa_sampler_gradient.py

Co-authored-by: Edoardo Altamura <[email protected]>

* Update qiskit_machine_learning/gradients/spsa/spsa_sampler_gradient.py

Co-authored-by: Edoardo Altamura <[email protected]>

* Update qiskit_machine_learning/neural_networks/sampler_qnn.py

Co-authored-by: Edoardo Altamura <[email protected]>

* Update qiskit_machine_learning/neural_networks/sampler_qnn.py

Co-authored-by: Edoardo Altamura <[email protected]>

* Update qiskit_machine_learning/neural_networks/sampler_qnn.py

Co-authored-by: Edoardo Altamura <[email protected]>

* Update qiskit_machine_learning/neural_networks/sampler_qnn.py

Co-authored-by: Edoardo Altamura <[email protected]>

* Update qiskit_machine_learning/neural_networks/sampler_qnn.py

Co-authored-by: Edoardo Altamura <[email protected]>

* Update qiskit_machine_learning/neural_networks/sampler_qnn.py

Co-authored-by: Edoardo Altamura <[email protected]>

* Fix lint errors due to Pylint 3.3.0 update in CI (#833)

* disable=too-many-positional-arguments

* Transfer pylint rc to toml

* Transfer pylint rc to toml

* Minor fixes

* Remove Python 3.8 from CI (#824) (#826)

* Remove Python 3.8 in CI (#824)

* Correct `tmp` dirs (#818)

* Correct unit py version (#818)

* Add reno (#818)

* Finalze removal of py38 (#818)

* Spelling

* Remove duplicate tmp folder

* Updated the release note

* Bump min pyversion in toml

* Remove ipython constraints

* Update reno

* Updated test for test_sampler_qnn

* Fix: output_shape

* Adding optimisation level to TestSamplerQNN SamplerV2 option

* Correcting the PUB prep for SamplerV2 by changing max iterator from n to len(job_param_values). Added a load of print statements to investigate behaviour when self._output_shape = (2, 3) - a tuple as this was failing tests due to a comparison in line 166. This has lead me to think that the way we are calculating QuasiDistribution is wrong as we need to know which real qubits the virtual qubits have been transpiled too to calculate the correct dist for SamplerV2. Following this up with IBM runtime.

* Update sampler_qnn.py for correcting tuple output_shape when interpret is provided.

* Adding ISA capabilities to gradients

* Fix output shape and its default for V2

* Implement SamplerV2 for bayesian inference

* Implement SamplerV2 for bayesian inference

* Adding ISA capabilities to SamplerQNN and ParamShiftSamplerGradient

* Removing unused backend

* Removing failed merge conflicts

* Removing residual merge conflicts

* added SamplerV2 support for ComputeUncompute

* Removing multiple tranpilations within same test

* Formatting

* Linting

* Adding measure_all to setUp

* removing default pm

---------

Co-authored-by: Edoardo Altamura <[email protected]>
Co-authored-by: FrancescaSchiav <[email protected]>
Co-authored-by: Declan Millar <[email protected]>
Co-authored-by: Steve Wood <[email protected]>
Co-authored-by: oscar-wallis <[email protected]>

* Added support for EstimatorV2 primitives (#48)

* Migrating `qiskit_algorithms` (#817)

* Update README.md

* Generalize the Einstein summation signature

* Add reno

* Update Copyright

* Rename and add test

* Update Copyright

* Add docstring for `test_get_einsum_signature`

* Correct spelling

* Disable spellcheck for comments

* Add `docstring` in pylint dict

* Delete example in docstring

* Add Einstein in pylint dict

* Add full use case in einsum dict

* Spelling and type ignore

* Spelling and type ignore

* Spelling and type ignore

* Spelling and type ignore

* Spelling and type ignore

* Remove for loop in einsum function and remove Literal arguments (1/2)

* Remove for loop in einsum function and remove Literal arguments (1/2)

* Remove for loop in einsum function and remove Literal arguments (2/2)

* Update RuntimeError msg

* Update RuntimeError msg - line too long

* Trigger CI

* Merge algos, globals.random to fix

* Fixed `algorithms_globals`

* Import /tests and run CI locally

* Fix copyrights and some spellings

* Ignore mypy in 8 instances

* Merge spell dicts

* Black reformatting

* Black reformatting

* Add reno

* Lint sanitize

* Pylint

* Pylint

* Pylint

* Pylint

* Fix relative imports in tutorials

* Fix relative imports in tutorials

* Remove algorithms from Jupyter magic methods

* Temporarily disable "Run stable tutorials" tests

* Change the docstrings with imports from qiskit_algorithms

* Styling

* Update qiskit_machine_learning/optimizers/gradient_descent.py

Co-authored-by: Declan Millar <[email protected]>

* Update qiskit_machine_learning/optimizers/optimizer_utils/learning_rate.py

Co-authored-by: Declan Millar <[email protected]>

* Add more tests for utils

* Add more tests for optimizers: adam, bobyqa, gsls and imfil

* Fix random seed for volatile optimizers

* Fix random seed for volatile optimizers

* Add more tests

* Pylint dict

* Activate scikit-quant-0.8.2

* Remove scikit-quant methods

* Remove scikit-quant methods (2)

* Edit the release notes and Qiskit version 1+

* Edit the release notes and Qiskit version 1+

* Add Qiskit 1.0 upgrade in reno

* Add Qiskit 1.0 upgrade in reno

* Add Qiskit 1.0 upgrade in reno

* Apply line breaks

* Restructure line breaks

---------

Co-authored-by: FrancescaSchiav <[email protected]>
Co-authored-by: M. Emre Sahin <[email protected]>
Co-authored-by: Declan Millar <[email protected]>

* Revamp readme pt2 (#822)

* Restructure README.md
---------

Co-authored-by: Steve Wood <[email protected]>

* Added support for EstimatorV2 primitives

* Update qiskit_machine_learning/neural_networks/estimator_qnn.py

Co-authored-by: Edoardo Altamura <[email protected]>

* Update qiskit_machine_learning/neural_networks/estimator_qnn.py

Co-authored-by: Edoardo Altamura <[email protected]>

* Update qiskit_machine_learning/neural_networks/estimator_qnn.py

Co-authored-by: Edoardo Altamura <[email protected]>

* Update qiskit_machine_learning/neural_networks/estimator_qnn.py

Co-authored-by: Edoardo Altamura <[email protected]>

* Update qiskit_machine_learning/gradients/param_shift/param_shift_estimator_gradient.py

Co-authored-by: Edoardo Altamura <[email protected]>

* Update qiskit_machine_learning/gradients/spsa/spsa_estimator_gradient.py

Co-authored-by: Edoardo Altamura <[email protected]>

* Update qiskit_machine_learning/gradients/param_shift/param_shift_estimator_gradient.py

Co-authored-by: Edoardo Altamura <[email protected]>

* Update qiskit_machine_learning/neural_networks/estimator_qnn.py

Co-authored-by: Edoardo Altamura <[email protected]>

* Update qiskit_machine_learning/neural_networks/estimator_qnn.py

Co-authored-by: Edoardo Altamura <[email protected]>

* Update qiskit_machine_learning/gradients/param_shift/param_shift_estimator_gradient.py

Co-authored-by: Edoardo Altamura <[email protected]>

* Fix lint errors due to Pylint 3.3.0 update in CI (#833)

* disable=too-many-positional-arguments

* Transfer pylint rc to toml

* Transfer pylint rc to toml

* Cleaner statements

* Remove Python 3.8 from CI (#824) (#826)

* Remove Python 3.8 in CI (#824)

* Correct `tmp` dirs (#818)

* Correct unit py version (#818)

* Add reno (#818)

* Finalze removal of py38 (#818)

* Spelling

* Remove duplicate tmp folder

* Updated the release note

* Bump min pyversion in toml

* Remove ipython constraints

* Update reno

* Added unit tests for estimatorqnnV2 and minor fixes

* Make black

* Make lint and changes to V1/2 choice logics

* Update requirements

* Add default precision

* Update estimator tests

* Change num qubits in backend

* Allow for num_qubits=None

* Fix shape in parameter shift

* Fix shape in parameter shift

* Fix shape observables

* Fix shape observables

* Change default precision to match base estimator

* Fix remaining shape issues

* Estimator seed has no effect in local testing

* fix argnames and supress error tolerance for test_estimator_qnn_v2

* Added pass manager the gradients.

* quick bugfix for isa_circuits

* Updating PUBs for estimatorqnn, updating test_estimator_qnn_v2 for ISA circs and relaxing tolerances

* Lint and formatting

* Tranpiling observables for isa g circs

* fixing apply_layout

---------

Co-authored-by: Edoardo Altamura <[email protected]>
Co-authored-by: FrancescaSchiav <[email protected]>
Co-authored-by: Declan Millar <[email protected]>
Co-authored-by: Steve Wood <[email protected]>
Co-authored-by: oscar-wallis <[email protected]>

* Pulled changes from main

* Quick fix

* bugfix for V1

* formatting

* Prep-ing for 0.8 (#53)

* Migrating `qiskit_algorithms` (#817)

* Update README.md

* Generalize the Einstein summation signature

* Add reno

* Update Copyright

* Rename and add test

* Update Copyright

* Add docstring for `test_get_einsum_signature`

* Correct spelling

* Disable spellcheck for comments

* Add `docstring` in pylint dict

* Delete example in docstring

* Add Einstein in pylint dict

* Add full use case in einsum dict

* Spelling and type ignore

* Spelling and type ignore

* Spelling and type ignore

* Spelling and type ignore

* Spelling and type ignore

* Remove for loop in einsum function and remove Literal arguments (1/2)

* Remove for loop in einsum function and remove Literal arguments (1/2)

* Remove for loop in einsum function and remove Literal arguments (2/2)

* Update RuntimeError msg

* Update RuntimeError msg - line too long

* Trigger CI

* Merge algos, globals.random to fix

* Fixed `algorithms_globals`

* Import /tests and run CI locally

* Fix copyrights and some spellings

* Ignore mypy in 8 instances

* Merge spell dicts

* Black reformatting

* Black reformatting

* Add reno

* Lint sanitize

* Pylint

* Pylint

* Pylint

* Pylint

* Fix relative imports in tutorials

* Fix relative imports in tutorials

* Remove algorithms from Jupyter magic methods

* Temporarily disable "Run stable tutorials" tests

* Change the docstrings with imports from qiskit_algorithms

* Styling

* Update qiskit_machine_learning/optimizers/gradient_descent.py

Co-authored-by: Declan Millar <[email protected]>

* Update qiskit_machine_learning/optimizers/optimizer_utils/learning_rate.py

Co-authored-by: Declan Millar <[email protected]>

* Add more tests for utils

* Add more tests for optimizers: adam, bobyqa, gsls and imfil

* Fix random seed for volatile optimizers

* Fix random seed for volatile optimizers

* Add more tests

* Pylint dict

* Activate scikit-quant-0.8.2

* Remove scikit-quant methods

* Remove scikit-quant methods (2)

* Edit the release notes and Qiskit version 1+

* Edit the release notes and Qiskit version 1+

* Add Qiskit 1.0 upgrade in reno

* Add Qiskit 1.0 upgrade in reno

* Add Qiskit 1.0 upgrade in reno

* Apply line breaks

* Restructure line breaks

---------

Co-authored-by: FrancescaSchiav <[email protected]>
Co-authored-by: M. Emre Sahin <[email protected]>
Co-authored-by: Declan Millar <[email protected]>

* Revamp readme pt2 (#822)

* Restructure README.md
---------

Co-authored-by: Steve Wood <[email protected]>

* Fix lint errors due to Pylint 3.3.0 update in CI (#833)

* disable=too-many-positional-arguments

* Transfer pylint rc to toml

* Transfer pylint rc to toml

* Remove Python 3.8 from CI (#824) (#826)

* Remove Python 3.8 in CI (#824)

* Correct `tmp` dirs (#818)

* Correct unit py version (#818)

* Add reno (#818)

* Finalze removal of py38 (#818)

* Spelling

* Remove duplicate tmp folder

* Updated the release note

* Bump min pyversion in toml

* Remove ipython constraints

* Update reno

* Reestablish latest Pytorch and Numpy (#818) (#827)

* Reestablish latest Pytorch and Numpy (#818)

* Keep pinned Numpy

* Keep pinned Numpy

* Fix numpy min version

* Fix RawFeatureVector for failing test case (#838)

* Alter RawFeatureVector normalization

* Alter RawFeatureVector normalization

* Release nbconvert constraints (#842)

* Remove redundant MacOS 14 image in CI (#841)

* Remove redundant MacOS 14 image

* Update with macos-latest-large

* Revert "Update with macos-latest-large"

This reverts commit 14f945e.

* Update with macos-latest-large

* Update v2 (#54)

* bugfix for V1

* formatting

---------

Co-authored-by: oscar-wallis <[email protected]>

---------

Co-authored-by: Edoardo Altamura <[email protected]>
Co-authored-by: FrancescaSchiav <[email protected]>
Co-authored-by: M. Emre Sahin <[email protected]>
Co-authored-by: Declan Millar <[email protected]>
Co-authored-by: Steve Wood <[email protected]>

* Update test_qbayesian

* Bugfixing the test_gradient

* Fixing an Options error with sampler_gradient

* Linting and formatting

* Add reno

* Fix dict typing definition

* Fix mypy

* Issue deprecation warnings

* Update skip test message

* Update deprecation warning for qbayesian.py

* Update deprecation warning for qbayesian.py

* Add headers in deprecation.py

* Add headers in deprecation.py

* Add headers in deprecation.py

* Correct spelling

* Add spelling `msg`

---------

Co-authored-by: FrancescaSchiav <[email protected]>
Co-authored-by: M. Emre Sahin <[email protected]>
Co-authored-by: Declan Millar <[email protected]>
Co-authored-by: Steve Wood <[email protected]>
Co-authored-by: oscar-wallis <[email protected]>
Co-authored-by: Emre <[email protected]>
Co-authored-by: Oscar <[email protected]>
  • Loading branch information
8 people authored Nov 11, 2024
1 parent fe7ea66 commit 2d2a249
Show file tree
Hide file tree
Showing 21 changed files with 1,581 additions and 168 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -312,4 +312,4 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: coveralls --service=github
shell: bash
shell: bash
2 changes: 2 additions & 0 deletions .pylintdict
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,7 @@ monte
mosca
mpl
mprev
msg
multiclass
multinomial
multioutput
Expand Down Expand Up @@ -501,6 +502,7 @@ sparsearray
spedalieri
spsa
sqrt
stacklevel
statefn
statevector
statevectors
Expand Down
67 changes: 56 additions & 11 deletions qiskit_machine_learning/algorithms/inference/qbayesian.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,17 @@

import copy
from typing import Tuple, Dict, Set, List

from qiskit import QuantumCircuit, ClassicalRegister
from qiskit.quantum_info import Statevector
from qiskit.circuit.library import GroverOperator
from qiskit.primitives import BaseSampler, Sampler
from qiskit.circuit import Qubit
from qiskit.circuit.library import GroverOperator
from qiskit.primitives import BaseSampler, Sampler, BaseSamplerV2, BaseSamplerV1
from qiskit.transpiler.passmanager import BasePassManager
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit.providers.fake_provider import GenericBackendV2

from ...utils.deprecation import issue_deprecation_msg


class QBayesian:
Expand Down Expand Up @@ -62,7 +68,8 @@ def __init__(
*,
limit: int = 10,
threshold: float = 0.9,
sampler: BaseSampler | None = None,
sampler: BaseSampler | BaseSamplerV2 | None = None,
pass_manager: BasePassManager | None = None,
):
"""
Args:
Expand All @@ -83,15 +90,30 @@ def __init__(
# Test valid input
for qrg in circuit.qregs:
if qrg.size > 1:
raise ValueError("Every register needs to be mapped to exactly one unique qubit")
raise ValueError("Every register needs to be mapped to exactly one unique qubit.")

# Initialize parameter
self._circ = circuit
self._limit = limit
self._threshold = threshold
if sampler is None:
sampler = Sampler()

if isinstance(sampler, BaseSamplerV1):
issue_deprecation_msg(
msg="V1 Primitives are deprecated",
version="0.8.0",
remedy="Use V2 primitives for continued compatibility and support.",
period="4 months",
)

self._sampler = sampler

if pass_manager is None:
_backend = GenericBackendV2(num_qubits=max(circuit.num_qubits, 2))
pass_manager = generate_preset_pass_manager(optimization_level=1, backend=_backend)
self._pass_manager = pass_manager

# Label of register mapped to its qubit
self._label2qubit = {qrg.name: qrg[0] for qrg in self._circ.qregs}
# Label of register mapped to its qubit index bottom up in significance
Expand Down Expand Up @@ -139,11 +161,34 @@ def _get_grover_op(self, evidence: Dict[str, int]) -> GroverOperator:

def _run_circuit(self, circuit: QuantumCircuit) -> Dict[str, float]:
"""Run the quantum circuit with the sampler."""
# Sample from circuit
job = self._sampler.run(circuit)
result = job.result()
# Get the counts of quantum state results
counts = result.quasi_dists[0].nearest_probability_distribution().binary_probabilities()
counts = {}

if isinstance(self._sampler, BaseSampler):
# Sample from circuit
job = self._sampler.run(circuit)
result = job.result()

# Get the counts of quantum state results
counts = result.quasi_dists[0].nearest_probability_distribution().binary_probabilities()

elif isinstance(self._sampler, BaseSamplerV2):

# Sample from circuit
circuit_isa = self._pass_manager.run(circuit)
job = self._sampler.run([circuit_isa])
result = job.result()

bit_array = list(result[0].data.values())[0]
bitstring_counts = bit_array.get_counts()

# Normalize the counts to probabilities
total_shots = result[0].metadata["shots"]
counts = {k: v / total_shots for k, v in bitstring_counts.items()}

# Convert to quasi-probabilities
# counts = QuasiDistribution(probabilities)
# counts = {k: v for k, v in counts.items()}

return counts

def __power_grover(
Expand Down Expand Up @@ -360,12 +405,12 @@ def limit(self, limit: int):
self._limit = limit

@property
def sampler(self) -> BaseSampler:
def sampler(self) -> BaseSampler | BaseSamplerV2:
"""Returns the sampler primitive used to compute the samples."""
return self._sampler

@sampler.setter
def sampler(self, sampler: BaseSampler):
def sampler(self, sampler: BaseSampler | BaseSamplerV2):
"""Set the sampler primitive used to compute the samples."""
self._sampler = sampler

Expand Down
28 changes: 20 additions & 8 deletions qiskit_machine_learning/gradients/base/base_estimator_gradient.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,13 @@
import numpy as np

from qiskit.circuit import Parameter, ParameterExpression, QuantumCircuit
from qiskit.primitives import BaseEstimator
from qiskit.primitives import BaseEstimator, BaseEstimatorV1
from qiskit.primitives.base import BaseEstimatorV2
from qiskit.primitives.utils import _circuit_key
from qiskit.providers import Options
from qiskit.quantum_info.operators.base_operator import BaseOperator
from qiskit.transpiler.passes import TranslateParameterizedGates
from qiskit.transpiler.passmanager import BasePassManager

from .estimator_gradient_result import EstimatorGradientResult
from ..utils import (
Expand All @@ -37,7 +39,7 @@
_make_gradient_parameters,
_make_gradient_parameter_values,
)

from ...utils.deprecation import issue_deprecation_msg
from ...algorithm_job import AlgorithmJob


Expand All @@ -46,13 +48,15 @@ class BaseEstimatorGradient(ABC):

def __init__(
self,
estimator: BaseEstimator,
estimator: BaseEstimator | BaseEstimatorV2,
options: Options | None = None,
derivative_type: DerivativeType = DerivativeType.REAL,
pass_manager: BasePassManager | None = None,
):
r"""
Args:
estimator: The estimator used to compute the gradients.
pass_manager: pass manager for isa_circuit transpilation.
options: Primitive backend runtime options used for circuit execution.
The order of priority is: options in ``run`` method > gradient's
default options > primitive's default setting.
Expand All @@ -68,7 +72,15 @@ def __init__(
gradient and this type is the only supported type for function-level schemes like
finite difference.
"""
if isinstance(estimator, BaseEstimatorV1):
issue_deprecation_msg(
msg="V1 Primitives are deprecated",
version="0.8.0",
remedy="Use V2 primitives for continued compatibility and support.",
period="4 months",
)
self._estimator: BaseEstimator = estimator
self._pass_manager = pass_manager
self._default_options = Options()
if options is not None:
self._default_options.update_options(**options)
Expand All @@ -92,7 +104,7 @@ def run(
self,
circuits: Sequence[QuantumCircuit],
observables: Sequence[BaseOperator],
parameter_values: Sequence[Sequence[float]],
parameter_values: Sequence[Sequence[float]] | np.ndarray,
parameters: Sequence[Sequence[Parameter] | None] | None = None,
**options,
) -> AlgorithmJob:
Expand Down Expand Up @@ -157,7 +169,7 @@ def _run(
self,
circuits: Sequence[QuantumCircuit],
observables: Sequence[BaseOperator],
parameter_values: Sequence[Sequence[float]],
parameter_values: Sequence[Sequence[float]] | np.ndarray,
parameters: Sequence[Sequence[Parameter]],
**options,
) -> EstimatorGradientResult:
Expand All @@ -167,7 +179,7 @@ def _run(
def _preprocess(
self,
circuits: Sequence[QuantumCircuit],
parameter_values: Sequence[Sequence[float]],
parameter_values: Sequence[Sequence[float]] | np.ndarray,
parameters: Sequence[Sequence[Parameter]],
supported_gates: Sequence[str],
) -> tuple[Sequence[QuantumCircuit], Sequence[Sequence[float]], Sequence[Sequence[Parameter]]]:
Expand Down Expand Up @@ -209,7 +221,7 @@ def _postprocess(
self,
results: EstimatorGradientResult,
circuits: Sequence[QuantumCircuit],
parameter_values: Sequence[Sequence[float]],
parameter_values: Sequence[Sequence[float]] | np.ndarray,
parameters: Sequence[Sequence[Parameter]],
) -> EstimatorGradientResult:
"""Postprocess the gradients. This method computes the gradient of the original circuits
Expand Down Expand Up @@ -269,7 +281,7 @@ def _postprocess(
def _validate_arguments(
circuits: Sequence[QuantumCircuit],
observables: Sequence[BaseOperator],
parameter_values: Sequence[Sequence[float]],
parameter_values: Sequence[Sequence[float]] | np.ndarray,
parameters: Sequence[Sequence[Parameter]],
) -> None:
"""Validate the arguments of the ``run`` method.
Expand Down
22 changes: 19 additions & 3 deletions qiskit_machine_learning/gradients/base/base_sampler_gradient.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@
from copy import copy

from qiskit.circuit import Parameter, ParameterExpression, QuantumCircuit
from qiskit.primitives import BaseSampler
from qiskit.primitives import BaseSampler, BaseSamplerV1
from qiskit.primitives.utils import _circuit_key
from qiskit.providers import Options
from qiskit.transpiler.passes import TranslateParameterizedGates
from qiskit.transpiler.passmanager import BasePassManager

from .sampler_gradient_result import SamplerGradientResult
from ..utils import (
Expand All @@ -34,14 +35,20 @@
_make_gradient_parameters,
_make_gradient_parameter_values,
)

from ...utils.deprecation import issue_deprecation_msg
from ...algorithm_job import AlgorithmJob


class BaseSamplerGradient(ABC):
"""Base class for a ``SamplerGradient`` to compute the gradients of the sampling probability."""

def __init__(self, sampler: BaseSampler, options: Options | None = None):
def __init__(
self,
sampler: BaseSampler,
options: Options | None = None,
len_quasi_dist: int | None = None,
pass_manager: BasePassManager | None = None,
):
"""
Args:
sampler: The sampler used to compute the gradients.
Expand All @@ -50,7 +57,16 @@ def __init__(self, sampler: BaseSampler, options: Options | None = None):
default options > primitive's default setting.
Higher priority setting overrides lower priority setting
"""
if isinstance(sampler, BaseSamplerV1):
issue_deprecation_msg(
msg="V1 Primitives are deprecated",
version="0.8.0",
remedy="Use V2 primitives for continued compatibility and support.",
period="4 months",
)
self._sampler: BaseSampler = sampler
self._pass_manager = pass_manager
self._len_quasi_dist = len_quasi_dist
self._default_options = Options()
if options is not None:
self._default_options.update_options(**options)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def _run(
self,
circuits: Sequence[QuantumCircuit],
observables: Sequence[BaseOperator],
parameter_values: Sequence[Sequence[float]],
parameter_values: Sequence[Sequence[float]] | np.ndarray,
parameters: Sequence[Sequence[Parameter]],
**options,
) -> EstimatorGradientResult:
Expand Down
Loading

0 comments on commit 2d2a249

Please sign in to comment.