nudaq 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.
- nudaq/__init__.py +74 -0
- nudaq/__main__.py +22 -0
- nudaq/_alias/cudaq/__init__.py +6 -0
- nudaq/_core.py +737 -0
- nudaq-0.1.0.dist-info/METADATA +157 -0
- nudaq-0.1.0.dist-info/RECORD +9 -0
- nudaq-0.1.0.dist-info/WHEEL +4 -0
- nudaq-0.1.0.dist-info/entry_points.txt +2 -0
- nudaq-0.1.0.dist-info/licenses/LICENSE +21 -0
nudaq/__init__.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""nudaq: a small numpy simulator that copies a subset of the CUDA-Q Python API.
|
|
2
|
+
|
|
3
|
+
Use it to run and test CUDA-Q style code where CUDA-Q cannot be installed
|
|
4
|
+
(for example Intel Macs or plain CI runners). nudaq is not CUDA-Q and is not
|
|
5
|
+
affiliated with NVIDIA.
|
|
6
|
+
|
|
7
|
+
Three ways to use it:
|
|
8
|
+
|
|
9
|
+
import nudaq as cudaq # in your own code
|
|
10
|
+
|
|
11
|
+
import nudaq; nudaq.install() # make a later `import cudaq` return nudaq (this process only)
|
|
12
|
+
|
|
13
|
+
PYTHONPATH="$(python -m nudaq path)" python script.py # unchanged code that does `import cudaq`
|
|
14
|
+
"""
|
|
15
|
+
import os
|
|
16
|
+
import sys
|
|
17
|
+
|
|
18
|
+
from ._core import ( # noqa: F401
|
|
19
|
+
ObserveResult,
|
|
20
|
+
SampleResult,
|
|
21
|
+
SpinOperator,
|
|
22
|
+
State,
|
|
23
|
+
adjoint,
|
|
24
|
+
control,
|
|
25
|
+
draw,
|
|
26
|
+
get_state,
|
|
27
|
+
get_target,
|
|
28
|
+
get_unitary,
|
|
29
|
+
kernel,
|
|
30
|
+
observe,
|
|
31
|
+
qubit,
|
|
32
|
+
qview,
|
|
33
|
+
qvector,
|
|
34
|
+
register_operation,
|
|
35
|
+
reset,
|
|
36
|
+
sample,
|
|
37
|
+
set_random_seed,
|
|
38
|
+
set_target,
|
|
39
|
+
spin,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
__version__ = "0.1.0"
|
|
43
|
+
|
|
44
|
+
#: The CUDA-Q release whose Python API nudaq follows.
|
|
45
|
+
CUDAQ_API_VERSION = "0.17"
|
|
46
|
+
|
|
47
|
+
__all__ = [
|
|
48
|
+
"CUDAQ_API_VERSION", "ObserveResult", "SampleResult", "SpinOperator", "State", "adjoint", "alias_path",
|
|
49
|
+
"control", "draw", "get_state", "get_target", "get_unitary", "install", "kernel", "observe", "qubit",
|
|
50
|
+
"qview", "qvector", "register_operation", "reset", "sample", "set_random_seed", "set_target", "spin",
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def install():
|
|
55
|
+
"""Register nudaq as the module ``cudaq`` in this interpreter.
|
|
56
|
+
|
|
57
|
+
After ``nudaq.install()``, ``import cudaq`` returns nudaq. Raises RuntimeError if a different
|
|
58
|
+
``cudaq`` module (for example the real CUDA-Q) is already imported.
|
|
59
|
+
"""
|
|
60
|
+
mod = sys.modules[__name__]
|
|
61
|
+
old = sys.modules.get("cudaq")
|
|
62
|
+
if old is not None and old is not mod:
|
|
63
|
+
raise RuntimeError("nudaq.install(): another 'cudaq' module is already imported")
|
|
64
|
+
sys.modules["cudaq"] = mod
|
|
65
|
+
return mod
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def alias_path():
|
|
69
|
+
"""Directory holding a ``cudaq`` package that forwards to nudaq.
|
|
70
|
+
|
|
71
|
+
Put it first on PYTHONPATH (or sys.path) to run unchanged code that does ``import cudaq``,
|
|
72
|
+
for example a Jupyter kernel or a test suite run in a subprocess.
|
|
73
|
+
"""
|
|
74
|
+
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "_alias")
|
nudaq/__main__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Command line: ``python -m nudaq path`` prints the directory to put on PYTHONPATH so that
|
|
2
|
+
``import cudaq`` loads nudaq; ``python -m nudaq version`` prints the versions."""
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
import nudaq
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main(argv=None):
|
|
9
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
10
|
+
cmd = argv[0] if argv else "help"
|
|
11
|
+
if cmd == "path":
|
|
12
|
+
print(nudaq.alias_path())
|
|
13
|
+
elif cmd == "version":
|
|
14
|
+
print(f"nudaq {nudaq.__version__} (CUDA-Q API {nudaq.CUDAQ_API_VERSION})")
|
|
15
|
+
else:
|
|
16
|
+
print(__doc__.strip())
|
|
17
|
+
return 0 if cmd in ("help", "-h", "--help") else 2
|
|
18
|
+
return 0
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
if __name__ == "__main__":
|
|
22
|
+
sys.exit(main())
|
nudaq/_core.py
ADDED
|
@@ -0,0 +1,737 @@
|
|
|
1
|
+
"""Core of nudaq: an eager numpy state-vector simulator with a CUDA-Q style Python API.
|
|
2
|
+
|
|
3
|
+
Kernels run eagerly as Python. A static lint rejects constructs the real CUDA-Q
|
|
4
|
+
kernel compiler would not accept (captured globals, unannotated arguments,
|
|
5
|
+
unsupported syntax), so code that passes here is likely to compile in CUDA-Q.
|
|
6
|
+
|
|
7
|
+
Conventions copied from CUDA-Q:
|
|
8
|
+
- sample() bitstrings: qubit 0 is the left-most character.
|
|
9
|
+
- get_state(): np.array(state) is little-endian (qubit 0 = least-significant bit
|
|
10
|
+
of the index); state.amplitude("01") takes a label with qubit 0 left-most.
|
|
11
|
+
- register_operation(): matrix in MSB order (first target = most significant).
|
|
12
|
+
"""
|
|
13
|
+
import ast
|
|
14
|
+
import inspect
|
|
15
|
+
import math
|
|
16
|
+
import textwrap
|
|
17
|
+
import types
|
|
18
|
+
from collections import Counter
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
|
|
22
|
+
_rng = np.random.default_rng()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def set_random_seed(seed):
|
|
26
|
+
global _rng
|
|
27
|
+
_rng = np.random.default_rng(seed)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class _Target:
|
|
31
|
+
name = "nudaq-numpy"
|
|
32
|
+
simulator = "numpy"
|
|
33
|
+
|
|
34
|
+
def num_qpus(self):
|
|
35
|
+
return 1
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def set_target(name, **kw):
|
|
39
|
+
pass
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def get_target(*a):
|
|
43
|
+
return _Target()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# --------------------------------------------------------------------------
|
|
47
|
+
# run context
|
|
48
|
+
# --------------------------------------------------------------------------
|
|
49
|
+
class _Ctx:
|
|
50
|
+
def __init__(self):
|
|
51
|
+
self.n = 0
|
|
52
|
+
self.state = np.ones((), dtype=complex) # tensor of shape [2]*n, axis i = qubit i
|
|
53
|
+
self.record = None # list when recording ops for adjoint/control
|
|
54
|
+
self.measured = []
|
|
55
|
+
self.ops = [] # for draw
|
|
56
|
+
|
|
57
|
+
def alloc(self, k, amps=None):
|
|
58
|
+
if self.record is not None:
|
|
59
|
+
raise RuntimeError("nudaq: qubit allocation inside cudaq.adjoint/cudaq.control sub-kernel")
|
|
60
|
+
if amps is None:
|
|
61
|
+
new = np.zeros([2] * k, dtype=complex)
|
|
62
|
+
new[(0,) * k] = 1.0
|
|
63
|
+
else:
|
|
64
|
+
a = np.asarray(amps, dtype=complex)
|
|
65
|
+
if a.size != 2 ** k:
|
|
66
|
+
raise ValueError("nudaq: amplitude vector length must be a power of 2")
|
|
67
|
+
if abs(np.linalg.norm(a) - 1) > 1e-6:
|
|
68
|
+
raise ValueError("nudaq: cudaq.qvector(amplitudes) needs a normalised vector")
|
|
69
|
+
# CUDA-Q state-vector order is little-endian (qubit 0 = LSB)
|
|
70
|
+
new = a.reshape([2] * k).transpose(list(range(k))[::-1])
|
|
71
|
+
self.state = np.multiply.outer(self.state, new) if self.n else new.copy()
|
|
72
|
+
idx = list(range(self.n, self.n + k))
|
|
73
|
+
self.n += k
|
|
74
|
+
return idx
|
|
75
|
+
|
|
76
|
+
def apply(self, U, targets, controls=(), neg=()):
|
|
77
|
+
if self.record is not None:
|
|
78
|
+
self.record.append((U, tuple(targets), tuple(controls), tuple(neg)))
|
|
79
|
+
return
|
|
80
|
+
self._apply(U, targets, controls, neg)
|
|
81
|
+
|
|
82
|
+
def _apply(self, U, targets, controls=(), neg=()):
|
|
83
|
+
targets = list(targets)
|
|
84
|
+
controls = list(controls)
|
|
85
|
+
if len(set(targets + controls)) != len(targets) + len(controls):
|
|
86
|
+
raise RuntimeError("nudaq: a qubit is used twice in one gate")
|
|
87
|
+
st = self.state
|
|
88
|
+
n = self.n
|
|
89
|
+
idx = [slice(None)] * n
|
|
90
|
+
for c in controls:
|
|
91
|
+
idx[c] = 0 if c in neg else 1
|
|
92
|
+
idx = tuple(idx)
|
|
93
|
+
sub = st[idx]
|
|
94
|
+
rem = [q for q in range(n) if q not in controls]
|
|
95
|
+
tpos = [rem.index(t) for t in targets]
|
|
96
|
+
k = len(targets)
|
|
97
|
+
Ut = np.asarray(U, dtype=complex).reshape([2] * (2 * k))
|
|
98
|
+
new = np.tensordot(Ut, sub, axes=(list(range(k, 2 * k)), tpos))
|
|
99
|
+
new = np.moveaxis(new, list(range(k)), tpos)
|
|
100
|
+
st[idx] = new
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
_ctx = None
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _need_ctx():
|
|
107
|
+
if _ctx is None:
|
|
108
|
+
raise RuntimeError("nudaq: quantum operation called outside a kernel run")
|
|
109
|
+
return _ctx
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# --------------------------------------------------------------------------
|
|
113
|
+
# qubits
|
|
114
|
+
# --------------------------------------------------------------------------
|
|
115
|
+
class _Neg:
|
|
116
|
+
def __init__(self, q):
|
|
117
|
+
self.q = q
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class qubit:
|
|
121
|
+
def __init__(self, _i=None):
|
|
122
|
+
if _i is None:
|
|
123
|
+
_i = _need_ctx().alloc(1)[0]
|
|
124
|
+
self.i = _i
|
|
125
|
+
|
|
126
|
+
def __invert__(self):
|
|
127
|
+
return _Neg(self)
|
|
128
|
+
|
|
129
|
+
def __repr__(self):
|
|
130
|
+
return f"qubit({self.i})"
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class qview:
|
|
134
|
+
def __init__(self, idx):
|
|
135
|
+
self.idx = list(idx)
|
|
136
|
+
|
|
137
|
+
def size(self):
|
|
138
|
+
return len(self.idx)
|
|
139
|
+
|
|
140
|
+
def __len__(self):
|
|
141
|
+
return len(self.idx)
|
|
142
|
+
|
|
143
|
+
def __getitem__(self, k):
|
|
144
|
+
if isinstance(k, slice):
|
|
145
|
+
return qview(self.idx[k])
|
|
146
|
+
if not isinstance(k, (int, np.integer)):
|
|
147
|
+
raise TypeError("nudaq: qubit index must be int")
|
|
148
|
+
return qubit(self.idx[k])
|
|
149
|
+
|
|
150
|
+
def __iter__(self):
|
|
151
|
+
return (qubit(i) for i in self.idx)
|
|
152
|
+
|
|
153
|
+
def front(self, k=None):
|
|
154
|
+
return qubit(self.idx[0]) if k is None else qview(self.idx[:k])
|
|
155
|
+
|
|
156
|
+
def back(self, k=None):
|
|
157
|
+
return qubit(self.idx[-1]) if k is None else qview(self.idx[-k:])
|
|
158
|
+
|
|
159
|
+
def slice(self, start, size):
|
|
160
|
+
return qview(self.idx[start:start + size])
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class qvector(qview):
|
|
164
|
+
def __init__(self, arg):
|
|
165
|
+
ctx = _need_ctx()
|
|
166
|
+
if isinstance(arg, (int, np.integer)):
|
|
167
|
+
super().__init__(ctx.alloc(int(arg)))
|
|
168
|
+
else:
|
|
169
|
+
a = list(arg)
|
|
170
|
+
k = int(round(math.log2(len(a))))
|
|
171
|
+
super().__init__(ctx.alloc(k, a))
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _flatten_qubits(args):
|
|
175
|
+
out, neg = [], []
|
|
176
|
+
for a in args:
|
|
177
|
+
if isinstance(a, _Neg):
|
|
178
|
+
out.append(a.q.i)
|
|
179
|
+
neg.append(a.q.i)
|
|
180
|
+
elif isinstance(a, qubit):
|
|
181
|
+
out.append(a.i)
|
|
182
|
+
elif isinstance(a, qview):
|
|
183
|
+
out.extend(a.idx)
|
|
184
|
+
elif isinstance(a, (list, tuple)):
|
|
185
|
+
o, n = _flatten_qubits(a)
|
|
186
|
+
out += o
|
|
187
|
+
neg += n
|
|
188
|
+
else:
|
|
189
|
+
raise TypeError(f"nudaq: expected qubit(s), got {type(a).__name__}")
|
|
190
|
+
return out, neg
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
# --------------------------------------------------------------------------
|
|
194
|
+
# gates
|
|
195
|
+
# --------------------------------------------------------------------------
|
|
196
|
+
_I2 = np.eye(2, dtype=complex)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _mat_rx(t):
|
|
200
|
+
c, s = math.cos(t / 2), math.sin(t / 2)
|
|
201
|
+
return np.array([[c, -1j * s], [-1j * s, c]])
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _mat_ry(t):
|
|
205
|
+
c, s = math.cos(t / 2), math.sin(t / 2)
|
|
206
|
+
return np.array([[c, -s], [s, c]], dtype=complex)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _mat_rz(t):
|
|
210
|
+
return np.diag([np.exp(-0.5j * t), np.exp(0.5j * t)])
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _mat_r1(t):
|
|
214
|
+
return np.diag([1, np.exp(1j * t)])
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _mat_u3(th, ph, lam):
|
|
218
|
+
c, s = math.cos(th / 2), math.sin(th / 2)
|
|
219
|
+
return np.array([[c, -np.exp(1j * lam) * s], [np.exp(1j * ph) * s, np.exp(1j * (ph + lam)) * c]])
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
_FIXED = {
|
|
223
|
+
"h": np.array([[1, 1], [1, -1]], dtype=complex) / math.sqrt(2),
|
|
224
|
+
"x": np.array([[0, 1], [1, 0]], dtype=complex),
|
|
225
|
+
"y": np.array([[0, -1j], [1j, 0]]),
|
|
226
|
+
"z": np.diag([1, -1]).astype(complex),
|
|
227
|
+
"s": np.diag([1, 1j]),
|
|
228
|
+
"t": np.diag([1, np.exp(1j * math.pi / 4)]),
|
|
229
|
+
"sdg": np.diag([1, -1j]),
|
|
230
|
+
"tdg": np.diag([1, np.exp(-1j * math.pi / 4)]),
|
|
231
|
+
}
|
|
232
|
+
_PARAM = {"rx": (_mat_rx, 1), "ry": (_mat_ry, 1), "rz": (_mat_rz, 1), "r1": (_mat_r1, 1), "u3": (_mat_u3, 3)}
|
|
233
|
+
_SWAP = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]], dtype=complex)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
class _Gate:
|
|
237
|
+
def __init__(self, name, matfn, nparams, ntargets, broadcast):
|
|
238
|
+
self.name, self.matfn, self.np, self.nt, self.bc = name, matfn, nparams, ntargets, broadcast
|
|
239
|
+
|
|
240
|
+
def _params(self, args):
|
|
241
|
+
ps = args[: self.np]
|
|
242
|
+
for p in ps:
|
|
243
|
+
if not isinstance(p, (int, float, np.floating, np.integer)) or isinstance(p, bool):
|
|
244
|
+
raise TypeError(f"nudaq: {self.name} parameter must be a number, got {type(p).__name__}")
|
|
245
|
+
return [float(p) for p in ps], args[self.np:]
|
|
246
|
+
|
|
247
|
+
def __call__(self, *args):
|
|
248
|
+
ctx = _need_ctx()
|
|
249
|
+
ps, qs = self._params(args)
|
|
250
|
+
U = self.matfn(*ps)
|
|
251
|
+
qi, neg = _flatten_qubits(qs)
|
|
252
|
+
if neg:
|
|
253
|
+
raise TypeError("nudaq: ~q only allowed as a control")
|
|
254
|
+
ctx.ops.append((self.name, ps, [], qi))
|
|
255
|
+
if self.nt == 1 and self.bc:
|
|
256
|
+
for q in qi:
|
|
257
|
+
ctx.apply(U, [q])
|
|
258
|
+
else:
|
|
259
|
+
if len(qi) != self.nt:
|
|
260
|
+
raise TypeError(f"nudaq: {self.name} expects {self.nt} target qubit(s), got {len(qi)}")
|
|
261
|
+
ctx.apply(U, qi)
|
|
262
|
+
|
|
263
|
+
def ctrl(self, *args):
|
|
264
|
+
ctx = _need_ctx()
|
|
265
|
+
ps, qs = self._params(args)
|
|
266
|
+
U = self.matfn(*ps)
|
|
267
|
+
if len(qs) < 2:
|
|
268
|
+
raise TypeError(f"nudaq: {self.name}.ctrl needs controls and target(s)")
|
|
269
|
+
if self.nt > 1:
|
|
270
|
+
tq, tneg = _flatten_qubits(qs[-self.nt:])
|
|
271
|
+
cq, cneg = _flatten_qubits(qs[:-self.nt])
|
|
272
|
+
else:
|
|
273
|
+
tq, tneg = _flatten_qubits([qs[-1]])
|
|
274
|
+
cq, cneg = _flatten_qubits(qs[:-1])
|
|
275
|
+
if len(tq) != self.nt or tneg:
|
|
276
|
+
raise TypeError(f"nudaq: {self.name}.ctrl: last argument(s) must be {self.nt} target qubit(s)")
|
|
277
|
+
ctx.ops.append((self.name, ps, cq, tq))
|
|
278
|
+
ctx.apply(U, tq, cq, cneg)
|
|
279
|
+
|
|
280
|
+
def adj(self, *args):
|
|
281
|
+
ctx = _need_ctx()
|
|
282
|
+
ps, qs = self._params(args)
|
|
283
|
+
U = self.matfn(*ps).conj().T
|
|
284
|
+
qi, _ = _flatten_qubits(qs)
|
|
285
|
+
ctx.ops.append((self.name + "†", ps, [], qi))
|
|
286
|
+
if self.nt == 1 and self.bc:
|
|
287
|
+
for q in qi:
|
|
288
|
+
ctx.apply(U, [q])
|
|
289
|
+
else:
|
|
290
|
+
ctx.apply(U, qi)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
_GATES = {}
|
|
294
|
+
for _n, _m in _FIXED.items():
|
|
295
|
+
_GATES[_n] = _Gate(_n, (lambda m: (lambda: m))(_m), 0, 1, True)
|
|
296
|
+
for _n, (_f, _k) in _PARAM.items():
|
|
297
|
+
_GATES[_n] = _Gate(_n, _f, _k, 1, True)
|
|
298
|
+
_GATES["swap"] = _Gate("swap", lambda: _SWAP, 0, 2, False)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
class _CGate:
|
|
302
|
+
"""cx, cy, cz, ch, cs, ct, crx, cry, crz, cr1: control(s) first, target last."""
|
|
303
|
+
|
|
304
|
+
def __init__(self, base):
|
|
305
|
+
self.base = base
|
|
306
|
+
self.name = "c" + base.name
|
|
307
|
+
|
|
308
|
+
def __call__(self, *args):
|
|
309
|
+
self.base.ctrl(*args)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
for _n in ["h", "x", "y", "z", "s", "t", "rx", "ry", "rz", "r1"]:
|
|
313
|
+
_GATES["c" + _n] = _CGate(_GATES[_n])
|
|
314
|
+
|
|
315
|
+
_registered = {}
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def register_operation(name, unitary):
|
|
319
|
+
m = np.asarray(unitary, dtype=complex).flatten()
|
|
320
|
+
d = int(round(math.sqrt(m.size)))
|
|
321
|
+
k = int(round(math.log2(d)))
|
|
322
|
+
M = m.reshape(d, d)
|
|
323
|
+
if not np.allclose(M.conj().T @ M, np.eye(d), atol=1e-8):
|
|
324
|
+
raise ValueError("nudaq: registered operation is not unitary")
|
|
325
|
+
_registered[name] = _Gate(name, lambda M=M: M, 0, k, k == 1)
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _measure(name):
|
|
329
|
+
def m(*qs):
|
|
330
|
+
ctx = _need_ctx()
|
|
331
|
+
qi, _ = _flatten_qubits(qs)
|
|
332
|
+
if ctx.record is not None:
|
|
333
|
+
raise RuntimeError("nudaq: measurement inside adjoint/control sub-kernel")
|
|
334
|
+
ctx.ops.append((name, [], [], qi))
|
|
335
|
+
for q in qi:
|
|
336
|
+
ctx.measured.append((q, name))
|
|
337
|
+
return False # value-dependent feed-forward is not supported by nudaq
|
|
338
|
+
|
|
339
|
+
return m
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def reset(*qs):
|
|
343
|
+
raise RuntimeError("nudaq: reset is not supported")
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
_MEASURES = {n: _measure(n) for n in ("mz", "mx", "my")}
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _kernel_names():
|
|
350
|
+
"""Names a kernel body can use without importing them (the CUDA-Q compiler knows them natively)."""
|
|
351
|
+
ns = dict(_GATES)
|
|
352
|
+
ns.update(_MEASURES)
|
|
353
|
+
ns["reset"] = reset
|
|
354
|
+
ns.update(_registered)
|
|
355
|
+
return ns
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
# --------------------------------------------------------------------------
|
|
359
|
+
# kernel decorator + lint
|
|
360
|
+
# --------------------------------------------------------------------------
|
|
361
|
+
_GATE_NAMES = set(_GATES) | {"mz", "mx", "my", "reset", "exp_pauli"}
|
|
362
|
+
_ALLOWED_ANN = {"int", "float", "bool", "complex", "list[int]", "list[float]", "list[bool]", "list[complex]",
|
|
363
|
+
"cudaq.qvector", "cudaq.qview", "cudaq.qubit", "nudaq.qvector", "nudaq.qview", "nudaq.qubit",
|
|
364
|
+
"qvector", "qview", "qubit"}
|
|
365
|
+
_MATH_ATTRS = {"pi", "e", "sin", "cos", "tan", "asin", "acos", "atan", "arcsin", "arccos", "arctan", "sqrt",
|
|
366
|
+
"exp", "log", "ceil", "floor"}
|
|
367
|
+
_CUDAQ_ATTRS = {"qvector", "qview", "qubit", "control", "adjoint"}
|
|
368
|
+
_OK_NODES = (ast.Module, ast.FunctionDef, ast.arguments, ast.arg, ast.Expr, ast.Call, ast.Name, ast.Attribute,
|
|
369
|
+
ast.Constant, ast.Assign, ast.AugAssign, ast.AnnAssign, ast.For, ast.While, ast.If, ast.Compare,
|
|
370
|
+
ast.BinOp, ast.UnaryOp, ast.BoolOp, ast.Subscript, ast.Slice, ast.List, ast.Return, ast.Load,
|
|
371
|
+
ast.Store, ast.operator, ast.unaryop, ast.cmpop, ast.boolop, ast.Pass, ast.Break, ast.Continue,
|
|
372
|
+
ast.IfExp, ast.Tuple, ast.keyword)
|
|
373
|
+
_BUILTIN_OK = {"range", "len", "int", "float", "bool", "abs", "min", "max", "complex", "enumerate", "list"}
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _ann_str(a):
|
|
377
|
+
return ast.unparse(a).replace(" ", "")
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _lint(fn):
|
|
381
|
+
src = textwrap.dedent(inspect.getsource(fn))
|
|
382
|
+
tree = ast.parse(src)
|
|
383
|
+
fdef = tree.body[0]
|
|
384
|
+
errs = []
|
|
385
|
+
params = set()
|
|
386
|
+
for a in fdef.args.args:
|
|
387
|
+
params.add(a.arg)
|
|
388
|
+
if a.annotation is None:
|
|
389
|
+
errs.append(f"argument '{a.arg}' has no type annotation")
|
|
390
|
+
elif _ann_str(a.annotation) not in _ALLOWED_ANN:
|
|
391
|
+
errs.append(f"argument '{a.arg}': unsupported annotation {_ann_str(a.annotation)}")
|
|
392
|
+
if fdef.args.vararg or fdef.args.kwarg or fdef.args.kwonlyargs or fdef.args.defaults:
|
|
393
|
+
errs.append("no *args/**kwargs/defaults allowed in kernel signature")
|
|
394
|
+
local = set(params)
|
|
395
|
+
allnodes = [n for st in fdef.body for n in ast.walk(st)] + list(ast.walk(fdef.args))
|
|
396
|
+
if fdef.returns is not None:
|
|
397
|
+
allnodes += list(ast.walk(fdef.returns))
|
|
398
|
+
for node in allnodes:
|
|
399
|
+
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
|
|
400
|
+
local.add(node.id)
|
|
401
|
+
for node in allnodes:
|
|
402
|
+
if not isinstance(node, _OK_NODES):
|
|
403
|
+
errs.append(f"line {getattr(node, 'lineno', '?')}: unsupported syntax {type(node).__name__}")
|
|
404
|
+
continue
|
|
405
|
+
if isinstance(node, ast.FunctionDef):
|
|
406
|
+
errs.append("nested function definitions are not allowed")
|
|
407
|
+
if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name):
|
|
408
|
+
base = node.value.id
|
|
409
|
+
if base in ("np", "numpy", "math") and node.attr not in _MATH_ATTRS:
|
|
410
|
+
errs.append(f"line {node.lineno}: {base}.{node.attr} is not supported inside kernels")
|
|
411
|
+
if base in ("cudaq", "nudaq") and node.attr not in _CUDAQ_ATTRS:
|
|
412
|
+
errs.append(f"line {node.lineno}: {base}.{node.attr} is not supported inside kernels")
|
|
413
|
+
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):
|
|
414
|
+
nm = node.id
|
|
415
|
+
if nm in local or nm in _GATE_NAMES or nm in _registered or nm in _BUILTIN_OK:
|
|
416
|
+
continue
|
|
417
|
+
if nm in ("np", "numpy", "math", "cudaq", "nudaq", "True", "False"):
|
|
418
|
+
continue
|
|
419
|
+
g = fn.__globals__.get(nm, None)
|
|
420
|
+
if isinstance(g, _Kernel):
|
|
421
|
+
continue
|
|
422
|
+
errs.append(f"line {node.lineno}: name '{nm}' is a captured global (pass it as an argument)")
|
|
423
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
|
424
|
+
errs.append(f"line {node.lineno}: string constants are not allowed in kernels")
|
|
425
|
+
# gate names shadowed by module-level variables
|
|
426
|
+
for nm in _GATE_NAMES | set(_registered):
|
|
427
|
+
if nm in fn.__globals__ and not isinstance(fn.__globals__[nm], (_Gate, _CGate)) and nm not in local:
|
|
428
|
+
used = any(isinstance(n, ast.Name) and n.id == nm for n in allnodes)
|
|
429
|
+
if used:
|
|
430
|
+
errs.append(f"global variable '{nm}' shadows the gate {nm}() - rename the variable")
|
|
431
|
+
if errs:
|
|
432
|
+
raise SyntaxError(f"nudaq kernel lint failed for '{fn.__name__}':\n " + "\n ".join(sorted(set(errs))))
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
class _Kernel:
|
|
436
|
+
def __init__(self, fn):
|
|
437
|
+
self.fn = fn
|
|
438
|
+
self.__name__ = fn.__name__
|
|
439
|
+
self._linted = False
|
|
440
|
+
|
|
441
|
+
def _check_args(self, args):
|
|
442
|
+
sig = inspect.signature(self.fn)
|
|
443
|
+
if len(args) != len(sig.parameters):
|
|
444
|
+
raise TypeError(f"nudaq: kernel '{self.__name__}' expects {len(sig.parameters)} args, got {len(args)}")
|
|
445
|
+
for a in args:
|
|
446
|
+
if isinstance(a, np.ndarray):
|
|
447
|
+
raise TypeError(f"nudaq: pass Python lists (e.g. arr.tolist()) to kernel '{self.__name__}', not numpy arrays")
|
|
448
|
+
|
|
449
|
+
def __call__(self, *args):
|
|
450
|
+
if not self._linted:
|
|
451
|
+
_lint(self.fn)
|
|
452
|
+
self._linted = True
|
|
453
|
+
if _ctx is None:
|
|
454
|
+
raise RuntimeError("nudaq: call kernels through sample/get_state/observe/draw")
|
|
455
|
+
return self._bound()(*args)
|
|
456
|
+
|
|
457
|
+
def _bound(self):
|
|
458
|
+
"""The kernel function with gate names visible, without touching Python's builtins."""
|
|
459
|
+
g = dict(self.fn.__globals__)
|
|
460
|
+
g.update(_kernel_names())
|
|
461
|
+
return types.FunctionType(self.fn.__code__, g, self.fn.__name__, self.fn.__defaults__,
|
|
462
|
+
self.fn.__closure__)
|
|
463
|
+
|
|
464
|
+
def _run(self, args):
|
|
465
|
+
global _ctx
|
|
466
|
+
if not self._linted:
|
|
467
|
+
_lint(self.fn)
|
|
468
|
+
self._linted = True
|
|
469
|
+
self._check_args(args)
|
|
470
|
+
prev = _ctx
|
|
471
|
+
_ctx = _Ctx()
|
|
472
|
+
try:
|
|
473
|
+
self(*args)
|
|
474
|
+
return _ctx
|
|
475
|
+
finally:
|
|
476
|
+
_ctx = prev
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def kernel(fn=None, **kw):
|
|
480
|
+
if fn is None:
|
|
481
|
+
return lambda f: _Kernel(f)
|
|
482
|
+
return _Kernel(fn)
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def _sub(kernel_, args, record):
|
|
486
|
+
ctx = _need_ctx()
|
|
487
|
+
old = ctx.record
|
|
488
|
+
ctx.record = []
|
|
489
|
+
try:
|
|
490
|
+
kernel_(*args)
|
|
491
|
+
ops = ctx.record
|
|
492
|
+
finally:
|
|
493
|
+
ctx.record = old
|
|
494
|
+
return ops
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def adjoint(kernel_, *args):
|
|
498
|
+
ctx = _need_ctx()
|
|
499
|
+
ops = _sub(kernel_, args, True)
|
|
500
|
+
for U, t, c, neg in reversed(ops):
|
|
501
|
+
ctx.apply(np.asarray(U).conj().T, t, c, neg)
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def control(kernel_, ctrl, *args):
|
|
505
|
+
ctx = _need_ctx()
|
|
506
|
+
cq, cneg = _flatten_qubits([ctrl])
|
|
507
|
+
ops = _sub(kernel_, args, True)
|
|
508
|
+
for U, t, c, neg in ops:
|
|
509
|
+
ctx.apply(U, t, tuple(c) + tuple(cq), tuple(neg) + tuple(cneg))
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
# --------------------------------------------------------------------------
|
|
513
|
+
# results
|
|
514
|
+
# --------------------------------------------------------------------------
|
|
515
|
+
class State:
|
|
516
|
+
def __init__(self, tensor, n):
|
|
517
|
+
self._t = tensor
|
|
518
|
+
self.n = n
|
|
519
|
+
|
|
520
|
+
def __array__(self, dtype=None, copy=None):
|
|
521
|
+
v = self._t.transpose(list(range(self.n))[::-1]).reshape(-1) # little-endian
|
|
522
|
+
return v.astype(dtype) if dtype else v.copy()
|
|
523
|
+
|
|
524
|
+
def num_qubits(self):
|
|
525
|
+
return self.n
|
|
526
|
+
|
|
527
|
+
def amplitude(self, bits):
|
|
528
|
+
if isinstance(bits, str):
|
|
529
|
+
bits = [int(b) for b in bits]
|
|
530
|
+
if len(bits) != self.n:
|
|
531
|
+
raise ValueError("nudaq: amplitude label length != number of qubits")
|
|
532
|
+
return complex(self._t[tuple(bits)])
|
|
533
|
+
|
|
534
|
+
def amplitudes(self, labels):
|
|
535
|
+
return [self.amplitude(b) for b in labels]
|
|
536
|
+
|
|
537
|
+
def overlap(self, other):
|
|
538
|
+
return complex(np.vdot(self._t.reshape(-1), other._t.reshape(-1)))
|
|
539
|
+
|
|
540
|
+
def __str__(self):
|
|
541
|
+
return "\n".join(f"{c.real:+.6f}{c.imag:+.6f}j" for c in np.array(self))
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def get_state(kernel_, *args):
|
|
545
|
+
ctx = kernel_._run(args)
|
|
546
|
+
if ctx.measured:
|
|
547
|
+
raise RuntimeError("nudaq: do not measure inside kernels passed to get_state")
|
|
548
|
+
return State(ctx.state.copy(), ctx.n)
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
class SampleResult(dict):
|
|
552
|
+
def most_probable(self):
|
|
553
|
+
return max(self, key=self.get)
|
|
554
|
+
|
|
555
|
+
def probability(self, b):
|
|
556
|
+
return self.get(b, 0) / sum(self.values())
|
|
557
|
+
|
|
558
|
+
def count(self, b):
|
|
559
|
+
return self.get(b, 0)
|
|
560
|
+
|
|
561
|
+
def dump(self):
|
|
562
|
+
print(dict(self))
|
|
563
|
+
|
|
564
|
+
def get_total_shots(self):
|
|
565
|
+
return sum(self.values())
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def sample(kernel_, *args, shots_count=1000):
|
|
569
|
+
ctx = kernel_._run(args)
|
|
570
|
+
n = ctx.n
|
|
571
|
+
probs = np.abs(ctx.state) ** 2
|
|
572
|
+
if ctx.measured:
|
|
573
|
+
qs = []
|
|
574
|
+
for q, basis in ctx.measured:
|
|
575
|
+
if basis != "mz":
|
|
576
|
+
raise RuntimeError("nudaq: only mz supported for sampling")
|
|
577
|
+
if q not in qs:
|
|
578
|
+
qs.append(q)
|
|
579
|
+
else:
|
|
580
|
+
qs = list(range(n))
|
|
581
|
+
keep = [q for q in range(n) if q not in qs]
|
|
582
|
+
marg = probs.sum(axis=tuple(keep)) if keep else probs
|
|
583
|
+
order = sorted(qs)
|
|
584
|
+
marg = np.transpose(marg, [order.index(q) for q in qs])
|
|
585
|
+
flat = marg.reshape(-1)
|
|
586
|
+
flat = flat / flat.sum()
|
|
587
|
+
draws = _rng.choice(flat.size, size=shots_count, p=flat)
|
|
588
|
+
k = len(qs)
|
|
589
|
+
res = SampleResult()
|
|
590
|
+
for idx, c in Counter(draws.tolist()).items():
|
|
591
|
+
res[format(idx, f"0{k}b")] = c
|
|
592
|
+
return SampleResult(sorted(res.items()))
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
# spin operators -------------------------------------------------------------
|
|
596
|
+
_P = {"I": _I2, "X": _FIXED["x"], "Y": _FIXED["y"], "Z": _FIXED["z"]}
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
class SpinOperator:
|
|
600
|
+
def __init__(self, terms=None):
|
|
601
|
+
self.terms = dict(terms or {}) # key: tuple(sorted((q,P))) -> coeff
|
|
602
|
+
|
|
603
|
+
@staticmethod
|
|
604
|
+
def _mul_term(a, b):
|
|
605
|
+
d = dict(a)
|
|
606
|
+
ph = 1
|
|
607
|
+
for q, p in b:
|
|
608
|
+
if q not in d:
|
|
609
|
+
d[q] = p
|
|
610
|
+
continue
|
|
611
|
+
m = _P[d[q]] @ _P[p]
|
|
612
|
+
for name, M in _P.items():
|
|
613
|
+
for c in (1, -1, 1j, -1j):
|
|
614
|
+
if np.allclose(m, c * M):
|
|
615
|
+
ph *= c
|
|
616
|
+
d[q] = name
|
|
617
|
+
break
|
|
618
|
+
else:
|
|
619
|
+
continue
|
|
620
|
+
break
|
|
621
|
+
key = tuple(sorted((q, p) for q, p in d.items() if p != "I"))
|
|
622
|
+
return key, ph
|
|
623
|
+
|
|
624
|
+
def __add__(self, o):
|
|
625
|
+
o = _as_op(o)
|
|
626
|
+
t = dict(self.terms)
|
|
627
|
+
for k, v in o.terms.items():
|
|
628
|
+
t[k] = t.get(k, 0) + v
|
|
629
|
+
return SpinOperator(t)
|
|
630
|
+
|
|
631
|
+
__radd__ = __add__
|
|
632
|
+
|
|
633
|
+
def __neg__(self):
|
|
634
|
+
return SpinOperator({k: -v for k, v in self.terms.items()})
|
|
635
|
+
|
|
636
|
+
def __sub__(self, o):
|
|
637
|
+
return self + (-_as_op(o))
|
|
638
|
+
|
|
639
|
+
def __rsub__(self, o):
|
|
640
|
+
return _as_op(o) + (-self)
|
|
641
|
+
|
|
642
|
+
def __mul__(self, o):
|
|
643
|
+
o = _as_op(o)
|
|
644
|
+
t = {}
|
|
645
|
+
for k1, v1 in self.terms.items():
|
|
646
|
+
for k2, v2 in o.terms.items():
|
|
647
|
+
k, ph = self._mul_term(k1, k2)
|
|
648
|
+
t[k] = t.get(k, 0) + v1 * v2 * ph
|
|
649
|
+
return SpinOperator(t)
|
|
650
|
+
|
|
651
|
+
def __rmul__(self, o):
|
|
652
|
+
return _as_op(o) * self
|
|
653
|
+
|
|
654
|
+
def __truediv__(self, c):
|
|
655
|
+
return self * (1 / c)
|
|
656
|
+
|
|
657
|
+
def _matrix(self, n):
|
|
658
|
+
"""MSB-first matrix (qubit 0 most significant), matching the tensor layout."""
|
|
659
|
+
M = np.zeros((2 ** n, 2 ** n), dtype=complex)
|
|
660
|
+
for key, c in self.terms.items():
|
|
661
|
+
d = dict(key)
|
|
662
|
+
m = np.array([[1]], dtype=complex)
|
|
663
|
+
for q in range(n):
|
|
664
|
+
m = np.kron(m, _P[d.get(q, "I")])
|
|
665
|
+
M += c * m
|
|
666
|
+
return M
|
|
667
|
+
|
|
668
|
+
def __str__(self):
|
|
669
|
+
return " + ".join(f"{v}*" + ("".join(f"{p}{q}" for q, p in k) or "I") for k, v in self.terms.items())
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def _as_op(o):
|
|
673
|
+
if isinstance(o, SpinOperator):
|
|
674
|
+
return o
|
|
675
|
+
return SpinOperator({(): complex(o)})
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
class _SpinNS:
|
|
679
|
+
@staticmethod
|
|
680
|
+
def x(q):
|
|
681
|
+
return SpinOperator({((q, "X"),): 1.0})
|
|
682
|
+
|
|
683
|
+
@staticmethod
|
|
684
|
+
def y(q):
|
|
685
|
+
return SpinOperator({((q, "Y"),): 1.0})
|
|
686
|
+
|
|
687
|
+
@staticmethod
|
|
688
|
+
def z(q):
|
|
689
|
+
return SpinOperator({((q, "Z"),): 1.0})
|
|
690
|
+
|
|
691
|
+
@staticmethod
|
|
692
|
+
def i(q):
|
|
693
|
+
return SpinOperator({(): 1.0})
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
spin = _SpinNS()
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
class ObserveResult:
|
|
700
|
+
def __init__(self, e):
|
|
701
|
+
self._e = e
|
|
702
|
+
|
|
703
|
+
def expectation(self, *a):
|
|
704
|
+
return self._e
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def observe(kernel_, op, *args, shots_count=-1):
|
|
708
|
+
ctx = kernel_._run(args)
|
|
709
|
+
if ctx.measured:
|
|
710
|
+
raise RuntimeError("nudaq: do not measure inside kernels passed to observe")
|
|
711
|
+
n = ctx.n
|
|
712
|
+
maxq = max([q for k in op.terms for q, _ in k] + [-1])
|
|
713
|
+
if maxq >= n:
|
|
714
|
+
raise ValueError("nudaq: spin operator acts on more qubits than the kernel allocates")
|
|
715
|
+
psi = ctx.state.reshape(-1)
|
|
716
|
+
e = np.vdot(psi, op._matrix(n) @ psi)
|
|
717
|
+
if abs(e.imag) > 1e-9:
|
|
718
|
+
raise ValueError("nudaq: non-Hermitian observable")
|
|
719
|
+
e = float(e.real)
|
|
720
|
+
if shots_count and shots_count > 0:
|
|
721
|
+
e = e + _rng.normal(0, 1 / math.sqrt(shots_count)) # crude shot noise
|
|
722
|
+
return ObserveResult(e)
|
|
723
|
+
|
|
724
|
+
|
|
725
|
+
def get_unitary(kernel_, *args):
|
|
726
|
+
raise NotImplementedError("nudaq: get_unitary is not supported")
|
|
727
|
+
|
|
728
|
+
|
|
729
|
+
def draw(kernel_, *args):
|
|
730
|
+
ctx = kernel_._run(args)
|
|
731
|
+
lines = []
|
|
732
|
+
for name, ps, cs, ts in ctx.ops:
|
|
733
|
+
p = "(" + ", ".join(f"{v:.3f}" for v in ps) + ")" if ps else ""
|
|
734
|
+
c = f" ctrl={cs}" if cs else ""
|
|
735
|
+
lines.append(f"{name}{p} q{ts}{c}")
|
|
736
|
+
return f"[nudaq circuit, {ctx.n} qubits]\n" + "\n".join(lines)
|
|
737
|
+
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: nudaq
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A small numpy simulator that copies a subset of the CUDA-Q Python API, for running and testing CUDA-Q style code without CUDA-Q
|
|
5
|
+
Project-URL: Homepage, https://github.com/ssuai/nudaq
|
|
6
|
+
Project-URL: Issues, https://github.com/ssuai/nudaq/issues
|
|
7
|
+
Author-email: Yongseok Yoo <yyoo@ssu.ac.kr>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: cuda-q,education,quantum,quantum computing,simulator,testing
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Education
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Topic :: Scientific/Engineering :: Physics
|
|
18
|
+
Classifier: Topic :: Software Development :: Testing
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Requires-Dist: numpy>=1.22
|
|
21
|
+
Provides-Extra: test
|
|
22
|
+
Requires-Dist: pytest>=7; extra == 'test'
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# nudaq
|
|
26
|
+
|
|
27
|
+
A small **numpy** state-vector simulator that copies a subset of the
|
|
28
|
+
[CUDA-Q](https://nvidia.github.io/cuda-quantum/) Python API. Use it to run and test CUDA-Q style code
|
|
29
|
+
where CUDA-Q cannot be installed: Intel Macs, Windows without WSL, lightweight CI runners, or a
|
|
30
|
+
course's test suite.
|
|
31
|
+
|
|
32
|
+
> nudaq is **not** CUDA-Q, and is not affiliated with or endorsed by NVIDIA. It reproduces only the API
|
|
33
|
+
> surface listed below, simulates at most a few dozen qubits (state vector in memory), and gives no
|
|
34
|
+
> performance or exact-behaviour guarantees. Before you rely on results, run your code once on the real
|
|
35
|
+
> CUDA-Q.
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install nudaq
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
The only dependency is numpy. Python ≥ 3.10.
|
|
44
|
+
|
|
45
|
+
## Three ways to use it
|
|
46
|
+
|
|
47
|
+
**1. Write against nudaq directly**
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
import nudaq as cudaq
|
|
51
|
+
|
|
52
|
+
@cudaq.kernel
|
|
53
|
+
def bell():
|
|
54
|
+
q = cudaq.qvector(2)
|
|
55
|
+
h(q[0])
|
|
56
|
+
x.ctrl(q[0], q[1])
|
|
57
|
+
mz(q)
|
|
58
|
+
|
|
59
|
+
print(cudaq.sample(bell, shots_count=1000)) # {'00': ~500, '11': ~500}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
**2. Make `import cudaq` return nudaq in the current process** (a test `conftest.py`, the first cell of
|
|
63
|
+
a notebook):
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
import nudaq
|
|
67
|
+
nudaq.install() # refuses if a real cudaq is already imported
|
|
68
|
+
import cudaq # -> nudaq
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
**3. Run unchanged code that does `import cudaq`** (scripts, Jupyter kernels, test subprocesses):
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
PYTHONPATH="$(python -m nudaq path)" python my_cudaq_script.py
|
|
75
|
+
PYTHONPATH="$(python -m nudaq path)" jupyter nbconvert --execute --to notebook my.ipynb
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
`python -m nudaq path` (or the `nudaq path` command) prints a directory that holds a tiny `cudaq` package
|
|
79
|
+
forwarding to nudaq. `nudaq.alias_path()` returns the same directory from Python.
|
|
80
|
+
|
|
81
|
+
## Supported API (CUDA-Q 0.17 semantics)
|
|
82
|
+
|
|
83
|
+
**Kernels** (`@cudaq.kernel`):
|
|
84
|
+
- Allocation: `cudaq.qvector(n)`, `cudaq.qvector(amplitudes)` (normalised list, little-endian
|
|
85
|
+
order), `cudaq.qubit()`.
|
|
86
|
+
- Indexing: `q[i]`, slices `q[a:b]`, `q.size()`, `q.front()`, `q.back()`, `q.front(k)`, `q.back(k)`,
|
|
87
|
+
`for qb in q`.
|
|
88
|
+
- Gates: `h x y z s t sdg tdg rx ry rz r1 u3 swap`, and the controlled forms `cx cy cz ch crx cry crz cr1`.
|
|
89
|
+
One-qubit gates broadcast over a register (`h(q)`).
|
|
90
|
+
- `.ctrl(...)` with one or several controls, a register as control, and negated controls `~q[0]`.
|
|
91
|
+
`.adj(...)` for adjoints.
|
|
92
|
+
- Sub-kernels with `cudaq.qview` arguments; `cudaq.control(kernel, ctrl, ...)` and
|
|
93
|
+
`cudaq.adjoint(kernel, ...)`.
|
|
94
|
+
- Custom gates with `cudaq.register_operation(name, unitary)`.
|
|
95
|
+
- Measurement with `mz`, as the final operations of a kernel.
|
|
96
|
+
|
|
97
|
+
**Host functions:**
|
|
98
|
+
- `sample(kernel, *args, shots_count=...)` returns a dict-like result with `most_probable`,
|
|
99
|
+
`probability`, `count` and `get_total_shots`.
|
|
100
|
+
- `get_state(...)` returns a state usable as `np.array(state)`, with `amplitude`, `amplitudes` and
|
|
101
|
+
`overlap`.
|
|
102
|
+
- `observe(kernel, H, *args)` with `H` built from `cudaq.spin.x/y/z/i`.
|
|
103
|
+
- Also `draw` (plain text list of gates), `set_random_seed`, `get_target`, and `set_target` (accepted,
|
|
104
|
+
ignored).
|
|
105
|
+
|
|
106
|
+
**Conventions copied from CUDA-Q:**
|
|
107
|
+
- `sample` bitstrings and `state.amplitude("01")` labels put qubit 0 on the **left**.
|
|
108
|
+
- `np.array(state)` is **little-endian**: qubit 0 is the least significant bit of the index.
|
|
109
|
+
`cudaq.qvector(amplitudes)` takes the same order.
|
|
110
|
+
- `register_operation` matrices are in **MSB order**: the first target is the most significant.
|
|
111
|
+
- Gate matrices:
|
|
112
|
+
- `ry(θ)|0⟩ = cos(θ/2)|0⟩ + sin(θ/2)|1⟩`
|
|
113
|
+
- `rx(θ) = e^{-iθX/2}`
|
|
114
|
+
- `rz(θ) = diag(e^{-iθ/2}, e^{iθ/2})`
|
|
115
|
+
- `r1(λ) = diag(1, e^{iλ})`
|
|
116
|
+
|
|
117
|
+
**Kernel lint.** Kernels run eagerly as Python, so nudaq first checks each kernel body and rejects what
|
|
118
|
+
the CUDA-Q kernel compiler rejects:
|
|
119
|
+
- captured globals (pass values as arguments);
|
|
120
|
+
- missing or unsupported argument annotations;
|
|
121
|
+
- default arguments;
|
|
122
|
+
- list comprehensions, strings, nested functions, try/with;
|
|
123
|
+
- numpy calls other than scalar math (`sin cos tan arcsin arccos arctan sqrt exp log`, `pi`);
|
|
124
|
+
- module-level variables that shadow gate names;
|
|
125
|
+
- numpy arrays passed as kernel arguments (pass `arr.tolist()`).
|
|
126
|
+
|
|
127
|
+
Passing the lint makes it likely, not certain, that CUDA-Q compiles the kernel.
|
|
128
|
+
|
|
129
|
+
Allowed argument types: `int float bool complex list[int] list[float] list[bool] list[complex]
|
|
130
|
+
cudaq.qview cudaq.qvector cudaq.qubit`.
|
|
131
|
+
|
|
132
|
+
**Not supported:** `get_unitary`, `exp_pauli`, `reset`, mid-circuit measurement with classical
|
|
133
|
+
feed-forward, noise models, `cudaq.run`, `cudaq.vqe`/optimizers, the builder API (`make_kernel`), GPU
|
|
134
|
+
targets, multi-QPU execution. `cudaq.draw` prints a gate list, not CUDA-Q's ASCII circuit.
|
|
135
|
+
|
|
136
|
+
## Development
|
|
137
|
+
|
|
138
|
+
```bash
|
|
139
|
+
python -m venv .venv && source .venv/bin/activate
|
|
140
|
+
pip install -e ".[test]"
|
|
141
|
+
python -m pytest
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
The tests check nudaq against an independent Kronecker-product reference simulator, the CUDA-Q ordering
|
|
145
|
+
conventions, the lint rules, and the three ways of importing it.
|
|
146
|
+
|
|
147
|
+
## Release
|
|
148
|
+
|
|
149
|
+
1. Update `__version__` in `src/nudaq/__init__.py` and `CHANGELOG.md`.
|
|
150
|
+
2. `python -m build && python -m twine check dist/*`.
|
|
151
|
+
3. Publish: `python -m twine upload dist/*`, or publish a GitHub release. `.github/workflows/publish.yml`
|
|
152
|
+
then uploads it through PyPI trusted publishing.
|
|
153
|
+
|
|
154
|
+
## License
|
|
155
|
+
|
|
156
|
+
MIT. "CUDA-Q" and "NVIDIA" are trademarks of NVIDIA Corporation; they are used here only to describe
|
|
157
|
+
API compatibility.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
nudaq/__init__.py,sha256=-h8zX7Pqh2jYBZdsQl8Day2vF9NMmxk-k05cRSixPm8,2198
|
|
2
|
+
nudaq/__main__.py,sha256=aOl1J0CtAbhYgSmPqyLhDdiWKBKgnu4575WjJihKDmc,639
|
|
3
|
+
nudaq/_core.py,sha256=Q4RdDqBU-ai14G2xQOjzX3TIAd6gNF6yHBbLmfLoQuo,24069
|
|
4
|
+
nudaq/_alias/cudaq/__init__.py,sha256=ZvaiaKKq8smZ0ikmdxzXeIaYhRd1YOirhCE6HzvMqlM,150
|
|
5
|
+
nudaq-0.1.0.dist-info/METADATA,sha256=GPdCUp8tSU1qnXBXDVlmk3dDw5RpJY4Re8oDt0XDanM,6277
|
|
6
|
+
nudaq-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
nudaq-0.1.0.dist-info/entry_points.txt,sha256=sswZyChXyi_hxdZQSA-j0OV3odYVz0BLxN69K_bwAes,46
|
|
8
|
+
nudaq-0.1.0.dist-info/licenses/LICENSE,sha256=9Tzptr1pyvlsvjG2BxIoE9chLcQjpPvWPGEnpHD_LQo,1069
|
|
9
|
+
nudaq-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Yongseok Yoo
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|