Skip to content

Commit

Permalink
Merge branch 'master' into rmv-qnode-static-methods
Browse files Browse the repository at this point in the history
  • Loading branch information
andrijapau authored Jan 15, 2025
2 parents 5514dd1 + 3bec1cd commit f9cc523
Show file tree
Hide file tree
Showing 25 changed files with 211 additions and 744 deletions.
22 changes: 11 additions & 11 deletions doc/development/deprecations.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,6 @@ deprecations are listed below.
Pending deprecations
--------------------

* The ``qsvt_legacy`` function has been deprecated.
Instead, use ``qml.qsvt``. The new functionality takes an input polynomial instead of angles.

- Deprecated in v0.40
- Will be removed in v0.41

* The ``tape`` and ``qtape`` properties of ``QNode`` have been deprecated.
Instead, use the ``qml.workflow.construct_tape`` function.

Expand All @@ -31,11 +25,6 @@ Pending deprecations
- Deprecated in v0.40
- Will be removed in v0.41

* The ``output_dim`` property of ``qml.tape.QuantumScript`` has been deprecated. Instead, use method ``shape`` of ``QuantumScript`` or ``MeasurementProcess`` to get the same information.

- Deprecated in v0.40
- Will be removed in v0.41

* The ``gradient_fn`` keyword argument to ``qml.execute`` has been renamed ``diff_method``.

- Deprecated in v0.40
Expand Down Expand Up @@ -86,6 +75,17 @@ Completed deprecation cycles

* The ``QNode.get_best_method`` and ``QNode.best_method_str`` methods have been removed.
Instead, use the ``qml.workflow.get_best_diff_method`` function.

- Deprecated in v0.40
- Removed in v0.41

* The ``output_dim`` property of ``qml.tape.QuantumScript`` has been removed. Instead, use method ``shape`` of ``QuantumScript`` or ``MeasurementProcess`` to get the same information.

- Deprecated in v0.40
- Removed in v0.41

* The ``qml.qsvt_legacy`` function has been removed.
Instead, use ``qml.qsvt``. The new functionality takes an input polynomial instead of angles.

- Deprecated in v0.40
- Removed in v0.41
Expand Down
2 changes: 1 addition & 1 deletion doc/releases/changelog-0.40.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -1170,4 +1170,4 @@ Anton Naim Ibrahim,
Andrija Paurevic,
Justin Pickering,
Jay Soni,
David Wierichs.
David Wierichs.
14 changes: 13 additions & 1 deletion doc/releases/changelog-dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,21 @@

<h3>Improvements 🛠</h3>

