ketjet 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ketjet/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ """ketjet: a high-performance differentiable quantum statevector simulator.
2
+
3
+ The public API grows sprint by sprint; see ``plan.md`` in the repository for the roadmap.
4
+ """
5
+
6
+ from ketjet.circuit import Circuit
7
+ from ketjet.statevector import MAX_QUBITS, state_nbytes, zero_state
8
+
9
+ __version__ = "0.1.0"
10
+
11
+ __all__ = ["MAX_QUBITS", "Circuit", "__version__", "state_nbytes", "zero_state"]
ketjet/adjoint.py ADDED
@@ -0,0 +1,115 @@
1
+ r"""Reference adjoint differentiation on NumPy statevectors (ADR-0004 D3; Jones and Gacon, 2020).
2
+
3
+ For :math:`f = \langle\psi|O|\psi\rangle` with :math:`|\psi\rangle = U_N \cdots U_1 |0\rangle`,
4
+
5
+ .. math::
6
+
7
+ \frac{\partial f}{\partial x_s} = 2\,\operatorname{Re}\,
8
+ \langle \lambda_k | \partial_s U_k | \psi_{k-1} \rangle,
9
+ \qquad \langle \lambda_k | = \langle\psi| O\, U_N \cdots U_{k+1}.
10
+
11
+ Both :math:`|\psi_{k-1}\rangle` and :math:`|\lambda_k\rangle` come from *undoing* one gate at a time
12
+ on the way back, so no intermediate state is stored: memory is :math:`2 + M` statevectors for
13
+ :math:`M` observables, plus one scratch state, independent of circuit depth.
14
+
15
+ Backends implement :meth:`~ketjet.backends.Backend.adjoint_jacobian` (ADR-0004 D4); this module is
16
+ the NumPy backend's implementation and the oracle for faster ones.
17
+ """
18
+
19
+ from collections.abc import Sequence
20
+ from typing import Any
21
+
22
+ import numpy as np
23
+ import numpy.typing as npt
24
+
25
+ from ketjet.kernels import apply_structured
26
+ from ketjet.observables import Observable
27
+ from ketjet.operations import Operation
28
+ from ketjet.statevector import DTypeLike, StateVector, as_complex_dtype, zero_state
29
+
30
+ __all__ = ["adjoint_jacobian"]
31
+
32
+
33
+ def _apply(state: StateVector, matrix: npt.NDArray[Any], op: Operation) -> StateVector:
34
+ """Apply ``matrix`` (the gate or its adjoint, which share structure) with the fast kernels."""
35
+ return apply_structured(
36
+ state, matrix, op.all_wires, diagonal=op.is_diagonal, permutation=op.is_permutation
37
+ )
38
+
39
+
40
+ def adjoint_jacobian(
41
+ n_wires: int,
42
+ operations: Sequence[Operation],
43
+ observables: Sequence[Observable],
44
+ trainable: Sequence[tuple[int, int]],
45
+ *,
46
+ dtype: DTypeLike = np.complex128,
47
+ ) -> npt.NDArray[np.float64]:
48
+ r"""Return :math:`J_{ms} = \partial \langle O_m \rangle / \partial x_s` by one backward pass.
49
+
50
+ Parameters
51
+ ----------
52
+ n_wires
53
+ Number of qubits; the circuit starts from :math:`|0\cdots0\rangle`.
54
+ operations
55
+ Bound operations, in circuit order.
56
+ observables
57
+ The observables :math:`O_m`.
58
+ trainable
59
+ ``(operation index, parameter index)`` of every slot to differentiate, in column order.
60
+ A slot may appear more than once.
61
+ dtype
62
+ Precision of the states: ``complex128`` (default) or ``complex64``.
63
+
64
+ Returns
65
+ -------
66
+ numpy.ndarray
67
+ ``float64`` array of shape ``(len(observables), len(trainable))``.
68
+
69
+ Raises
70
+ ------
71
+ ValueError
72
+ If a trainable slot names an operation or parameter that doesn't exist.
73
+
74
+ Examples
75
+ --------
76
+ >>> from ketjet.observables import Z
77
+ >>> from ketjet.operations import RX
78
+ >>> adjoint_jacobian(1, [RX(0.5, 0)], [Z(0)], [(0, 0)]).round(6) # d cos(x) = -sin(x)
79
+ array([[-0.479426]])
80
+ """
81
+ dtype = as_complex_dtype(dtype)
82
+ ops = list(operations)
83
+ by_op: dict[int, list[tuple[int, int]]] = {}
84
+ for column, (i, j) in enumerate(trainable):
85
+ if not 0 <= i < len(ops) or not 0 <= j < ops[i].spec.num_params:
86
+ raise ValueError(f"Trainable slot {(i, j)} doesn't exist in the circuit.")
87
+ by_op.setdefault(i, []).append((column, j))
88
+ jac = np.zeros((len(observables), len(trainable)))
89
+ if not by_op:
90
+ return jac
91
+
92
+ psi = zero_state(n_wires, dtype)
93
+ for op in ops:
94
+ psi = _apply(psi, op.matrix(dtype), op)
95
+ lambdas = [obs.apply(psi) for obs in observables]
96
+
97
+ first = min(by_op) # gates before the first trainable one don't affect any gradient
98
+ for k in range(len(ops) - 1, first - 1, -1):
99
+ op = ops[k]
100
+ adjoint = op.matrix(dtype).conj().T
101
+ psi = _apply(psi, adjoint, op) # now |ψ_{k-1}⟩
102
+ for column, j in by_op.get(k, ()):
103
+ # A diagonal gate's derivative is diagonal; a permutation's isn't a permutation.
104
+ mu = apply_structured(
105
+ psi, op.derivative_matrix(j, dtype), op.all_wires, diagonal=op.is_diagonal
106
+ )
107
+ for m, lam in enumerate(lambdas):
108
+ jac[m, column] = 2 * np.vdot(lam, mu).real
109
+ del mu # free the scratch state before the next slot
110
+ if k > first:
111
+ # One at a time, so each old λ is freed at once: building a new list would hold
112
+ # 2M states instead of M.
113
+ for m in range(len(lambdas)):
114
+ lambdas[m] = _apply(lambdas[m], adjoint, op)
115
+ return jac
@@ -0,0 +1,6 @@
1
+ """Simulator backends behind one typed protocol (ADR-0001 D4)."""
2
+
3
+ from ketjet.backends.base import Backend, StateT
4
+ from ketjet.backends.numpy_backend import NumPyBackend
5
+
6
+ __all__ = ["Backend", "NumPyBackend", "StateT"]
@@ -0,0 +1,101 @@
1
+ """The backend protocol every simulator backend implements (ADR-0001 D4).
2
+
3
+ A backend owns the representation of a state (a NumPy array, a JAX array, a native buffer, a GPU
4
+ buffer) and the kernels that transform it. Callers interact only through this protocol, so the same
5
+ test suite runs against every backend.
6
+
7
+ **Ownership rule (ADR-0001 D4):** methods that transform a state *consume* their input. Callers
8
+ must use the returned state and must not read or reuse the state they passed in. Pure backends
9
+ (NumPy, JAX) return a new state; in-place backends (C++, CUDA) may update the buffer and return it,
10
+ avoiding a second ``2**n`` allocation.
11
+
12
+ **Measurements are read-only (ADR-0003 D6):** ``probs``, ``expval``, ``var`` and ``sample`` don't
13
+ consume the state. Backends compute them where the state lives (e.g. on a GPU) and return only
14
+ the results.
15
+
16
+ **Adjoint differentiation is one coarse method (ADR-0004 D4),** so native and GPU backends can run
17
+ the whole backward pass on their own memory, without a host call per gate.
18
+ """
19
+
20
+ from collections.abc import Iterable, Sequence
21
+ from typing import Protocol, TypeVar, runtime_checkable
22
+
23
+ import numpy as np
24
+ import numpy.typing as npt
25
+
26
+ from ketjet.measurements import Probabilities, Samples, Seed
27
+ from ketjet.observables import Observable
28
+ from ketjet.operations import Operation
29
+ from ketjet.statevector import DTypeLike, StateVector
30
+
31
+ __all__ = ["Backend", "StateT"]
32
+
33
+ StateT = TypeVar("StateT")
34
+ """The backend's native state type."""
35
+
36
+
37
+ @runtime_checkable
38
+ class Backend(Protocol[StateT]):
39
+ """Interface implemented by every simulator backend.
40
+
41
+ Attributes
42
+ ----------
43
+ name
44
+ Short identifier, e.g. ``"numpy"``.
45
+ """
46
+
47
+ name: str
48
+
49
+ def zero_state(self, n_wires: int, dtype: DTypeLike = ...) -> StateT:
50
+ """Allocate the ``|0…0⟩`` state of ``n_wires`` qubits."""
51
+ ...
52
+
53
+ def n_wires(self, state: StateT) -> int:
54
+ """Return the number of qubits of ``state``."""
55
+ ...
56
+
57
+ def apply_operation(self, state: StateT, op: Operation) -> StateT:
58
+ """Apply one operation. Consumes ``state``; use the returned state."""
59
+ ...
60
+
61
+ def apply_operations(self, state: StateT, ops: Iterable[Operation]) -> StateT:
62
+ """Apply operations in order. Consumes ``state``; use the returned state."""
63
+ ...
64
+
65
+ def to_numpy(self, state: StateT) -> StateVector:
66
+ """Return the amplitudes as a flat NumPy array (wire 0 = most significant bit)."""
67
+ ...
68
+
69
+ def probs(self, state: StateT, wires: Sequence[int] | None = None) -> Probabilities:
70
+ """Return measurement probabilities of ``wires`` (``wires[0]`` = most significant bit)."""
71
+ ...
72
+
73
+ def expval(self, state: StateT, observable: Observable) -> float:
74
+ """Return the expectation value of ``observable``."""
75
+ ...
76
+
77
+ def var(self, state: StateT, observable: Observable) -> float:
78
+ """Return the variance of ``observable``."""
79
+ ...
80
+
81
+ def sample(
82
+ self, state: StateT, shots: int, wires: Sequence[int] | None = None, seed: Seed = None
83
+ ) -> Samples:
84
+ """Return ``(shots, len(wires))`` measured bits, reproducible for a given ``seed``."""
85
+ ...
86
+
87
+ def adjoint_jacobian(
88
+ self,
89
+ n_wires: int,
90
+ operations: Sequence[Operation],
91
+ observables: Sequence[Observable],
92
+ trainable: Sequence[tuple[int, int]],
93
+ *,
94
+ dtype: DTypeLike = ...,
95
+ ) -> npt.NDArray[np.float64]:
96
+ """Return ``∂⟨O_m⟩/∂x_s`` for the ``trainable`` ``(operation, parameter)`` slots.
97
+
98
+ Shape ``(len(observables), len(trainable))``. The circuit starts from ``|0…0⟩``; memory
99
+ must not grow with circuit depth (see :mod:`ketjet.adjoint`).
100
+ """
101
+ ...
@@ -0,0 +1,107 @@
1
+ """The NumPy reference backend: the correctness oracle for every faster backend (plan.md §3)."""
2
+
3
+ from collections.abc import Iterable, Sequence
4
+
5
+ import numpy as np
6
+ import numpy.typing as npt
7
+
8
+ from ketjet import adjoint, measurements
9
+ from ketjet.kernels import apply_structured, n_wires_of
10
+ from ketjet.measurements import Probabilities, Samples, Seed
11
+ from ketjet.observables import Observable
12
+ from ketjet.operations import Operation
13
+ from ketjet.statevector import DTypeLike, StateVector, zero_state
14
+
15
+ __all__ = ["NumPyBackend"]
16
+
17
+
18
+ class NumPyBackend:
19
+ """Pure NumPy statevector backend.
20
+
21
+ Every method is pure: it never modifies the state it receives, which makes it the simplest
22
+ possible implementation of the :class:`~ketjet.backends.Backend` protocol. Callers should still
23
+ follow the protocol's ownership rule and only use returned states, so that switching to an
24
+ in-place backend never changes their results.
25
+
26
+ Examples
27
+ --------
28
+ >>> from ketjet.operations import CNOT, H
29
+ >>> backend = NumPyBackend()
30
+ >>> bell = backend.apply_operations(backend.zero_state(2), [H(0), CNOT(0, 1)])
31
+ >>> (backend.to_numpy(bell) + 0.0).round(3) # + 0.0 normalizes -0.0 across platforms
32
+ array([0.707+0.j, 0. +0.j, 0. +0.j, 0.707+0.j])
33
+ """
34
+
35
+ name = "numpy"
36
+
37
+ def zero_state(self, n_wires: int, dtype: DTypeLike = np.complex128) -> StateVector:
38
+ """Allocate the ``|0…0⟩`` state of ``n_wires`` qubits."""
39
+ return zero_state(n_wires, dtype)
40
+
41
+ def n_wires(self, state: StateVector) -> int:
42
+ """Return the number of qubits of ``state``."""
43
+ return n_wires_of(state)
44
+
45
+ def apply_operation(self, state: StateVector, op: Operation) -> StateVector:
46
+ """Apply one operation, controls included, and return the new state.
47
+
48
+ Diagonal and permutation gates use the specialized kernels (QS-205).
49
+
50
+ Raises
51
+ ------
52
+ ValueError
53
+ If the operation uses a wire outside the state, or has unbound symbolic parameters.
54
+ """
55
+ n = n_wires_of(state)
56
+ out_of_range = [w for w in op.all_wires if w >= n]
57
+ if out_of_range:
58
+ raise ValueError(
59
+ f"{op.gate} uses wire(s) {out_of_range}, but the state has {n} qubit(s)."
60
+ )
61
+ return apply_structured(
62
+ state,
63
+ op.matrix(state.dtype),
64
+ op.all_wires,
65
+ diagonal=op.is_diagonal,
66
+ permutation=op.is_permutation,
67
+ )
68
+
69
+ def apply_operations(self, state: StateVector, ops: Iterable[Operation]) -> StateVector:
70
+ """Apply operations in order and return the final state."""
71
+ for op in ops:
72
+ state = self.apply_operation(state, op)
73
+ return state
74
+
75
+ def to_numpy(self, state: StateVector) -> StateVector:
76
+ """Return a copy of the amplitudes (the caller may modify it freely)."""
77
+ return state.copy()
78
+
79
+ def probs(self, state: StateVector, wires: Sequence[int] | None = None) -> Probabilities:
80
+ """Return measurement probabilities of ``wires`` (see :func:`ketjet.measurements.probs`)."""
81
+ return measurements.probs(state, wires)
82
+
83
+ def expval(self, state: StateVector, observable: Observable) -> float:
84
+ """Return the expectation value of ``observable``."""
85
+ return measurements.expval(state, observable)
86
+
87
+ def var(self, state: StateVector, observable: Observable) -> float:
88
+ """Return the variance of ``observable``."""
89
+ return measurements.var(state, observable)
90
+
91
+ def sample(
92
+ self, state: StateVector, shots: int, wires: Sequence[int] | None = None, seed: Seed = None
93
+ ) -> Samples:
94
+ """Return measured bits (see :func:`ketjet.measurements.sample`)."""
95
+ return measurements.sample(state, shots, wires, seed)
96
+
97
+ def adjoint_jacobian(
98
+ self,
99
+ n_wires: int,
100
+ operations: Sequence[Operation],
101
+ observables: Sequence[Observable],
102
+ trainable: Sequence[tuple[int, int]],
103
+ *,
104
+ dtype: DTypeLike = np.complex128,
105
+ ) -> npt.NDArray[np.float64]:
106
+ """Adjoint Jacobian (see :func:`ketjet.adjoint.adjoint_jacobian`)."""
107
+ return adjoint.adjoint_jacobian(n_wires, operations, observables, trainable, dtype=dtype)