PyQrackIsing 9.17.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.
- pyqrackising/__init__.py +22 -0
- pyqrackising/convert_tensor_network_to_tsp.py +93 -0
- pyqrackising/generate_tfim_samples.py +351 -0
- pyqrackising/kernels.cl +1238 -0
- pyqrackising/local_search.py +401 -0
- pyqrackising/maxcut_tfim.py +474 -0
- pyqrackising/maxcut_tfim_sparse.py +518 -0
- pyqrackising/maxcut_tfim_streaming.py +295 -0
- pyqrackising/maxcut_tfim_util.py +791 -0
- pyqrackising/otoc.py +248 -0
- pyqrackising/solve_maxcut_bnb.py +321 -0
- pyqrackising/solve_maxcut_bnb_sparse.py +322 -0
- pyqrackising/solve_maxcut_bnb_streaming.py +292 -0
- pyqrackising/solve_maxcut_exact.py +305 -0
- pyqrackising/solve_maxcut_exact_sparse.py +227 -0
- pyqrackising/solve_maxcut_exact_streaming.py +217 -0
- pyqrackising/solve_qubo.py +133 -0
- pyqrackising/spin_glass_solver.py +545 -0
- pyqrackising/spin_glass_solver_hybrid.py +53 -0
- pyqrackising/spin_glass_solver_sparse.py +611 -0
- pyqrackising/spin_glass_solver_streaming.py +294 -0
- pyqrackising/tfim_magnetization.py +23 -0
- pyqrackising/tfim_square_magnetization.py +22 -0
- pyqrackising/tsp.py +2014 -0
- pyqrackising/tsp_maxcut.py +312 -0
- pyqrackising-9.17.0.dist-info/METADATA +299 -0
- pyqrackising-9.17.0.dist-info/RECORD +30 -0
- pyqrackising-9.17.0.dist-info/WHEEL +5 -0
- pyqrackising-9.17.0.dist-info/licenses/LICENSE.md +165 -0
- pyqrackising-9.17.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,791 @@
|
|
|
1
|
+
import math
|
|
2
|
+
import networkx as nx
|
|
3
|
+
import numpy as np
|
|
4
|
+
import os
|
|
5
|
+
import warnings
|
|
6
|
+
from numba import njit, prange
|
|
7
|
+
from scipy.sparse import lil_matrix, csr_matrix, triu
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class OpenCLContext:
|
|
11
|
+
"""
|
|
12
|
+
OpenCL state, initialised lazily: creating the context and building
|
|
13
|
+
kernels.cl happens the first time a GPU code path reads a device
|
|
14
|
+
attribute (IS_OPENCL_AVAILABLE, queue, a kernel, work_group_size, ...),
|
|
15
|
+
not at import. dtype, epsilon and GRAY_NODE_LIMIT are static.
|
|
16
|
+
|
|
17
|
+
The device is chosen non-interactively: set PYOPENCL_CTX (e.g. "0" or
|
|
18
|
+
"0:1") to pick one; otherwise PyOpenCL's first device is used. If PyOpenCL
|
|
19
|
+
is missing or no device initialises, IS_OPENCL_AVAILABLE is False, one
|
|
20
|
+
warning is issued, and the solvers use their CPU paths.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
GRAY_NODE_LIMIT = 131072
|
|
24
|
+
|
|
25
|
+
def __init__(self, dtype, epsilon, kernel_src):
|
|
26
|
+
self.dtype = dtype
|
|
27
|
+
self.epsilon = epsilon
|
|
28
|
+
self._kernel_src = kernel_src
|
|
29
|
+
self._initialized = False
|
|
30
|
+
|
|
31
|
+
def __getattr__(self, name):
|
|
32
|
+
# Only reached for attributes not yet set, i.e. device state before init.
|
|
33
|
+
if name.startswith("_") or self.__dict__.get("_initialized", True):
|
|
34
|
+
raise AttributeError(name)
|
|
35
|
+
self._initialize()
|
|
36
|
+
return getattr(self, name)
|
|
37
|
+
|
|
38
|
+
def _set_unavailable(self, reason):
|
|
39
|
+
self.IS_OPENCL_AVAILABLE = False
|
|
40
|
+
self.MAX_GPU_PROC_ELEM = None
|
|
41
|
+
self.work_group_size = 32
|
|
42
|
+
self.max_alloc = 0xFFFFFFFFFFFFFFFF
|
|
43
|
+
self.ctx = None
|
|
44
|
+
self.queue = None
|
|
45
|
+
for k in _KERNEL_NAMES:
|
|
46
|
+
setattr(self, k + "_kernel", None)
|
|
47
|
+
warnings.warn(reason + " PyQrackIsing will use its CPU code paths.", RuntimeWarning, stacklevel=3)
|
|
48
|
+
|
|
49
|
+
def _initialize(self):
|
|
50
|
+
self._initialized = True
|
|
51
|
+
if cl is None:
|
|
52
|
+
self._set_unavailable(
|
|
53
|
+
"PyOpenCL not installed. (If you have any OpenCL accelerator devices with available ICDs, "
|
|
54
|
+
"you might want to optionally install pyopencl.)"
|
|
55
|
+
)
|
|
56
|
+
return
|
|
57
|
+
try:
|
|
58
|
+
ctx = cl.create_some_context(interactive=False)
|
|
59
|
+
queue = cl.CommandQueue(ctx)
|
|
60
|
+
program = cl.Program(ctx, self._kernel_src + open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "kernels.cl")).read()).build()
|
|
61
|
+
except Exception as ex: # no platform/ICD, build failure, ...
|
|
62
|
+
self._set_unavailable("OpenCL initialisation failed (" + type(ex).__name__ + ": " + str(ex).strip() + ").")
|
|
63
|
+
return
|
|
64
|
+
self.IS_OPENCL_AVAILABLE = True
|
|
65
|
+
self.ctx = ctx
|
|
66
|
+
self.queue = queue
|
|
67
|
+
self.MAX_GPU_PROC_ELEM = int(
|
|
68
|
+
os.getenv("PYQRACKISING_MAX_GPU_PROC_ELEM", str(ctx.devices[0].get_info(cl.device_info.MAX_COMPUTE_UNITS)))
|
|
69
|
+
)
|
|
70
|
+
for k in _KERNEL_NAMES:
|
|
71
|
+
setattr(self, k + "_kernel", getattr(program, k))
|
|
72
|
+
self.work_group_size = self.calculate_cut_kernel.get_work_group_info(
|
|
73
|
+
cl.kernel_work_group_info.PREFERRED_WORK_GROUP_SIZE_MULTIPLE, ctx.devices[0]
|
|
74
|
+
)
|
|
75
|
+
self.max_alloc = ctx.devices[0].get_info(cl.device_info.MAX_MEM_ALLOC_SIZE)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
_KERNEL_NAMES = (
|
|
79
|
+
"calculate_cut",
|
|
80
|
+
"calculate_cut_sparse",
|
|
81
|
+
"calculate_cut_segmented",
|
|
82
|
+
"calculate_cut_sparse_segmented",
|
|
83
|
+
"single_bit_flips",
|
|
84
|
+
"single_bit_flips_sparse",
|
|
85
|
+
"single_bit_flips_segmented",
|
|
86
|
+
"single_bit_flips_sparse_segmented",
|
|
87
|
+
"double_bit_flips",
|
|
88
|
+
"double_bit_flips_sparse",
|
|
89
|
+
"double_bit_flips_segmented",
|
|
90
|
+
"double_bit_flips_sparse_segmented",
|
|
91
|
+
"gray",
|
|
92
|
+
"gray_segmented",
|
|
93
|
+
"gray_sparse",
|
|
94
|
+
"gray_sparse_segmented",
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
dtype_bits = int(os.getenv("PYQRACKISING_FPPOW", "5"))
|
|
98
|
+
kernel_src = ""
|
|
99
|
+
if dtype_bits <= 4:
|
|
100
|
+
dtype = np.float16
|
|
101
|
+
epsilon = 2**-10
|
|
102
|
+
kernel_src += "#pragma OPENCL EXTENSION cl_khr_fp16 : enable\n"
|
|
103
|
+
kernel_src += "#define FP16 1\n"
|
|
104
|
+
kernel_src += "#define real1 half\n"
|
|
105
|
+
kernel_src += "#define qint short\n"
|
|
106
|
+
kernel_src += "#define EPSILON ((half)0.00097656f)\n"
|
|
107
|
+
kernel_src += "#define ZERO_R1 ((half)0.0f)\n"
|
|
108
|
+
kernel_src += "#define ONE_R1 ((half)1.0f)\n"
|
|
109
|
+
kernel_src += "#define TWO_R1 ((half)2.0f)\n"
|
|
110
|
+
elif dtype_bits >= 6:
|
|
111
|
+
dtype = np.float64
|
|
112
|
+
epsilon = 2**-52
|
|
113
|
+
kernel_src += "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"
|
|
114
|
+
kernel_src += "#define real1 double\n"
|
|
115
|
+
kernel_src += "#define qint long\n"
|
|
116
|
+
kernel_src += "#define EPSILON DBL_EPSILON\n"
|
|
117
|
+
kernel_src += "#define ZERO_R1 0.0\n"
|
|
118
|
+
kernel_src += "#define ONE_R1 1.0\n"
|
|
119
|
+
kernel_src += "#define TWO_R1 2.0\n"
|
|
120
|
+
else:
|
|
121
|
+
dtype = np.float32
|
|
122
|
+
epsilon = 2**-23
|
|
123
|
+
kernel_src += "#define real1 float\n"
|
|
124
|
+
kernel_src += "#define qint int\n"
|
|
125
|
+
kernel_src += "#define EPSILON FLT_EPSILON\n"
|
|
126
|
+
kernel_src += "#define ZERO_R1 0.0f\n"
|
|
127
|
+
kernel_src += "#define ONE_R1 1.0f\n"
|
|
128
|
+
kernel_src += "#define TWO_R1 2.0f\n"
|
|
129
|
+
|
|
130
|
+
try:
|
|
131
|
+
import pyopencl as cl
|
|
132
|
+
|
|
133
|
+
warnings.simplefilter("ignore", cl.CompilerWarning)
|
|
134
|
+
except Exception: # not installed, or a broken install: fall back to CPU paths
|
|
135
|
+
cl = None
|
|
136
|
+
|
|
137
|
+
opencl_context = OpenCLContext(dtype, epsilon, kernel_src)
|
|
138
|
+
heuristic_threshold = 24
|
|
139
|
+
heuristic_threshold_sparse = 23
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def setup_opencl(l, g, args_np, is_gray=False):
|
|
143
|
+
ctx = opencl_context.ctx
|
|
144
|
+
queue = opencl_context.queue
|
|
145
|
+
dtype = opencl_context.dtype
|
|
146
|
+
wgs = opencl_context.work_group_size
|
|
147
|
+
|
|
148
|
+
# Buffers
|
|
149
|
+
mf = cl.mem_flags
|
|
150
|
+
args_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=args_np)
|
|
151
|
+
|
|
152
|
+
# Group sizes
|
|
153
|
+
local_size = min(wgs, l)
|
|
154
|
+
max_global_size = (
|
|
155
|
+
(opencl_context.MAX_GPU_PROC_ELEM + local_size - 1) // local_size
|
|
156
|
+
) * local_size # corresponds to MAX_PROC_ELEM macro in OpenCL kernel program
|
|
157
|
+
global_size = min(((g + local_size - 1) // local_size) * local_size, max_global_size)
|
|
158
|
+
|
|
159
|
+
max_energy_host = np.empty(global_size // local_size, dtype=dtype)
|
|
160
|
+
max_energy_buf = cl.Buffer(ctx, mf.WRITE_ONLY, max_energy_host.nbytes)
|
|
161
|
+
|
|
162
|
+
if is_gray:
|
|
163
|
+
max_theta_host = np.empty(((args_np[0] + 63) // 64) * (global_size // local_size), dtype=np.int64)
|
|
164
|
+
max_theta_buf = cl.Buffer(ctx, mf.WRITE_ONLY, max_theta_host.nbytes)
|
|
165
|
+
|
|
166
|
+
return (
|
|
167
|
+
local_size,
|
|
168
|
+
global_size,
|
|
169
|
+
args_buf,
|
|
170
|
+
max_energy_host,
|
|
171
|
+
max_theta_host,
|
|
172
|
+
max_energy_buf,
|
|
173
|
+
max_theta_buf,
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
# Local memory allocation (1 float per work item)
|
|
177
|
+
local_energy_buf = cl.LocalMemory(np.dtype(dtype).itemsize * local_size)
|
|
178
|
+
local_index_buf = cl.LocalMemory(np.dtype(np.int32).itemsize * local_size)
|
|
179
|
+
|
|
180
|
+
# Allocate max_energy and max_index result buffers per workgroup
|
|
181
|
+
max_index_host = np.empty(global_size // local_size, dtype=np.int32)
|
|
182
|
+
max_index_buf = cl.Buffer(ctx, mf.WRITE_ONLY, max_index_host.nbytes)
|
|
183
|
+
|
|
184
|
+
return (
|
|
185
|
+
local_size,
|
|
186
|
+
global_size,
|
|
187
|
+
args_buf,
|
|
188
|
+
local_energy_buf,
|
|
189
|
+
local_index_buf,
|
|
190
|
+
max_energy_host,
|
|
191
|
+
max_index_host,
|
|
192
|
+
max_energy_buf,
|
|
193
|
+
max_index_buf,
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def pad_split4(flat, segment_size):
|
|
198
|
+
"""Zero-pad a flat array to 4 * segment_size and split it into the four
|
|
199
|
+
equal segments the *_segmented kernels index (flat_idx / segment_size)."""
|
|
200
|
+
flat = np.ravel(flat)
|
|
201
|
+
n_shape = segment_size << 2
|
|
202
|
+
if flat.shape[0] > n_shape:
|
|
203
|
+
raise ValueError("pad_split4: array longer than 4 * segment_size")
|
|
204
|
+
if flat.shape[0] != n_shape:
|
|
205
|
+
flat = np.concatenate((flat, np.zeros(n_shape - flat.shape[0], dtype=flat.dtype)))
|
|
206
|
+
return [np.ascontiguousarray(seg) for seg in np.split(flat, 4)]
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def make_G_m_buf(G_m, is_segmented, segment_size):
|
|
210
|
+
mf = cl.mem_flags
|
|
211
|
+
ctx = opencl_context.ctx
|
|
212
|
+
if is_segmented:
|
|
213
|
+
G_m_segments = pad_split4(G_m, segment_size)
|
|
214
|
+
G_m_buf = [cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=seg) for seg in G_m_segments]
|
|
215
|
+
else:
|
|
216
|
+
G_m_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=G_m)
|
|
217
|
+
|
|
218
|
+
return G_m_buf
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def make_G_m_csr_buf(G_m, is_segmented, segment_size):
|
|
222
|
+
mf = cl.mem_flags
|
|
223
|
+
ctx = opencl_context.ctx
|
|
224
|
+
G_rows_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=G_m.indptr)
|
|
225
|
+
G_cols_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=G_m.indices)
|
|
226
|
+
if is_segmented:
|
|
227
|
+
G_data_segments = pad_split4(G_m.data, segment_size)
|
|
228
|
+
G_data_buf = [cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=seg) for seg in G_data_segments]
|
|
229
|
+
else:
|
|
230
|
+
G_data_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=G_m.data)
|
|
231
|
+
|
|
232
|
+
return G_data_buf, G_rows_buf, G_cols_buf
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def make_theta_buf(theta, is_segmented, shots, n):
|
|
236
|
+
mf = cl.mem_flags
|
|
237
|
+
ctx = opencl_context.ctx
|
|
238
|
+
if is_segmented:
|
|
239
|
+
n_shape = (((shots + 3) >> 2) << 2) * ((n + 31) >> 5)
|
|
240
|
+
theta = np.reshape(theta, (n_shape,))
|
|
241
|
+
theta_segments = np.split(theta, 4)
|
|
242
|
+
theta_buf = [cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=seg) for seg in theta_segments]
|
|
243
|
+
else:
|
|
244
|
+
theta_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=theta)
|
|
245
|
+
|
|
246
|
+
return theta_buf
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def make_best_theta_buf(theta):
|
|
250
|
+
n = theta.shape[0]
|
|
251
|
+
n32 = (n + 31) >> 5
|
|
252
|
+
theta_np = np.zeros(n32, dtype=np.uint32)
|
|
253
|
+
for i in range(n):
|
|
254
|
+
if theta[i]:
|
|
255
|
+
theta_np[(i >> 5)] |= 1 << (i & 31)
|
|
256
|
+
|
|
257
|
+
mf = cl.mem_flags
|
|
258
|
+
theta_buf = cl.Buffer(opencl_context.ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=theta_np)
|
|
259
|
+
|
|
260
|
+
return theta_buf
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def make_best_theta_buf_64(theta):
|
|
264
|
+
n = theta.shape[0]
|
|
265
|
+
n64 = (n + 63) >> 6
|
|
266
|
+
theta_np = np.zeros(n64, dtype=np.uint64)
|
|
267
|
+
for i in range(n):
|
|
268
|
+
if theta[i]:
|
|
269
|
+
theta_np[(i >> 6)] |= 1 << (i & 63)
|
|
270
|
+
|
|
271
|
+
mf = cl.mem_flags
|
|
272
|
+
theta_buf = cl.Buffer(opencl_context.ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=theta_np)
|
|
273
|
+
|
|
274
|
+
return theta_buf
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
@njit(parallel=True, cache=True)
|
|
278
|
+
def convert_bool_to_uint(samples):
|
|
279
|
+
shots = samples.shape[0]
|
|
280
|
+
n = samples.shape[1]
|
|
281
|
+
n32 = (n + 31) >> 5
|
|
282
|
+
theta = np.zeros(shots * n32, dtype=np.uint32)
|
|
283
|
+
for i in prange(shots):
|
|
284
|
+
i_offset = i * n32
|
|
285
|
+
for j in range(n):
|
|
286
|
+
if samples[i, j]:
|
|
287
|
+
theta[i_offset + (j >> 5)] |= 1 << (j & 31)
|
|
288
|
+
|
|
289
|
+
return theta
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
@njit(cache=True)
|
|
293
|
+
def compute_energy(sample, G_m, n_qubits):
|
|
294
|
+
result = np.repeat(sample, n_qubits).reshape(-1, n_qubits) ^ np.broadcast_to(sample, (n_qubits, n_qubits))
|
|
295
|
+
result = (result << 1) - 1
|
|
296
|
+
|
|
297
|
+
return (result * G_m).sum() / 2.0
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
@njit(cache=True)
|
|
301
|
+
def compute_cut(sample, G_m, n_qubits):
|
|
302
|
+
result = np.repeat(sample, n_qubits).reshape(-1, n_qubits) ^ np.broadcast_to(sample, (n_qubits, n_qubits))
|
|
303
|
+
|
|
304
|
+
return (result * G_m).sum() / 2.0
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
@njit(cache=True)
|
|
308
|
+
def compute_cut_diff(u, sample, G_m, n_qubits):
|
|
309
|
+
return (G_m[u] * (((sample[u] ^ sample) << 1) - 1)).sum()
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
@njit(cache=True)
|
|
313
|
+
def compute_cut_diff_2(k, l, sample, G_m, n_qubits):
|
|
314
|
+
k_x = ((sample[k] ^ sample) << 1) - 1
|
|
315
|
+
l_x = ((sample[l] ^ sample) << 1) - 1
|
|
316
|
+
k_x[l] = 0
|
|
317
|
+
l_x[k] = 0
|
|
318
|
+
|
|
319
|
+
return (G_m[k] * k_x).sum() + (G_m[l] * l_x).sum()
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
@njit(cache=True)
|
|
323
|
+
def compute_energy_sparse(sample, G_data, G_rows, G_cols, n_qubits):
|
|
324
|
+
energy = 0.0
|
|
325
|
+
for u in range(n_qubits):
|
|
326
|
+
u_bit = sample[u]
|
|
327
|
+
for col in range(G_rows[u], G_rows[u + 1]):
|
|
328
|
+
val = G_data[col]
|
|
329
|
+
energy += -val if u_bit == sample[G_cols[col]] else val
|
|
330
|
+
|
|
331
|
+
return energy
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
@njit(cache=True)
|
|
335
|
+
def compute_cut_sparse(sample, G_data, G_rows, G_cols, n_qubits):
|
|
336
|
+
cut = 0.0
|
|
337
|
+
for u in range(n_qubits):
|
|
338
|
+
u_bit = sample[u]
|
|
339
|
+
for col in range(G_rows[u], G_rows[u + 1]):
|
|
340
|
+
j = G_cols[col]
|
|
341
|
+
if j > u and u_bit != sample[j]:
|
|
342
|
+
cut += G_data[col]
|
|
343
|
+
|
|
344
|
+
return cut
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
@njit(cache=True)
|
|
348
|
+
def compute_energy_streaming(sample, G_func, nodes, n_qubits):
|
|
349
|
+
energy = 0.0
|
|
350
|
+
for u in range(n_qubits):
|
|
351
|
+
u_bit = sample[u]
|
|
352
|
+
u_node = nodes[u]
|
|
353
|
+
for v in range(u + 1, n_qubits):
|
|
354
|
+
val = G_func(u_node, nodes[v])
|
|
355
|
+
energy += -val if u_bit == sample[v] else val
|
|
356
|
+
|
|
357
|
+
return energy
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
@njit(cache=True)
|
|
361
|
+
def compute_cut_streaming(sample, G_func, nodes, n_qubits):
|
|
362
|
+
cut = 0.0
|
|
363
|
+
for u in range(n_qubits):
|
|
364
|
+
u_bit = sample[u]
|
|
365
|
+
u_node = nodes[u]
|
|
366
|
+
for v in range(u + 1, n_qubits):
|
|
367
|
+
if u_bit != sample[v]:
|
|
368
|
+
cut += G_func(u_node, nodes[v])
|
|
369
|
+
|
|
370
|
+
return cut
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
@njit(cache=True)
|
|
374
|
+
def compute_cut_diff_streaming(u, sample, G_func, nodes, n_qubits):
|
|
375
|
+
energy = 0.0
|
|
376
|
+
u_bit = sample[u]
|
|
377
|
+
u_node = nodes[u]
|
|
378
|
+
for v in range(u):
|
|
379
|
+
val = G_func(u_node, nodes[v])
|
|
380
|
+
energy += -val if u_bit == sample[v] else val
|
|
381
|
+
for v in range(u + 1, n_qubits):
|
|
382
|
+
val = G_func(u_node, nodes[v])
|
|
383
|
+
energy += -val if u_bit == sample[v] else val
|
|
384
|
+
|
|
385
|
+
return energy
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
@njit(cache=True)
|
|
389
|
+
def compute_cut_diff_2_streaming(k, l, sample, G_func, nodes, n_qubits):
|
|
390
|
+
if l < k:
|
|
391
|
+
t = k
|
|
392
|
+
k = l
|
|
393
|
+
l = t
|
|
394
|
+
energy = 0.0
|
|
395
|
+
k_bit = sample[k]
|
|
396
|
+
k_node = nodes[k]
|
|
397
|
+
l_bit = sample[l]
|
|
398
|
+
l_node = nodes[l]
|
|
399
|
+
for v in range(k):
|
|
400
|
+
val = G_func(k_node, nodes[v])
|
|
401
|
+
energy += -val if k_bit == sample[v] else val
|
|
402
|
+
val = G_func(l_node, nodes[v])
|
|
403
|
+
energy += -val if l_bit == sample[v] else val
|
|
404
|
+
for v in range(k + 1, l):
|
|
405
|
+
val = G_func(k_node, nodes[v])
|
|
406
|
+
energy += -val if k_bit == sample[v] else val
|
|
407
|
+
val = G_func(l_node, nodes[v])
|
|
408
|
+
energy += -val if l_bit == sample[v] else val
|
|
409
|
+
for v in range(l + 1, n_qubits):
|
|
410
|
+
val = G_func(k_node, nodes[v])
|
|
411
|
+
energy += -val if k_bit == sample[v] else val
|
|
412
|
+
val = G_func(l_node, nodes[v])
|
|
413
|
+
energy += -val if l_bit == sample[v] else val
|
|
414
|
+
|
|
415
|
+
return energy
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
@njit(cache=True)
|
|
419
|
+
def compute_cut_diff_between(o_theta, n_theta, G_m, n_qubits):
|
|
420
|
+
energy = 0.0
|
|
421
|
+
|
|
422
|
+
for i in range(n_qubits):
|
|
423
|
+
G_i = G_m[i]
|
|
424
|
+
o_i_bit = o_theta[i]
|
|
425
|
+
n_i_bit = n_theta[i]
|
|
426
|
+
for j in range(i + 1, n_qubits):
|
|
427
|
+
o_diff = o_i_bit != o_theta[j]
|
|
428
|
+
n_diff = n_i_bit != n_theta[j]
|
|
429
|
+
|
|
430
|
+
if o_diff != n_diff:
|
|
431
|
+
gij = G_i[j]
|
|
432
|
+
energy += gij if n_diff else -gij
|
|
433
|
+
|
|
434
|
+
return energy
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
@njit(cache=True)
|
|
438
|
+
def compute_cut_diff_between_streaming(o_theta, n_theta, G_func, nodes, n_qubits):
|
|
439
|
+
energy = 0.0
|
|
440
|
+
|
|
441
|
+
for i in range(n_qubits):
|
|
442
|
+
o_i_bit = o_theta[i]
|
|
443
|
+
n_i_bit = n_theta[i]
|
|
444
|
+
for j in range(i + 1, n_qubits):
|
|
445
|
+
o_diff = o_i_bit != o_theta[j]
|
|
446
|
+
n_diff = n_i_bit != n_theta[j]
|
|
447
|
+
|
|
448
|
+
if o_diff != n_diff:
|
|
449
|
+
gij = G_func(nodes[i], nodes[j])
|
|
450
|
+
energy += gij if n_diff else -gij
|
|
451
|
+
|
|
452
|
+
return energy
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
@njit(cache=True)
|
|
456
|
+
def get_cut(solution, nodes, n):
|
|
457
|
+
bit_string = ""
|
|
458
|
+
l, r = [], []
|
|
459
|
+
for i in range(n):
|
|
460
|
+
if solution[i]:
|
|
461
|
+
bit_string += "1"
|
|
462
|
+
r.append(nodes[i])
|
|
463
|
+
else:
|
|
464
|
+
bit_string += "0"
|
|
465
|
+
l.append(nodes[i])
|
|
466
|
+
|
|
467
|
+
return bit_string, l, r
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
@njit(cache=True)
|
|
471
|
+
def get_cut_base(solution, n):
|
|
472
|
+
l, r = [], []
|
|
473
|
+
for i in range(n):
|
|
474
|
+
if solution[i]:
|
|
475
|
+
r.append(i)
|
|
476
|
+
else:
|
|
477
|
+
l.append(i)
|
|
478
|
+
|
|
479
|
+
return l, r
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
# By Gemini (Google Search AI)
|
|
483
|
+
def int_to_bitstring(integer, length):
|
|
484
|
+
return (bin(integer)[2:].zfill(length))[::-1]
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
@njit(cache=True)
|
|
488
|
+
def binary_search(l, t):
|
|
489
|
+
left = 0
|
|
490
|
+
right = len(l) - 1
|
|
491
|
+
|
|
492
|
+
while left <= right:
|
|
493
|
+
mid = (left + right) >> 1
|
|
494
|
+
|
|
495
|
+
if l[mid] == t:
|
|
496
|
+
return mid
|
|
497
|
+
|
|
498
|
+
if l[mid] < t:
|
|
499
|
+
left = mid + 1
|
|
500
|
+
else:
|
|
501
|
+
right = mid - 1
|
|
502
|
+
|
|
503
|
+
return len(l)
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
# ---------------------------------------------------------------------------
|
|
507
|
+
# Reproducible random numbers
|
|
508
|
+
#
|
|
509
|
+
# Numba's np.random state is per thread and is NOT seeded by np.random.seed()
|
|
510
|
+
# called from Python, so solves were not reproducible. The samplers instead
|
|
511
|
+
# draw from a counter-based generator keyed by (base seed, round, shot index):
|
|
512
|
+
# results depend only on the seed (and, for the CPU samplers, on the chain
|
|
513
|
+
# count, which defaults from os.cpu_count()), never on thread scheduling.
|
|
514
|
+
# ---------------------------------------------------------------------------
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def resolve_seed(seed):
|
|
518
|
+
"""Base seed for a solve. None draws one from NumPy's global generator,
|
|
519
|
+
so np.random.seed(...) in Python now also makes runs repeatable."""
|
|
520
|
+
if seed is None:
|
|
521
|
+
return int(np.random.randint(0, 2**62))
|
|
522
|
+
return int(seed) & ((1 << 62) - 1)
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
@njit(cache=True)
|
|
526
|
+
def rng_init(base_seed, rnd, s):
|
|
527
|
+
x = np.uint64(base_seed) ^ (np.uint64(rnd) * np.uint64(0xD1B54A32D192ED03)) ^ (np.uint64(s) * np.uint64(0x9E3779B97F4A7C15))
|
|
528
|
+
state, _ = rng_next(x)
|
|
529
|
+
return state
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
@njit(cache=True)
|
|
533
|
+
def rng_next(state):
|
|
534
|
+
"""splitmix64: returns (new state, 64-bit output)."""
|
|
535
|
+
state = state + np.uint64(0x9E3779B97F4A7C15)
|
|
536
|
+
z = state
|
|
537
|
+
z = (z ^ (z >> np.uint64(30))) * np.uint64(0xBF58476D1CE4E5B9)
|
|
538
|
+
z = (z ^ (z >> np.uint64(27))) * np.uint64(0x94D049BB133111EB)
|
|
539
|
+
return state, z ^ (z >> np.uint64(31))
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
@njit(cache=True)
|
|
543
|
+
def rng_uniform(state):
|
|
544
|
+
"""Returns (new state, uniform float64 in [0, 1))."""
|
|
545
|
+
state, z = rng_next(state)
|
|
546
|
+
return state, float(z >> np.uint64(11)) * (1.0 / 9007199254740992.0)
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
# Dense samplers multiply weights by repulsion_base ** -G_m[node] on every pick;
|
|
550
|
+
# precomputing that table once is ~6x faster. It costs one float32 n x n array
|
|
551
|
+
# (the size of G_m itself), so it is skipped above this many bytes.
|
|
552
|
+
REPULSION_TABLE_MAX_BYTES = int(os.getenv("PYQRACKISING_REPULSION_TABLE_MB", "2048")) << 20
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def repulsion_table(G_m, repulsion_base):
|
|
556
|
+
"""(R, use_table) for the dense samplers; R is a 1x1 dummy when unused."""
|
|
557
|
+
n = G_m.shape[0]
|
|
558
|
+
if abs(1.0 - repulsion_base) <= epsilon or (n * n * 4) > REPULSION_TABLE_MAX_BYTES:
|
|
559
|
+
return np.ones((1, 1), dtype=np.float32), False
|
|
560
|
+
return np.power(np.float64(repulsion_base), -np.asarray(G_m, dtype=np.float64)).astype(np.float32), True
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def as_upper_csr(G_m):
|
|
564
|
+
"""Strict upper triangle of a (scipy) adjacency matrix as sorted CSR in the
|
|
565
|
+
solver dtype: the convention the sparse kernels and energy functions use.
|
|
566
|
+
A full symmetric matrix and its upper triangle give the same graph."""
|
|
567
|
+
U = triu(csr_matrix(G_m), k=1, format="csr").astype(dtype)
|
|
568
|
+
U.eliminate_zeros()
|
|
569
|
+
U.sort_indices()
|
|
570
|
+
return U
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def symmetric_csr(G_upper):
|
|
574
|
+
"""Both triangles of an upper-triangular CSR (for O(degree) neighbour loops
|
|
575
|
+
in local_search)."""
|
|
576
|
+
S = (G_upper + G_upper.T).tocsr().astype(np.float64)
|
|
577
|
+
S.sort_indices()
|
|
578
|
+
return S
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def to_scipy_sparse_upper_triangular(G, nodes, n_nodes):
|
|
582
|
+
lil = lil_matrix((n_nodes, n_nodes), dtype=dtype)
|
|
583
|
+
for u in range(n_nodes):
|
|
584
|
+
u_node = nodes[u]
|
|
585
|
+
for v in range(u + 1, n_nodes):
|
|
586
|
+
v_node = nodes[v]
|
|
587
|
+
if G.has_edge(u_node, v_node):
|
|
588
|
+
lil[u, v] = G[u_node][v_node].get("weight", 1.0)
|
|
589
|
+
|
|
590
|
+
return lil.tocsr()
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
@njit(parallel=True, cache=True)
|
|
594
|
+
def init_theta(h_mult, n_qubits, J_eff, degrees):
|
|
595
|
+
theta = np.empty(n_qubits, dtype=np.float64)
|
|
596
|
+
h_mult = abs(h_mult)
|
|
597
|
+
for q in prange(n_qubits):
|
|
598
|
+
J = J_eff[q]
|
|
599
|
+
z = degrees[q]
|
|
600
|
+
zJ = z * J
|
|
601
|
+
theta[q] = ((np.pi if J > 0 else -np.pi) / 2) if abs(zJ) < epsilon else np.arcsin(max(-1.0, min(1.0, h_mult / zJ)))
|
|
602
|
+
|
|
603
|
+
return theta
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def init_thresholds(n_qubits, theta=0.0):
|
|
607
|
+
n_bias = n_qubits + 1
|
|
608
|
+
p = (1.0 - np.sin(theta)) / 2.0
|
|
609
|
+
return np.array([math.comb(n_qubits, k) * (p ** k * (1.0 - p) ** (n_qubits - k)) for k in range(n_bias)])
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
@njit(cache=True)
|
|
613
|
+
def _apply_time_envelope(bias, t, n_qubits):
|
|
614
|
+
"""
|
|
615
|
+
Multiply bias[k] by exp(-|k - n/2| / max(t, epsilon)) for each k.
|
|
616
|
+
|
|
617
|
+
This is the time-dependent Hamming weight envelope:
|
|
618
|
+
- At small t: peaks sharply at half-filling k = n/2 (AFM sector).
|
|
619
|
+
- At large t: envelope -> 1, recovering the original bias exactly.
|
|
620
|
+
|
|
621
|
+
The differential effect is greatest at initialization (small t),
|
|
622
|
+
which is where the ESD / adiabatic physics lives.
|
|
623
|
+
|
|
624
|
+
alpha = 1.0 is hardcoded as the natural physical invariant.
|
|
625
|
+
It is the least contrived value that produces the correct qualitative
|
|
626
|
+
behaviour, and is left fixed rather than tuned empirically.
|
|
627
|
+
|
|
628
|
+
Authors: Claude (Anthropic) and D. Strano
|
|
629
|
+
"""
|
|
630
|
+
alpha = 1.0
|
|
631
|
+
half = n_qubits / 2.0
|
|
632
|
+
# Numba-safe floor of t for the epsilon guard
|
|
633
|
+
t_eff = t if t > 1e-9 else 1e-9
|
|
634
|
+
|
|
635
|
+
out = np.empty(n_qubits + 1, dtype=np.float64)
|
|
636
|
+
tot = 0.0
|
|
637
|
+
for k in range(n_qubits + 1):
|
|
638
|
+
dist = k - half
|
|
639
|
+
if dist < 0.0:
|
|
640
|
+
dist = -dist
|
|
641
|
+
envelope = math.exp(-alpha * dist / t_eff)
|
|
642
|
+
val = bias[k] * envelope
|
|
643
|
+
out[k] = val
|
|
644
|
+
tot += val
|
|
645
|
+
|
|
646
|
+
if tot <= 0.0:
|
|
647
|
+
# Pathological underflow: collapse to half-filling delta
|
|
648
|
+
for k in range(n_qubits + 1):
|
|
649
|
+
out[k] = 0.0
|
|
650
|
+
mid = n_qubits // 2
|
|
651
|
+
out[mid] = 1.0
|
|
652
|
+
return out
|
|
653
|
+
|
|
654
|
+
for k in range(n_qubits + 1):
|
|
655
|
+
out[k] /= tot
|
|
656
|
+
|
|
657
|
+
return out
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
@njit(cache=True)
|
|
661
|
+
def probability_by_hamming_weight(J, h, z, theta, t, n_bias, omega=1.5 * np.pi):
|
|
662
|
+
zJ = z * J
|
|
663
|
+
theta_c = ((np.pi if J > 0 else -np.pi) / 2) if abs(zJ) < epsilon else np.arcsin(max(-1.0, min(1.0, h / zJ)))
|
|
664
|
+
|
|
665
|
+
p = 2.0 ** (abs(J / h) - 1.0) * (1.0 + np.sin(theta - theta_c) * np.cos(omega * J * t + theta) / (1.0 + np.sqrt(t))) - 0.5
|
|
666
|
+
|
|
667
|
+
bias = np.empty(n_bias, dtype=np.float64)
|
|
668
|
+
factor = 2.0 ** -(p / n_bias)
|
|
669
|
+
result = 1.0
|
|
670
|
+
for q in range(n_bias):
|
|
671
|
+
result *= factor
|
|
672
|
+
bias[q] = result
|
|
673
|
+
|
|
674
|
+
if (result == 0.0) or np.isnan(result) or np.isinf(result):
|
|
675
|
+
print("[WARN]: probability_by_hamming_weight() went below maximum precision.")
|
|
676
|
+
|
|
677
|
+
if J > 0.0:
|
|
678
|
+
bias = bias[::-1]
|
|
679
|
+
|
|
680
|
+
# Apply time-dependent envelope: maximum differential at small t,
|
|
681
|
+
# recovers original distribution as t -> inf.
|
|
682
|
+
return _apply_time_envelope(bias / bias.sum(), t, n_bias - 1)
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
@njit(cache=True)
|
|
686
|
+
def maxcut_hamming_cdf(hamming_prob, n_qubits, J_func, degrees, quality, tot_t, h_mult, omega=1.5 * np.pi):
|
|
687
|
+
n_steps = 1 << quality
|
|
688
|
+
delta_t = tot_t / n_steps
|
|
689
|
+
n_bias = n_qubits + 1
|
|
690
|
+
|
|
691
|
+
theta = init_theta(h_mult, n_qubits, J_func, degrees)
|
|
692
|
+
|
|
693
|
+
for qc in range(n_qubits, n_steps * n_qubits):
|
|
694
|
+
step = qc // n_qubits
|
|
695
|
+
q = qc % n_qubits
|
|
696
|
+
J_eff = J_func[q]
|
|
697
|
+
if abs(J_eff) < epsilon:
|
|
698
|
+
continue
|
|
699
|
+
z = degrees[q]
|
|
700
|
+
theta_eff = theta[q]
|
|
701
|
+
t = step * delta_t
|
|
702
|
+
tm1 = (step - 1) * delta_t
|
|
703
|
+
h_t = h_mult * (tot_t - t)
|
|
704
|
+
bias = probability_by_hamming_weight(J_eff, h_t, z, theta_eff, t, n_bias, omega)
|
|
705
|
+
last_bias = probability_by_hamming_weight(J_eff, h_t, z, theta_eff, tm1, n_bias, omega)
|
|
706
|
+
hamming_prob += bias - last_bias
|
|
707
|
+
|
|
708
|
+
p_min = hamming_prob.min()
|
|
709
|
+
if p_min < 0:
|
|
710
|
+
hamming_prob -= p_min
|
|
711
|
+
hamming_prob /= hamming_prob.sum() - (hamming_prob[0] + hamming_prob[-1])
|
|
712
|
+
tot_prob = 0.0
|
|
713
|
+
n_bias -= 2
|
|
714
|
+
cum_prob = np.empty(n_bias, dtype=np.float64)
|
|
715
|
+
for i in range(n_bias):
|
|
716
|
+
tot_prob += hamming_prob[i + 1]
|
|
717
|
+
cum_prob[i] = tot_prob
|
|
718
|
+
cum_prob[-1] = 1.0
|
|
719
|
+
|
|
720
|
+
return cum_prob
|
|
721
|
+
|
|
722
|
+
|
|
723
|
+
@njit(cache=True)
|
|
724
|
+
def sample_mag(cum_prob):
|
|
725
|
+
return sample_mag_u(cum_prob, np.random.random())
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
@njit(cache=True)
|
|
729
|
+
def sample_mag_u(cum_prob, p):
|
|
730
|
+
m = 0
|
|
731
|
+
left = 0
|
|
732
|
+
right = len(cum_prob) - 1
|
|
733
|
+
while True:
|
|
734
|
+
m = (left + right) >> 1
|
|
735
|
+
|
|
736
|
+
if (cum_prob[m] >= p) and ((m == 0) or (cum_prob[m - 1] < p)):
|
|
737
|
+
break
|
|
738
|
+
|
|
739
|
+
if cum_prob[m] < p:
|
|
740
|
+
left = m + 1
|
|
741
|
+
else:
|
|
742
|
+
right = m - 1
|
|
743
|
+
|
|
744
|
+
return m
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
@njit(cache=True)
|
|
748
|
+
def bit_pick(weights, n):
|
|
749
|
+
return bit_pick_u(weights, n, np.random.rand())
|
|
750
|
+
|
|
751
|
+
|
|
752
|
+
@njit(cache=True)
|
|
753
|
+
def bit_pick_u(weights, n, u):
|
|
754
|
+
# Count available
|
|
755
|
+
p = weights.sum()
|
|
756
|
+
# Normalize & sample
|
|
757
|
+
p *= u
|
|
758
|
+
cum = 0.0
|
|
759
|
+
node = 0
|
|
760
|
+
for i in range(n):
|
|
761
|
+
cum += weights[i]
|
|
762
|
+
if p < cum:
|
|
763
|
+
node = i
|
|
764
|
+
break
|
|
765
|
+
|
|
766
|
+
return node
|
|
767
|
+
|
|
768
|
+
|
|
769
|
+
@njit(cache=True)
|
|
770
|
+
def gray_code_next(state, curr_idx, offset):
|
|
771
|
+
prev = curr_idx
|
|
772
|
+
curr = curr_idx + 1
|
|
773
|
+
prev = prev ^ (prev >> 1)
|
|
774
|
+
curr = curr ^ (curr >> 1)
|
|
775
|
+
diff = prev ^ curr
|
|
776
|
+
flip_bit = int(np.log2(diff)) + offset
|
|
777
|
+
state[flip_bit] = not state[flip_bit]
|
|
778
|
+
|
|
779
|
+
return flip_bit
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
@njit(cache=True)
|
|
783
|
+
def gray_mutation(index, seed_bits, offset):
|
|
784
|
+
"""Apply Gray-code-indexed bit flips to a seed bitstring."""
|
|
785
|
+
n = seed_bits.shape[0]
|
|
786
|
+
gray = index ^ (index >> 1)
|
|
787
|
+
bits = seed_bits.copy()
|
|
788
|
+
for i in range(n):
|
|
789
|
+
bits[n - offset - 1 - i] ^= (gray >> i) & 1
|
|
790
|
+
|
|
791
|
+
return bits
|