# Copyright 2026 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.
"""
Adds ``qp.hint``, a tool for annotating things with compiler hints.
"""
import functools
from collections.abc import Callable, Set
from difflib import SequenceMatcher
from typing import Any, overload
def process_hints(hints: dict[str, Any], supported: Set[str]) -> dict[str, Any]:
"""Return a copy of ``hints`` remapped onto canonical supported keys.
Exact matches are kept. Close misspellings are rewritten to the matching
supported key so typos like ``"num_iters"`` become ``"num-iters"``.
Similarity uses a case-insensitive :class:`~difflib.SequenceMatcher` ratio
with a cutoff of ``0.8``. Unrecognized keys are ignored.
Args:
hints (dict[str, Any]): user-provided compiler hints
supported (Set[str]): allowed canonical hint keys
Returns:
dict[str, Any]: hints keyed only by names in ``supported``
>>> process_hints({"num_iters": 10}, {"num-iters"})
{'num-iters': 10}
>>> process_hints({"numiters": 10}, {"num-iters"})
{'num-iters': 10}
"""
processed: dict[str, Any] = {}
supported = sorted(supported)
for key, value in hints.items():
match = _canonical_match(key, supported)
if match in processed:
raise ValueError(f"Multiple hint keys map to {match!r}. Got {tuple(hints)}.")
if match is not None:
processed[match] = value
return processed
def _canonical_match(key: str, supported: Set[str]) -> str | None:
"""Return match if key has a close match in supported, else None."""
if key in supported:
return key
for target in supported:
ratio = SequenceMatcher(a=key.casefold(), b=target.casefold()).ratio()
if ratio >= 0.5:
return target
return None
class HintedCallable:
"""A function annotated with compiler hints.
Args:
f (Callable): a generic function that should be annotated
hints (dict[str, Any]): a dictionary of hints to be applied
"""
def __init__(self, f: Callable, hints: dict[str, Any]):
functools.update_wrapper(self, f)
self._f = f
self._hints = hints
def __repr__(self):
return f"<HintedCallable({self.f}, {self.hints})>"
@property
def f(self) -> Callable:
"""The callable to be annotated."""
return self._f
@property
def hints(self) -> dict[str, Any]:
"""The compiler hints for the function."""
return self._hints
def __call__(self, *args, **kwargs):
return self.f(*args, **kwargs)
def get_hints(f, supported: Set[str]) -> dict[str, Any]:
"""Collect the compiler hints attached to ``f``, remapped onto the ``supported`` keys
with :func:`~.process_hints`.
Looks through ``functools.partial`` and nested :class:`~.HintedCallable` layers, so that
hints are not lost when a hinted callable gets wrapped in a partial. Hints from outer
layers take precedence over hints from inner layers.
Args:
f: the object to collect hints from
supported (Set[str]): allowed canonical hint keys
Returns:
dict[str, Any]: the merged hints keyed only by names in ``supported``, empty if ``f``
carries no such hints
>>> from functools import partial
>>> def f(x, y): return x + y
>>> get_hints(partial(qp.hint(f, {"num_iters": 10}), y=1), {"num-iters"})
{'num-iters': 10}
"""
hints = {}
while isinstance(f, (HintedCallable, functools.partial)):
if isinstance(f, HintedCallable):
hints = process_hints(f.hints, supported) | hints
f = f.f
else:
f = f.func
return hints
@functools.singledispatch
def apply_hint(f, hints: dict[str, Any]):
"""A single dispatch function that applies a hint to a certain type of object.
Args:
f : the thing to apply the hints to
hints (dict[str, Any]): a dictionary of hints to be applied
This is a single dispatch function, and custom behaviour for more types of classes can
be registered. For example, the ``ForLoopCallable`` produced by :func:`~for_loop` has
a custom way of applying the hint.
By default, all callables are converted to a :class:`~HintedCallable` for deferred handling.
>>> def f(x): return x
>>> hinted_f = qp.hint({"identity": True})(f)
>>> hinted_f
<HintedCallable(<function f at ...>, {'identity': True})>
>>> hinted_f.hints
{'identity': True}
"""
raise NotImplementedError(
f"No registered way to apply compiler hints to object of type {type(f)}"
)
@apply_hint.register
def _apply_to_callable(f: Callable, hints: dict) -> HintedCallable:
return HintedCallable(f, hints)
@apply_hint.register
def _stack_to_HintedCallable(f: HintedCallable, hints: dict) -> HintedCallable:
return HintedCallable(f, f.hints | hints)
@overload
def hint(f_or_hints: dict[str, Any], hints: None = None) -> Callable: ...
@overload
def hint(f_or_hints: Any, hints: dict[str, Any]) -> Any: ...
[docs]
def hint(f_or_hints, hints: dict[str, Any] | None = None):
r"""Attaches a compiler hint to applicable functionality.
Can be used as a decorator or applied directly:
* ``@qp.hint({"num-iters": 10})`` / ``qp.hint({"num-iters": 10})(f)``
* ``qp.hint(f, {"num-iters": 10})``
Args:
f_or_hints: either a dictionary of hints (decorator form), or the object
to annotate (direct form)
hints (dict[str, Any]): dictionary of hints; required for the direct form
Returns:
A decorator when only a hint dictionary is passed, otherwise the hinted object.
**Available Hints:**
* ``"num-iters": val`` — Both :func:`~.for_loop` and :func:`~.while_loop` support
``"num-iters"`` to indicate a heuristic number of loop iterations for the purposes of resource
estimation with :func:`~.specs`. See Usage Details for more information.
* ``"branch-prob"`` — The branches to :func:`~.cond` support ``"branch-prob"`` to indicate the
probability that a branch will be selected.
.. warning::
By definition, the :func:`~.qjit` compiler may decide to completely ignore any instances of
``hint`` in a program; a compiler hint is something that does not affect program
correctness, meaning that the compiler can safely ignore them and still provide correct
results.
While close misspellings may be accepted (e.g., ``"num-iter"``), spellings sufficiently far
away from the target will be ignored.
.. details::
:title: Usage Details
**"num-iters" with for and while loops**
By hinting control flow like :func:`~.for_loop` and :func:`~.while_loop`, profiling
with :func:`~.analyze` can heuristically specify the number of iterations, leading to
concrete resource counts (no symbolic expressions).
.. code-block:: python
@qp.qjit(capture=True)
@qp.qnode(qp.device('lightning.qubit', wires=10))
def c(n):
@qp.hint({"num-iters": 10})
@qp.for_loop(n)
def hinted_loop(i):
qp.X(i)
hinted_loop()
@qp.for_loop(n)
def unhinted_loop(i):
qp.Y(i)
unhinted_loop()
return qp.expval(qp.Z(0))
>>> print(qp.analyze(c)(5).resources)
Symbolic Variables: a
Quantum operations:
- Total: a + 10
- PauliX: 10
- PauliY: a
Measurement processes:
- expval(PauliZ): 1
Total wires: 10
Circuit Depth: Not computed
The concrete ``10`` corresponds to the hinted loop, contrasting the symbolic ``a`` from the
unhinted loop.
The same annotation can be applied directly instead of as a decorator:
.. code-block:: python
@qp.for_loop(n)
def hinted_loop(i):
qp.X(i)
hinted_loop = qp.hint(hinted_loop, {"num-iters": 10})
**"branch-prob" with cond**
By hinting :func:`~.cond` branches with ``"branch-prob"``, profiling with :func:`~.analyze`
can heuristically specify the probabilities for each branch being selected, leading to a
weighted average of resources from each branch.
By default (with no hints), :func:`~.analyze` takes the maximum union of all gate types
in every :func:`~.cond` branch. The difference in behaviour with and without ``hint`` is
evident in the example below.
.. code-block:: python
import pennylane as qp
@qp.qjit(capture=True)
@qp.qnode(qp.device("lightning.qubit", wires=2))
def circuit():
qp.H(0)
qp.H(1)
@qp.for_loop(0, 10)
def loop_hinted(_):
m = qp.measure(0)
@qp.hint({"branch-prob": 0.8})
def true_fn():
qp.CNOT((0, 1))
@qp.hint({"branch-prob": 0.2})
def false_fn():
qp.CZ((1, 0))
qp.cond(m, true_fn=true_fn, false_fn=false_fn)()
@qp.for_loop(0, 10)
def loop_unhinted(_):
m = qp.measure(0)
def true_fn():
qp.CRZ(0.1, (0, 1))
def false_fn():
qp.CRY(0.1, (1, 0))
qp.cond(m, true_fn=true_fn, false_fn=false_fn)()
loop_hinted()
loop_unhinted()
return qp.expval(qp.X(0))
>>> print(qp.analyze(circuit)().resources.quantum_operations)
{'CNOT': 8, 'CRY': 10, 'CRZ': 10, 'CZ': 2, 'Hadamard': 2, 'MidCircuitMeasure': 20}
With the hinted conditional branches in ``loop_hinted``, :func:`~.analyze` takes the
weighted sum of each branch's resources
(:math:`10\ \text{iterations} \times (0.8 \times \text{CNOT} + 0.2 \times \text{CZ}) = 8 \times \text{CNOT} + 2 \times \text{CZ}`).
In contrast, with the unhinted conditional branches in ``loop_unhinted``, :func:`~.analyze`
takes the max union of all gate types across every branch, which accumulates to
:math:`10 \times \text{CRZ} + 10 \times \text{CRY}`.
**General notes on using hint**
Note that hints can be overwritten. The following will use ``20`` as the number of
iterations:
.. code-block:: python
@qp.qjit(capture=True)
@qp.qnode(qp.device('lightning.qubit', wires=10))
def c(n):
@qp.hint({"num-iters": 20})
@qp.hint({"num-iters": 10})
@qp.while_loop(lambda i: i < 10)
def loop(i):
qp.X(i)
return i + 1
loop(0)
return qp.expval(qp.Z(0))
Compiler hints will also be discarded without warning if they do not match the expected type
of hint. The next example would run without warning:
.. code-block:: python
@qp.qjit(capture=True)
@qp.qnode(qp.device('null.qubit', wires=10))
def c(n):
@qp.hint({"unknown_hint": "a"})
@qp.for_loop(3)
def loop(i):
qp.X(i)
loop()
return qp.expval(qp.Z(0))
"""
if hints is not None:
return apply_hint(f_or_hints, hints)
if not isinstance(f_or_hints, dict):
raise TypeError(
"hint() decorator form expects a dict of hints; "
"use hint(f, hints) to apply directly."
)
def decorator(f):
return apply_hint(f, f_or_hints)
return decorator