|
| 1 | +""" |
| 2 | +Interface wraps quantum function as a jax function |
| 3 | +""" |
| 4 | + |
| 5 | +from typing import Any, Callable, Tuple, Optional, Union, Sequence |
| 6 | +from functools import wraps, partial |
| 7 | + |
| 8 | +import jax |
| 9 | +from jax import custom_vjp |
| 10 | + |
| 11 | +from ..cons import backend |
| 12 | +from .tensortrans import general_args_to_backend |
| 13 | + |
| 14 | +Tensor = Any |
| 15 | + |
| 16 | + |
| 17 | +def jax_wrapper( |
| 18 | + fun: Callable[..., Any], |
| 19 | + enable_dlpack: bool = False, |
| 20 | + output_shape: Optional[ |
| 21 | + Union[Tuple[int, ...], Tuple[int, ...], Sequence[Tuple[int, ...]]] |
| 22 | + ] = None, |
| 23 | + output_dtype: Optional[Union[Any, Sequence[Any]]] = None, |
| 24 | +) -> Callable[..., Any]: |
| 25 | + @wraps(fun) |
| 26 | + def fun_jax(*x: Any) -> Any: |
| 27 | + def wrapped_fun(*args: Any) -> Any: |
| 28 | + args = general_args_to_backend(args, enable_dlpack=enable_dlpack) |
| 29 | + y = fun(*args) |
| 30 | + y = general_args_to_backend( |
| 31 | + y, target_backend="jax", enable_dlpack=enable_dlpack |
| 32 | + ) |
| 33 | + return y |
| 34 | + |
| 35 | + # Use provided shape and dtype if available, otherwise run test |
| 36 | + if output_shape is not None and output_dtype is not None: |
| 37 | + if isinstance(output_shape, Sequence) and not isinstance( |
| 38 | + output_shape[0], int |
| 39 | + ): |
| 40 | + # Multiple outputs case |
| 41 | + out_shape = tuple( |
| 42 | + jax.ShapeDtypeStruct(s, d) |
| 43 | + for s, d in zip(output_shape, output_dtype) |
| 44 | + ) |
| 45 | + else: |
| 46 | + # Single output case |
| 47 | + out_shape = jax.ShapeDtypeStruct(output_shape, output_dtype) # type: ignore |
| 48 | + else: |
| 49 | + # Get expected output shape by running function once |
| 50 | + test_out = wrapped_fun(*x) |
| 51 | + if isinstance(test_out, tuple): |
| 52 | + # Multiple outputs case |
| 53 | + out_shape = tuple( |
| 54 | + jax.ShapeDtypeStruct( |
| 55 | + t.shape if hasattr(t, "shape") else (), |
| 56 | + t.dtype if hasattr(t, "dtype") else x[0].dtype, |
| 57 | + ) |
| 58 | + for t in test_out |
| 59 | + ) |
| 60 | + else: |
| 61 | + # Single output case |
| 62 | + out_shape = jax.ShapeDtypeStruct( # type: ignore |
| 63 | + test_out.shape if hasattr(test_out, "shape") else (), |
| 64 | + test_out.dtype if hasattr(test_out, "dtype") else x[0].dtype, |
| 65 | + ) |
| 66 | + |
| 67 | + # Use pure_callback with correct output shape |
| 68 | + result = jax.pure_callback(wrapped_fun, out_shape, *x) |
| 69 | + return result |
| 70 | + |
| 71 | + return fun_jax |
| 72 | + |
| 73 | + |
| 74 | +def jax_interface( |
| 75 | + fun: Callable[..., Any], |
| 76 | + jit: bool = False, |
| 77 | + enable_dlpack: bool = False, |
| 78 | + output_shape: Optional[Union[Tuple[int, ...], Tuple[()]]] = None, |
| 79 | + output_dtype: Optional[Any] = None, |
| 80 | +) -> Callable[..., Any]: |
| 81 | + """ |
| 82 | + Wrap a function on different ML backend with a jax interface. |
| 83 | +
|
| 84 | + :Example: |
| 85 | +
|
| 86 | + .. code-block:: python |
| 87 | +
|
| 88 | + tc.set_backend("tensorflow") |
| 89 | +
|
| 90 | + def f(params): |
| 91 | + c = tc.Circuit(1) |
| 92 | + c.rx(0, theta=params[0]) |
| 93 | + c.ry(0, theta=params[1]) |
| 94 | + return tc.backend.real(c.expectation([tc.gates.z(), [0]])) |
| 95 | +
|
| 96 | + f = tc.interfaces.jax_interface(f, jit=True) |
| 97 | +
|
| 98 | + params = jnp.ones(2) |
| 99 | + value, grad = jax.value_and_grad(f)(params) |
| 100 | +
|
| 101 | + :param fun: The quantum function with tensor in and tensor out |
| 102 | + :type fun: Callable[..., Any] |
| 103 | + :param jit: whether to jit ``fun``, defaults to False |
| 104 | + :type jit: bool, optional |
| 105 | + :param enable_dlpack: whether transform tensor backend via dlpack, defaults to False |
| 106 | + :type enable_dlpack: bool, optional |
| 107 | + :param output_shape: Optional shape of the function output, defaults to None |
| 108 | + :type output_shape: Optional[Union[Tuple[int, ...], Tuple[()]]], optional |
| 109 | + :param output_dtype: Optional dtype of the function output, defaults to None |
| 110 | + :type output_dtype: Optional[Any], optional |
| 111 | + :return: The same quantum function but now with jax array in and jax array out |
| 112 | + while AD is also supported |
| 113 | + :rtype: Callable[..., Any] |
| 114 | + """ |
| 115 | + jax_fun = create_jax_function( |
| 116 | + fun, |
| 117 | + enable_dlpack=enable_dlpack, |
| 118 | + jit=jit, |
| 119 | + output_shape=output_shape, |
| 120 | + output_dtype=output_dtype, |
| 121 | + ) |
| 122 | + return jax_fun |
| 123 | + |
| 124 | + |
| 125 | +def create_jax_function( |
| 126 | + fun: Callable[..., Any], |
| 127 | + enable_dlpack: bool = False, |
| 128 | + jit: bool = False, |
| 129 | + output_shape: Optional[Union[Tuple[int, ...], Tuple[()]]] = None, |
| 130 | + output_dtype: Optional[Any] = None, |
| 131 | +) -> Callable[..., Any]: |
| 132 | + if jit: |
| 133 | + fun = backend.jit(fun) |
| 134 | + |
| 135 | + wrapped = jax_wrapper( |
| 136 | + fun, |
| 137 | + enable_dlpack=enable_dlpack, |
| 138 | + output_shape=output_shape, |
| 139 | + output_dtype=output_dtype, |
| 140 | + ) |
| 141 | + |
| 142 | + @custom_vjp |
| 143 | + def f(*x: Any) -> Any: |
| 144 | + return wrapped(*x) |
| 145 | + |
| 146 | + def f_fwd(*x: Any) -> Tuple[Any, Tuple[Any, ...]]: |
| 147 | + y = wrapped(*x) |
| 148 | + return y, x |
| 149 | + |
| 150 | + def f_bwd(res: Tuple[Any, ...], g: Any) -> Tuple[Any, ...]: |
| 151 | + x = res |
| 152 | + |
| 153 | + if len(x) == 1: |
| 154 | + x = x[0] |
| 155 | + |
| 156 | + vjp_fun = partial(backend.vjp, fun) |
| 157 | + if jit: |
| 158 | + vjp_fun = backend.jit(vjp_fun) # type: ignore |
| 159 | + |
| 160 | + def vjp_wrapped(args: Any) -> Any: |
| 161 | + args = general_args_to_backend(args, enable_dlpack=enable_dlpack) |
| 162 | + gb = general_args_to_backend(g, enable_dlpack=enable_dlpack) |
| 163 | + r = vjp_fun(args, gb)[1] |
| 164 | + r = general_args_to_backend( |
| 165 | + r, target_backend="jax", enable_dlpack=enable_dlpack |
| 166 | + ) |
| 167 | + return r |
| 168 | + |
| 169 | + # Handle gradient shape for both single input and tuple inputs |
| 170 | + if isinstance(x, tuple): |
| 171 | + # Create a tuple of ShapeDtypeStruct for each input |
| 172 | + grad_shape = tuple(jax.ShapeDtypeStruct(xi.shape, xi.dtype) for xi in x) |
| 173 | + else: |
| 174 | + grad_shape = jax.ShapeDtypeStruct(x.shape, x.dtype) |
| 175 | + |
| 176 | + dx = jax.pure_callback( |
| 177 | + vjp_wrapped, |
| 178 | + grad_shape, |
| 179 | + x, |
| 180 | + ) |
| 181 | + |
| 182 | + if not isinstance(dx, tuple): |
| 183 | + dx = (dx,) |
| 184 | + return dx # type: ignore |
| 185 | + |
| 186 | + f.defvjp(f_fwd, f_bwd) |
| 187 | + return f |
0 commit comments