|
| 1 | +# Copyright 2024 Xanadu Quantum Technologies Inc. |
| 2 | + |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | + |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +""" |
| 15 | +This submodule offers custom primitives for the PennyLane capture module. |
| 16 | +""" |
| 17 | +from enum import Enum |
| 18 | +from typing import Union |
| 19 | + |
| 20 | +import jax |
| 21 | + |
| 22 | + |
| 23 | +class PrimitiveType(Enum): |
| 24 | + """Enum to define valid set of primitive classes""" |
| 25 | + |
| 26 | + DEFAULT = "default" |
| 27 | + OPERATOR = "operator" |
| 28 | + MEASUREMENT = "measurement" |
| 29 | + HIGHER_ORDER = "higher_order" |
| 30 | + TRANSFORM = "transform" |
| 31 | + |
| 32 | + |
| 33 | +# pylint: disable=too-few-public-methods,abstract-method |
| 34 | +class QmlPrimitive(jax.core.Primitive): |
| 35 | + """A subclass for JAX's Primitive that differentiates between different |
| 36 | + classes of primitives.""" |
| 37 | + |
| 38 | + _prim_type: PrimitiveType = PrimitiveType.DEFAULT |
| 39 | + |
| 40 | + @property |
| 41 | + def prim_type(self): |
| 42 | + """Value of Enum representing the primitive type to differentiate between various |
| 43 | + sets of PennyLane primitives.""" |
| 44 | + return self._prim_type.value |
| 45 | + |
| 46 | + @prim_type.setter |
| 47 | + def prim_type(self, value: Union[str, PrimitiveType]): |
| 48 | + """Setter for QmlPrimitive.prim_type.""" |
| 49 | + self._prim_type = PrimitiveType(value) |
| 50 | + |
| 51 | + |
| 52 | +# pylint: disable=too-few-public-methods,abstract-method |
| 53 | +class NonInterpPrimitive(QmlPrimitive): |
| 54 | + """A subclass to JAX's Primitive that works like a Python function |
| 55 | + when evaluating JVPTracers and BatchTracers.""" |
| 56 | + |
| 57 | + def bind_with_trace(self, trace, args, params): |
| 58 | + """Bind the ``NonInterpPrimitive`` with a trace. |
| 59 | +
|
| 60 | + If the trace is a ``JVPTrace``or a ``BatchTrace``, binding falls back to a standard Python function call. |
| 61 | + Otherwise, the bind call of JAX's standard Primitive is used.""" |
| 62 | + if isinstance(trace, (jax.interpreters.ad.JVPTrace, jax.interpreters.batching.BatchTrace)): |
| 63 | + return self.impl(*args, **params) |
| 64 | + return super().bind_with_trace(trace, args, params) |
0 commit comments