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

Add qml.workflow.construct_execution_config(qnode)(*args,**kwargs) #6901

Merged
merged 26 commits into from
Jan 30, 2025
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
891e4c8
initial commit
andrijapau Jan 29, 2025
385e6de
add example to docstring
andrijapau Jan 29, 2025
7669ab6
add type hinting
andrijapau Jan 29, 2025
2552bff
doc: changelog
andrijapau Jan 29, 2025
21daa92
Update pennylane/workflow/construct_execution_config.py
andrijapau Jan 29, 2025
11416b1
Update pennylane/workflow/construct_execution_config.py
andrijapau Jan 29, 2025
45b8630
Update pennylane/workflow/construct_execution_config.py
andrijapau Jan 29, 2025
fed1b2b
address Christina's review
andrijapau Jan 29, 2025
2191a10
Merge branch 'add-construct-exec-config' of github.com:PennyLaneAI/pe…
andrijapau Jan 29, 2025
618b396
refactor
andrijapau Jan 29, 2025
1c8290d
revert bc of circular imports
andrijapau Jan 29, 2025
db9a05f
doc: Update __init__.py for workflow
andrijapau Jan 29, 2025
683027e
doc: Fix docstring for sphinx
andrijapau Jan 29, 2025
152d484
remove pprint from code block
andrijapau Jan 29, 2025
63b1bdc
fix: Update execution.py typing hinting
andrijapau Jan 29, 2025
2e570f7
fix: Update execution.py typing hinting
andrijapau Jan 29, 2025
3204aa6
fix: Update docstring
andrijapau Jan 29, 2025
0aa70ae
fix: Update docstring
andrijapau Jan 29, 2025
c36afb4
Trigger CI
andrijapau Jan 29, 2025
f547bc8
fix: Update docstring
andrijapau Jan 29, 2025
368eb16
update interface as well in resolve_execution_config
andrijapau Jan 29, 2025
88459b4
update changelog as well
andrijapau Jan 29, 2025
07f3ca1
remove __str__
andrijapau Jan 30, 2025
90e36cf
Merge branch 'master' into add-construct-exec-config
andrijapau Jan 30, 2025
d914f24
Merge branch 'master' into add-construct-exec-config
andrijapau Jan 30, 2025
ca14f0e
Merge branch 'master' into add-construct-exec-config
andrijapau Jan 30, 2025
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
27 changes: 27 additions & 0 deletions doc/releases/changelog-dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,33 @@

<h3>Improvements 🛠</h3>