* The coefficients of observables now have improved differentiability.
[(#6598)](https://github.com/PennyLaneAI/pennylane/pull/6598)

<h3>Breaking changes 💔</h3>

* The ``QNode.get_best_method`` and ``QNode.best_method_str`` methods have been removed.
Instead, use the ``qml.workflow.get_best_diff_method`` function.
[(#6823)](https://github.com/PennyLaneAI/pennylane/pull/6823)

* The `output_dim` property of `qml.tape.QuantumScript` has been removed. Instead, use method `shape` of `QuantumScript` or `MeasurementProcess` to get the same information.
[(#6829)](https://github.com/PennyLaneAI/pennylane/pull/6829)

* Removed method `qsvt_legacy` along with its private helper `_qsp_to_qsvt`
[(#6827)](https://github.com/PennyLaneAI/pennylane/pull/6827)

<h3>Deprecations 👋</h3>

<h3>Documentation 📝</h3>
Expand All @@ -24,4 +33,7 @@
<h3>Contributors ✍️</h3>

This release contains contributions from (in alphabetical order):
Diksha Dhawan

Yushao Chen,
Diksha Dhawan,
Christina Lee,
2 changes: 1 addition & 1 deletion pennylane/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@
Version number (major.minor.patch[-label])
"""

__version__ = "0.41.0-dev6"
__version__ = "0.41.0-dev7"
2 changes: 1 addition & 1 deletion pennylane/compiler/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

from packaging.version import Version

PL_CATALYST_MIN_VERSION = Version("0.9.0")
PL_CATALYST_MIN_VERSION = Version("0.10.0")


class CompileError(Exception):
Expand Down
1 change: 0 additions & 1 deletion pennylane/devices/_legacy_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@ def _local_tape_expand(tape, depth, stop_at):

# Update circuit info
new_tape._batch_size = tape._batch_size
new_tape._output_dim = tape._output_dim
return new_tape


Expand Down
26 changes: 21 additions & 5 deletions pennylane/gradients/parameter_shift.py
Original file line number Diff line number Diff line change
Expand Up @@ -752,6 +752,12 @@ def _param_shift_stopping_condition(op) -> bool:
return True


def _inplace_set_trainable_params(tape):
"""Update all the trainable params in place."""
params = tape.get_parameters(trainable_only=False)
tape.trainable_params = qml.math.get_trainable_indices(params)


def _expand_transform_param_shift(
tape: QuantumScript,
argnum=None,
Expand All @@ -769,11 +775,21 @@ def _expand_transform_param_shift(
name="param_shift",
error=qml.operation.DecompositionUndefinedError,
)
if new_tape is tape:
return [tape], postprocessing
params = new_tape.get_parameters(trainable_only=False)
new_tape.trainable_params = qml.math.get_trainable_indices(params)
return [new_tape], postprocessing
if any(
qml.math.requires_grad(d) for mp in tape.measurements for d in getattr(mp.obs, "data", [])
):
try:
batch, postprocessing = qml.transforms.split_to_single_terms(new_tape)
except RuntimeError as e:
raise ValueError(
"Can only differentiate Hamiltonian "
f"coefficients for expectations, not {tape.measurements}."
) from e
else:
batch = [new_tape]
if len(batch) > 1 or batch[0] is not tape:
_ = [_inplace_set_trainable_params(t) for t in batch]
return batch, postprocessing


@partial(
Expand Down
10 changes: 6 additions & 4 deletions pennylane/ops/functions/dot.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,10 +142,12 @@ def dot(
f"ops must be an Iterable of {t.__name__}'s, not a {t.__name__} itself."
)

if len(coeffs) != len(ops):
raise ValueError("Number of coefficients and operators does not match.")
if len(coeffs) == 0 and len(ops) == 0:
raise ValueError("Cannot compute the dot product of an empty sequence.")
# tensorflow variables have no len
if qml.math.get_interface(coeffs) != "tensorflow":
if len(coeffs) != len(ops):
raise ValueError("Number of coefficients and operators does not match.")
if len(coeffs) == 0 and len(ops) == 0:
raise ValueError("Cannot compute the dot product of an empty sequence.")

for t in (Operator, PauliWord, PauliSentence):
if isinstance(ops, t):
Expand Down
2 changes: 0 additions & 2 deletions pennylane/ops/op_math/sprod.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
This file contains the implementation of the SProd class which contains logic for
computing the scalar product of operations.
"""
from copy import copy
from typing import Union

import pennylane as qml
Expand Down Expand Up @@ -148,7 +147,6 @@ def __init__(
elif (base_pauli_rep := getattr(self.base, "pauli_rep", None)) and (
self.batch_size is None
):
scalar = copy(self.scalar)

pr = {pw: qnp.dot(coeff, scalar) for pw, coeff in base_pauli_rep.items()}
self._pauli_rep = qml.pauli.PauliSentence(pr)
Expand Down
51 changes: 1 addition & 50 deletions pennylane/tape/qscript.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from typing import Any, Optional, TypeVar, Union

import pennylane as qml
from pennylane.measurements import MeasurementProcess, ProbabilityMP, StateMP
from pennylane.measurements import MeasurementProcess
from pennylane.measurements.shots import Shots, ShotsLike
from pennylane.operation import _UNSET_BATCH_SIZE, Observable, Operation, Operator
from pennylane.pytrees import register_pytree
Expand Down Expand Up @@ -183,7 +183,6 @@ def __init__(
self._trainable_params = trainable_params
self._graph = None
self._specs = None
self._output_dim = None
self._batch_size = _UNSET_BATCH_SIZE

self._obs_sharing_wires = None
Expand Down Expand Up @@ -322,29 +321,6 @@ def batch_size(self) -> Optional[int]:
self._update_batch_size()
return self._batch_size

@property
def output_dim(self) -> int:
"""The (inferred) output dimension of the quantum script.
.. warning::
``QuantumScript.output_dim`` is being deprecated. Instead, considering
using method ``shape`` of ``QuantumScript`` or ``MeasurementProcess``
to get the same information. See ``qml.gradients.parameter_shift_cv.py::_get_output_dim``
for an example.
"""
# pylint: disable=import-outside-toplevel
import warnings

warnings.warn(
"The 'output_dim' property is deprecated and will be removed in version 0.41",
qml.PennyLaneDeprecationWarning,
)
if self._output_dim is None:
self._update_output_dim() # this will set _batch_size if it isn't already
return self._output_dim

@property
def diagonalizing_gates(self) -> list[Operation]:
"""Returns the gates that diagonalize the measured wires such that they
Expand Down Expand Up @@ -566,28 +542,6 @@ def _update_batch_size(self):

self._batch_size = candidate

def _update_output_dim(self):
"""Update the dimension of the output of the quantum script.
Sets:
self._output_dim (int): Size of the quantum script output (when flattened)
This method makes use of `self.batch_size`, so that `self._batch_size`
needs to be up to date when calling it.
Call `_update_batch_size` before `_update_output_dim`
"""
self._output_dim = 0
for m in self.measurements:
# attempt to infer the output dimension
if isinstance(m, ProbabilityMP):
# TODO: what if we had a CV device here? Having the base as
# 2 would have to be swapped to the cutoff value
self._output_dim += 2 ** len(m.wires)
elif not isinstance(m, StateMP):
self._output_dim += 1
if self.batch_size:
self._output_dim *= self.batch_size

# ========================================================
# Parameter handling
# ========================================================
Expand Down Expand Up @@ -984,9 +938,6 @@ def copy(self, copy_operations: bool = False, **update) -> "QuantumScript":
# obs may change if measurements were updated
new_qscript._obs_sharing_wires = self._obs_sharing_wires
new_qscript._obs_sharing_wires_id = self._obs_sharing_wires_id
if not (update.get("measurements") or update.get("operations")):
# output_dim may change if either measurements or operations were updated
new_qscript._output_dim = self._output_dim
return new_qscript

def __copy__(self) -> "QuantumScript":
Expand Down
2 changes: 0 additions & 2 deletions pennylane/tape/tape.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,6 @@ def stop_at(obj): # pylint: disable=unused-argument

# Update circuit info
new_tape._batch_size = tape._batch_size
new_tape._output_dim = tape._output_dim
return new_tape


Expand Down Expand Up @@ -343,7 +342,6 @@ def expand_tape_state_prep(tape, skip_first=True):

# Update circuit info
new_tape._batch_size = tape._batch_size
new_tape._output_dim = tape._output_dim
return new_tape


Expand Down
2 changes: 1 addition & 1 deletion pennylane/templates/subroutines/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
from .hilbert_schmidt import HilbertSchmidt, LocalHilbertSchmidt
from .flip_sign import FlipSign
from .basis_rotation import BasisRotation
from .qsvt import poly_to_angles, QSVT, qsvt, qsvt_legacy, transform_angles
from .qsvt import poly_to_angles, QSVT, qsvt, transform_angles
from .select import Select
from .qdrift import QDrift
from .controlled_sequence import ControlledSequence
Expand Down
Loading

0 comments on commit f9cc523

Please sign in to comment.