* Added the `qml.workflow.construct_execution_config(qnode)(*args,**kwargs)` helper function.
Users can now construct the execution configuration from a particular `QNode` instance.
[(#6901)](https://github.com/PennyLaneAI/pennylane/pull/6901)

```python
@qml.qnode(qml.device("default.qubit", wires=1))
def circuit(x):
qml.RX(x, 0)
return qml.expval(qml.Z(0))
```
```pycon
>>> config = qml.workflow.construct_execution_config(circuit)(1)
>>> pprint.pprint(config)
ExecutionConfig(grad_on_execution=False,
use_device_gradient=True,
use_device_jacobian_product=False,
gradient_method='backprop',
gradient_keyword_arguments={},
device_options={'max_workers': None,
'prng_key': None,
'rng': Generator(PCG64) at 0x17D5BB220},
interface=<Interface.AUTO: 'auto'>,
derivative_order=1,
mcm_config=MCMConfig(mcm_method=None, postselect_mode=None),
convert_to_numpy=True)
```

* The higher order primitives in program capture can now accept inputs with abstract shapes.
[(#6786)](https://github.com/PennyLaneAI/pennylane/pull/6786)

Expand Down
2 changes: 2 additions & 0 deletions pennylane/workflow/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
~execute
~workflow.construct_tape
~workflow.construct_batch
~workflow.construct_execution_config
~workflow.get_transform_program
~workflow.get_best_diff_method
Expand All @@ -44,6 +45,7 @@
"""
from .construct_batch import construct_batch, get_transform_program
from .construct_tape import construct_tape
from .construct_execution_config import construct_execution_config
from .execution import execute
from .get_best_diff_method import get_best_diff_method
from .qnode import QNode, qnode
Expand Down
115 changes: 115 additions & 0 deletions pennylane/workflow/construct_execution_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
# Copyright 2018-2025 Xanadu Quantum Technologies Inc.

# 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 rif 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.
"""Contains a function to construct an execution configuration from a QNode instance."""
import functools

import pennylane as qml
from pennylane.math import Interface
from pennylane.workflow import construct_tape
from pennylane.workflow.resolution import _resolve_execution_config


def construct_execution_config(qnode: "qml.QNode", resolve: bool = True):
"""Constructs the execution configuration of a QNode instance.

Args:
qnode (QNode): the qnode we want to get execution configuration for
resolve (bool): Whether or not to validate and fill in undetermined values like `"best"`. Defaults to ``True``.

Returns:
config (qml.devices.ExecutionConfig): the execution configuration

**Example**

.. code-block:: python

@qml.qnode(qml.device("default.qubit", wires=1))
def circuit(x):
qml.RX(x, 0)
return qml.expval(qml.Z(0))

First, let's import ``pprint`` to make it easier to read the execution configuration objects.

>>> from pprint import pprint

If we wish to construct an unresolved execution configuration, we can specify
``resolve=False``. This will leave properties like ``gradient_method`` and ``interface``
in their unrefined state (e.g. ``"best"`` or ``"auto"`` respectively).

>>> config = qml.workflow.construct_execution_config(circuit, resolve=False)(1)
>>> pprint(config)
ExecutionConfig(grad_on_execution=None,
use_device_gradient=None,
use_device_jacobian_product=False,
gradient_method='best',
gradient_keyword_arguments={},
device_options={},
interface=<Interface.AUTO: 'auto'>,
derivative_order=1,
mcm_config=MCMConfig(mcm_method=None, postselect_mode=None),
convert_to_numpy=True)

Specifying ``resolve=True`` will then resolve these properties appropriately for the
given ``QNode`` configuration that was provided,

>>> resolved_config = qml.workflow.construct_execution_config(circuit, resolve=True)(1)
>>> pprint(resolved_config)
ExecutionConfig(grad_on_execution=False,
use_device_gradient=True,
use_device_jacobian_product=False,
gradient_method='backprop',
gradient_keyword_arguments={},
device_options={'max_workers': None,
'prng_key': None,
'rng': Generator(PCG64) at 0x17CFBBA00},
interface=<Interface.AUTO: 'auto'>,
andrijapau marked this conversation as resolved.
Show resolved Hide resolved
derivative_order=1,
mcm_config=MCMConfig(mcm_method=None, postselect_mode=None),
convert_to_numpy=True)
"""

@functools.wraps(qnode)
def wrapper(*args, **kwargs):
andrijapau marked this conversation as resolved.
Show resolved Hide resolved

mcm_config = qml.devices.MCMConfig(
postselect_mode=qnode.execute_kwargs["postselect_mode"],
mcm_method=qnode.execute_kwargs["mcm_method"],
)

grad_on_execution = qnode.execute_kwargs["grad_on_execution"]
if qnode.interface in {Interface.JAX.value, Interface.JAX_JIT.value}:
grad_on_execution = False
elif grad_on_execution == "best":
grad_on_execution = None

config = qml.devices.ExecutionConfig(
interface=qnode.interface,
gradient_method=qnode.diff_method,
grad_on_execution=grad_on_execution,
use_device_jacobian_product=qnode.execute_kwargs["device_vjp"],
derivative_order=qnode.execute_kwargs["max_diff"],
gradient_keyword_arguments=qnode.gradient_kwargs,
mcm_config=mcm_config,
)

if resolve:
tape = construct_tape(qnode)(*args, **kwargs)
# pylint:disable=protected-access
config = _resolve_execution_config(
config, qnode.device, (tape,), qnode._transform_program
)

return config

return wrapper
6 changes: 3 additions & 3 deletions pennylane/workflow/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,13 @@ def execute(
interface: Optional[InterfaceLike] = Interface.AUTO,
*,
transform_program: TransformProgram = None,
grad_on_execution: Literal[bool, "best"] = "best",
grad_on_execution: Literal[True, False, "best"] = "best",
cache: Union[None, bool, dict, Cache] = True,
cachesize: int = 10000,
max_diff: int = 1,
device_vjp: Union[bool, None] = False,
postselect_mode=None,
mcm_method=None,
postselect_mode: Literal[None, "hw-like", "fill-shots"] = None,
mcm_method: Literal[None, "deferred", "one-shot", "tree-traversal"] = None,
gradient_kwargs: dict = None,
mcm_config="unset",
config="unset",
Expand Down
141 changes: 141 additions & 0 deletions tests/workflow/test_construct_execution_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
# Copyright 2018-2025 Xanadu Quantum Technologies Inc.

# 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.
"""Contains tests for `construct_execution_config`."""

from dataclasses import replace

import pytest

import pennylane as qml
from pennylane.devices import ExecutionConfig, MCMConfig
from pennylane.math import get_canonical_interface_name
from pennylane.workflow import construct_execution_config


def dummycircuit():
"""Dummy function."""
qml.X(0)
return qml.expval(qml.Z(0))


@pytest.mark.all_interfaces
@pytest.mark.parametrize("device_name", ["default.qubit", "lightning.qubit"])
@pytest.mark.parametrize("interface", ["autograd", "tf", "torch", "jax", "jax-jit"])
def test_unresolved_construction(device_name, interface):
"""Test that an unresolved execution config is created correctly."""
qn = qml.QNode(dummycircuit, qml.device(device_name, wires=1), interface=interface)

config = construct_execution_config(qn, resolve=False)()

mcm_config = MCMConfig(None, None)
expected_config = ExecutionConfig(
grad_on_execution=False if "jax" in interface else None,
use_device_gradient=None,
use_device_jacobian_product=False,
gradient_method="best",
gradient_keyword_arguments={},
device_options={},
interface=get_canonical_interface_name(interface),
derivative_order=1,
mcm_config=mcm_config,
convert_to_numpy=True,
)

assert config == expected_config


@pytest.mark.all_interfaces
@pytest.mark.parametrize("interface", ["autograd", "tf", "torch", "jax", "jax-jit"])
def test_resolved_construction_lightning_qubit(interface):
"""Test that an resolved execution config is created correctly."""
qn = qml.QNode(dummycircuit, qml.device("lightning.qubit", wires=1), interface=interface)

config = construct_execution_config(qn, resolve=True)()

mcm_config = MCMConfig(None, None)
expected_config = ExecutionConfig(
grad_on_execution=True,
use_device_gradient=True,
use_device_jacobian_product=False,
gradient_method="adjoint",
gradient_keyword_arguments={},
interface=get_canonical_interface_name(interface),
derivative_order=1,
mcm_config=mcm_config,
convert_to_numpy=True,
)

# ignore comparison of device_options, could change
assert replace(config, device_options={}) == replace(expected_config, device_options={})


@pytest.mark.all_interfaces
@pytest.mark.parametrize("interface", ["autograd", "tf", "torch", "jax", "jax-jit"])
def test_resolved_construction_default_qubit(interface):
"""Test that an resolved execution config is created correctly."""
qn = qml.QNode(dummycircuit, qml.device("default.qubit", wires=1), interface=interface)

config = construct_execution_config(qn, resolve=True)()

mcm_config = MCMConfig(None, None)
expected_config = ExecutionConfig(
grad_on_execution=False,
use_device_gradient=True,
use_device_jacobian_product=False,
gradient_method="backprop",
gradient_keyword_arguments={},
interface=get_canonical_interface_name(interface),
derivative_order=1,
mcm_config=mcm_config,
convert_to_numpy=True,
)

# ignore comparison of device_options, could change
assert replace(config, device_options={}) == replace(expected_config, device_options={})


@pytest.mark.parametrize("mcm_method", [None, "one-shot"])
@pytest.mark.parametrize("postselect_mode", [None, "hw-like"])
@pytest.mark.parametrize("interface", ["jax", "jax-jit"])
@pytest.mark.jax
def test_jax_interface(mcm_method, postselect_mode, interface):
"""Test constructing config with JAX interface and different MCMConfig settings."""

@qml.qnode(
qml.device("default.qubit"),
interface=interface,
mcm_method=mcm_method,
postselect_mode=postselect_mode,
)
def circuit():
qml.X(0)
return qml.expval(qml.Z(0))

config = construct_execution_config(circuit)(shots=100)

expected_mcm_config = MCMConfig(mcm_method, postselect_mode="pad-invalid-samples")
expected_config = ExecutionConfig(
grad_on_execution=False,
use_device_gradient=False,
use_device_jacobian_product=False,
gradient_method=qml.gradients.param_shift,
gradient_keyword_arguments={},
interface=get_canonical_interface_name(interface),
derivative_order=1,
mcm_config=expected_mcm_config,
convert_to_numpy=True,
)

# ignore comparison of device_options, could change
assert replace(config, device_options={}) == replace(expected_config, device_options={})
Loading