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.
@@ -0,0 +1,545 @@
1
+ from .maxcut_tfim import maxcut_tfim
2
+ from .local_search import local_search
3
+ from .maxcut_tfim_util import (
4
+ compute_cut,
5
+ compute_energy,
6
+ compute_cut_diff,
7
+ compute_cut_diff_2,
8
+ compute_cut_diff_between,
9
+ get_cut,
10
+ gray_code_next,
11
+ gray_mutation,
12
+ heuristic_threshold,
13
+ int_to_bitstring,
14
+ make_G_m_buf,
15
+ make_best_theta_buf,
16
+ make_best_theta_buf_64,
17
+ opencl_context,
18
+ setup_opencl,
19
+ )
20
+ import networkx as nx
21
+ import numpy as np
22
+ from numba import njit, prange
23
+ import os
24
+ import time
25
+
26
+
27
+ IS_OPENCL_AVAILABLE = True
28
+ try:
29
+ import pyopencl as cl
30
+ except ImportError:
31
+ IS_OPENCL_AVAILABLE = False
32
+
33
+
34
+ dtype = opencl_context.dtype
35
+ gnl = opencl_context.GRAY_NODE_LIMIT
36
+
37
+
38
+ def run_bit_flips_opencl(
39
+ is_double,
40
+ n,
41
+ kernel,
42
+ theta,
43
+ theta_buf,
44
+ G_m_buf,
45
+ is_segmented,
46
+ local_size,
47
+ global_size,
48
+ args_buf,
49
+ local_energy_buf,
50
+ local_index_buf,
51
+ max_energy_host,
52
+ max_index_host,
53
+ max_energy_buf,
54
+ max_index_buf,
55
+ ):
56
+ queue = opencl_context.queue
57
+
58
+ # Set kernel args
59
+ if is_segmented:
60
+ kernel.set_args(
61
+ G_m_buf[0],
62
+ G_m_buf[1],
63
+ G_m_buf[2],
64
+ G_m_buf[3],
65
+ theta_buf,
66
+ args_buf,
67
+ max_energy_buf,
68
+ max_index_buf,
69
+ local_energy_buf,
70
+ local_index_buf,
71
+ )
72
+ else:
73
+ kernel.set_args(
74
+ G_m_buf,
75
+ theta_buf,
76
+ args_buf,
77
+ max_energy_buf,
78
+ max_index_buf,
79
+ local_energy_buf,
80
+ local_index_buf,
81
+ )
82
+
83
+ cl.enqueue_nd_range_kernel(queue, kernel, (global_size,), (local_size,))
84
+
85
+ # Read results
86
+ cl.enqueue_copy(queue, max_energy_host, max_energy_buf)
87
+ queue.finish()
88
+
89
+ # Queue read for results we might not need
90
+ cl.enqueue_copy(queue, max_index_host, max_index_buf)
91
+
92
+ # Find global minimum
93
+ best_x = np.argmax(max_energy_host)
94
+ energy = max_energy_host[best_x]
95
+
96
+ if energy <= 0.0:
97
+ # No improvement: we can exit early
98
+ return 0.0, theta
99
+
100
+ # We need the best index
101
+ queue.finish()
102
+
103
+ s = max_index_host[best_x]
104
+ theta = theta.copy()
105
+
106
+ if is_double:
107
+ c = s
108
+ i = 0
109
+ lcv = n - 1
110
+ while c >= lcv:
111
+ c -= lcv
112
+ i += 1
113
+ lcv -= 1
114
+ if not lcv:
115
+ break
116
+ j = c + i + 1
117
+
118
+ theta[i] = not theta[i]
119
+ theta[j] = not theta[j]
120
+ else:
121
+ theta[s] = not theta[s]
122
+
123
+ return energy, theta
124
+
125
+
126
+ def run_gray_search_opencl(
127
+ n,
128
+ kernel,
129
+ theta,
130
+ theta_buf,
131
+ G_m_buf,
132
+ is_segmented,
133
+ local_size,
134
+ global_size,
135
+ args_buf,
136
+ max_energy_host,
137
+ max_theta_host,
138
+ max_energy_buf,
139
+ max_theta_buf,
140
+ ):
141
+ queue = opencl_context.queue
142
+
143
+ # Set kernel args
144
+ if is_segmented:
145
+ kernel.set_args(
146
+ G_m_buf[0],
147
+ G_m_buf[1],
148
+ G_m_buf[2],
149
+ G_m_buf[3],
150
+ theta_buf,
151
+ args_buf,
152
+ max_theta_buf,
153
+ max_energy_buf,
154
+ )
155
+ else:
156
+ kernel.set_args(G_m_buf, theta_buf, args_buf, max_theta_buf, max_energy_buf)
157
+
158
+ cl.enqueue_nd_range_kernel(queue, kernel, (global_size,), (local_size,))
159
+
160
+ # Read results
161
+ cl.enqueue_copy(queue, max_energy_host, max_energy_buf)
162
+ queue.finish()
163
+
164
+ # Queue read for results we might not need
165
+ cl.enqueue_copy(queue, max_theta_host, max_theta_buf)
166
+
167
+ # Find global minimum
168
+ best_x = np.argmax(max_energy_host)
169
+ energy = max_energy_host[best_x]
170
+
171
+ if energy <= 0.0:
172
+ # No improvement: we can exit early
173
+ return 0.0, theta
174
+
175
+ # We need the best index
176
+ queue.finish()
177
+
178
+ blocks = (n + 63) // 64
179
+ offset = best_x * blocks
180
+ for b in range(blocks):
181
+ s = max_theta_host[offset + b]
182
+ b_offset = b << 6
183
+ for i in range(64):
184
+ j = b_offset + i
185
+ if j >= n:
186
+ break
187
+ theta[j] = (s >> i) & 1
188
+
189
+ return energy, theta
190
+
191
+
192
+ # Belief propagation was added by (Anthropic) Claude
193
+ def belief_propagation_marginals_dense(G_m, n, bp_scale=1.0, damping=0.5):
194
+ """
195
+ Run loopy belief propagation on the dense (upper-triangular) adjacency
196
+ matrix to produce per-node marginals for warm-starting the partition.
197
+
198
+ The dense solver stores G_m as a full n×n matrix; we read only the
199
+ upper triangle (j > i) to match the sparse convention, so behaviour
200
+ is consistent across all three solver variants.
201
+
202
+ Parameters
203
+ ----------
204
+ G_m : ndarray, shape (n, n)
205
+ Dense adjacency/weight matrix. May be full or upper-triangular.
206
+ n : int
207
+ Number of nodes.
208
+ bp_scale : float
209
+ Iteration cap = int(bp_scale * n). Gives O(n * m) total work,
210
+ <= O(n^3) for any graph density. User-controlled.
211
+ damping : float
212
+ Message damping factor in [0, 1). Stabilises oscillating marginals
213
+ on dense or heavily frustrated graphs.
214
+
215
+ Returns
216
+ -------
217
+ marginals : ndarray, shape (n,)
218
+ Soft assignment in (-1, +1). Positive values favour partition 1,
219
+ negative values favour partition 0.
220
+ """
221
+ max_iterations = max(1, int(bp_scale * n))
222
+
223
+ # Collect undirected edges from upper triangle
224
+ us = []
225
+ vs = []
226
+ ws = []
227
+ for i in range(n):
228
+ for j in range(i + 1, n):
229
+ w = G_m[i, j]
230
+ if abs(w) > 1e-12:
231
+ us.append(i)
232
+ vs.append(j)
233
+ ws.append(w)
234
+
235
+ m = len(us)
236
+ if m == 0:
237
+ return np.zeros(n, dtype=np.float64)
238
+
239
+ us = np.array(us, dtype=np.int32)
240
+ vs = np.array(vs, dtype=np.int32)
241
+ ws = np.array(ws, dtype=np.float64)
242
+
243
+ # msg_fwd[k] = message from us[k] -> vs[k]
244
+ # msg_bwd[k] = message from vs[k] -> us[k]
245
+ msg_fwd = np.zeros(m, dtype=np.float64)
246
+ msg_bwd = np.zeros(m, dtype=np.float64)
247
+
248
+ # Build neighbour index: node -> list of (edge_idx, direction)
249
+ # direction=0: node is 'u' end, incoming = msg_bwd[k]
250
+ # direction=1: node is 'v' end, incoming = msg_fwd[k]
251
+ node_edges = [[] for _ in range(n)]
252
+ for k in range(m):
253
+ node_edges[us[k]].append((k, 0))
254
+ node_edges[vs[k]].append((k, 1))
255
+
256
+ for _ in range(max_iterations):
257
+ new_fwd = np.empty(m, dtype=np.float64)
258
+ new_bwd = np.empty(m, dtype=np.float64)
259
+
260
+ for k in range(m):
261
+ u = us[k]
262
+ v = vs[k]
263
+ w = ws[k]
264
+
265
+ # Message u -> v: aggregate incoming to u excluding v
266
+ h_u = 0.0
267
+ for (ek, direction) in node_edges[u]:
268
+ if ek == k:
269
+ continue
270
+ h_u += msg_bwd[ek] if direction == 0 else msg_fwd[ek]
271
+
272
+ tanh_w = np.tanh(w)
273
+ product = tanh_w * np.tanh(h_u)
274
+ product = np.clip(product, -1.0 + 1e-9, 1.0 - 1e-9)
275
+ new_fwd[k] = damping * msg_fwd[k] + (1.0 - damping) * np.arctanh(product)
276
+
277
+ # Message v -> u: aggregate incoming to v excluding u
278
+ h_v = 0.0
279
+ for (ek, direction) in node_edges[v]:
280
+ if ek == k:
281
+ continue
282
+ h_v += msg_bwd[ek] if direction == 0 else msg_fwd[ek]
283
+
284
+ product_v = tanh_w * np.tanh(h_v)
285
+ product_v = np.clip(product_v, -1.0 + 1e-9, 1.0 - 1e-9)
286
+ new_bwd[k] = damping * msg_bwd[k] + (1.0 - damping) * np.arctanh(product_v)
287
+
288
+ msg_fwd = new_fwd
289
+ msg_bwd = new_bwd
290
+
291
+ # Marginals: sum all incoming messages per node
292
+ marginals = np.zeros(n, dtype=np.float64)
293
+ for k in range(m):
294
+ marginals[us[k]] += msg_bwd[k]
295
+ marginals[vs[k]] += msg_fwd[k]
296
+
297
+ return np.tanh(marginals)
298
+
299
+
300
+ def bp_warm_start_dense(G_m, n, bp_scale=1.0, damping=0.5):
301
+ """Partition bitstring from BP marginals over the dense adjacency matrix."""
302
+ marginals = belief_propagation_marginals_dense(G_m, n, bp_scale, damping)
303
+ return marginals > 0.0
304
+
305
+
306
+ def spin_glass_solver(
307
+ G,
308
+ quality=None,
309
+ shots=None,
310
+ best_guess=None,
311
+ is_maxcut_gpu=True,
312
+ is_spin_glass=True,
313
+ anneal_t=None,
314
+ anneal_h=None,
315
+ repulsion_base=None,
316
+ is_log=False,
317
+ gray_iterations=None,
318
+ gray_seed_multiple=None,
319
+ bp_scale=None,
320
+ bp_damping=0.5,
321
+ seed=None,
322
+ time_limit=None,
323
+ ):
324
+ """
325
+ Dense spin glass / MaxCut solver with optional belief propagation warm-start.
326
+
327
+ Parameters
328
+ ----------
329
+ seed : int or None
330
+ Makes the sampling stage reproducible (see maxcut_tfim). The local
331
+ search is deterministic.
332
+ time_limit : float or None
333
+ Seconds for the whole solve. Sampling and then local search stop at
334
+ the deadline (between steps) and return the best state found so far.
335
+ bp_scale : float or None
336
+ Controls BP iteration count as int(bp_scale * n_qubits).
337
+ Default None disables BP. Set to 1.0 to enable with O(n*m) cost
338
+ (<=O(n^3) for any graph density). Increase for more BP iterations
339
+ at proportionally higher cost.
340
+ bp_damping : float
341
+ Message damping in [0, 1). Default 0.5. Higher values help
342
+ convergence on dense or heavily frustrated graphs.
343
+ """
344
+ dtype = opencl_context.dtype
345
+ deadline = float("inf") if time_limit is None else time.perf_counter() + time_limit
346
+ remaining = lambda: None if time_limit is None else max(0.0, deadline - time.perf_counter())
347
+ nodes = None
348
+ n_qubits = 0
349
+ G_m = None
350
+ if isinstance(G, nx.Graph):
351
+ nodes = list(G.nodes())
352
+ n_qubits = len(nodes)
353
+ G_m = nx.to_numpy_array(G, weight="weight", nonedge=0.0, dtype=dtype)
354
+ else:
355
+ n_qubits = len(G)
356
+ nodes = list(range(n_qubits))
357
+ G_m = G
358
+
359
+ if n_qubits < 3:
360
+ if n_qubits == 0:
361
+ return "", 0, ([], []), 0
362
+
363
+ if n_qubits == 1:
364
+ return "0", 0, (nodes, []), 0
365
+
366
+ if n_qubits == 2:
367
+ weight = G_m[0, 1]
368
+ if weight < 0.0:
369
+ return "00", 0, (nodes, []), weight
370
+
371
+ return "01", weight, ([nodes[0]], [nodes[1]]), -weight
372
+
373
+ if n_qubits < heuristic_threshold:
374
+ best_guess = None
375
+
376
+ bitstring = ""
377
+ cut_value = None
378
+ if isinstance(best_guess, str):
379
+ bitstring = best_guess
380
+ elif isinstance(best_guess, int):
381
+ bitstring = int_to_bitstring(best_guess, n_qubits)
382
+ elif isinstance(best_guess, list):
383
+ bitstring = "".join(["1" if b else "0" for b in best_guess])
384
+ else:
385
+ # BP warm-start: run before the sampling heuristic if bp_scale is set,
386
+ # so that the cascade local search begins from a sign-aware partition
387
+ # rather than the TFIM prior alone.
388
+ if bp_scale is not None and n_qubits >= heuristic_threshold:
389
+ bp_theta = bp_warm_start_dense(G_m, n_qubits, bp_scale, bp_damping)
390
+ bitstring, cut_value, _ = maxcut_tfim(
391
+ G_m,
392
+ quality=quality,
393
+ shots=shots,
394
+ is_spin_glass=is_spin_glass,
395
+ anneal_t=anneal_t,
396
+ anneal_h=anneal_h,
397
+ repulsion_base=repulsion_base,
398
+ is_maxcut_gpu=is_maxcut_gpu,
399
+ is_nested=True,
400
+ seed=seed,
401
+ time_limit=remaining(),
402
+ )
403
+ # Keep whichever of BP or sampling gave the better cut
404
+ bp_energy = (
405
+ compute_energy(bp_theta, G_m, n_qubits)
406
+ if is_spin_glass
407
+ else compute_cut(bp_theta, G_m, n_qubits)
408
+ )
409
+ sample_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
410
+ sample_energy = (
411
+ compute_energy(sample_theta, G_m, n_qubits)
412
+ if is_spin_glass
413
+ else compute_cut(sample_theta, G_m, n_qubits)
414
+ )
415
+ if bp_energy > sample_energy:
416
+ bitstring = "".join(["1" if b else "0" for b in bp_theta])
417
+ cut_value = bp_energy if not is_spin_glass else None
418
+ else:
419
+ bitstring, cut_value, _ = maxcut_tfim(
420
+ G_m,
421
+ quality=quality,
422
+ shots=shots,
423
+ is_spin_glass=is_spin_glass,
424
+ anneal_t=anneal_t,
425
+ anneal_h=anneal_h,
426
+ repulsion_base=repulsion_base,
427
+ is_maxcut_gpu=is_maxcut_gpu,
428
+ is_nested=True,
429
+ seed=seed,
430
+ time_limit=remaining(),
431
+ )
432
+
433
+ best_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
434
+ if is_spin_glass:
435
+ max_energy = compute_energy(best_theta, G_m, n_qubits)
436
+ elif cut_value is None:
437
+ max_energy = compute_cut(best_theta, G_m, n_qubits)
438
+ else:
439
+ max_energy = cut_value
440
+
441
+ if n_qubits < heuristic_threshold:
442
+ bitstring, l, r = get_cut(best_theta, nodes, n_qubits)
443
+ if is_spin_glass:
444
+ cut_value = compute_cut(best_theta, G_m, n_qubits)
445
+ min_energy = -max_energy
446
+ else:
447
+ cut_value = max_energy
448
+ min_energy = compute_energy(best_theta, G_m, n_qubits)
449
+
450
+ return bitstring, float(cut_value), (l, r), float(min_energy)
451
+
452
+ if gray_iterations is None:
453
+ gray_iterations = n_qubits * n_qubits
454
+
455
+ if gray_seed_multiple is None:
456
+ gray_seed_multiple = max(2, os.cpu_count())
457
+
458
+ is_opencl = is_maxcut_gpu and opencl_context.IS_OPENCL_AVAILABLE
459
+
460
+ if is_opencl:
461
+ segment_size = (G_m.shape[0] * G_m.shape[1] + 3) >> 2
462
+ is_segmented = (G_m.nbytes << 1) > opencl_context.max_alloc
463
+ G_m_buf = make_G_m_buf(G_m, is_segmented, segment_size)
464
+
465
+ local_work_group_size = min(opencl_context.work_group_size, n_qubits)
466
+ global_work_group_size = n_qubits
467
+ opencl_args = setup_opencl(
468
+ local_work_group_size,
469
+ global_work_group_size,
470
+ np.array([n_qubits, is_spin_glass, segment_size], dtype=np.int32), # kernels read __constant int*
471
+ )
472
+
473
+ if is_segmented:
474
+ single_bit_flips_kernel = opencl_context.single_bit_flips_segmented_kernel
475
+ double_bit_flips_kernel = opencl_context.double_bit_flips_segmented_kernel
476
+ gray_kernel = opencl_context.gray_segmented_kernel
477
+ else:
478
+ single_bit_flips_kernel = opencl_context.single_bit_flips_kernel
479
+ double_bit_flips_kernel = opencl_context.double_bit_flips_kernel
480
+ gray_kernel = opencl_context.gray_kernel
481
+
482
+ if n_qubits <= gnl:
483
+ gray_work_group_size = opencl_context.MAX_GPU_PROC_ELEM
484
+ gray_args = setup_opencl(
485
+ 1,
486
+ gray_work_group_size,
487
+ np.array(
488
+ [
489
+ n_qubits,
490
+ is_spin_glass,
491
+ (gray_iterations + gray_work_group_size - 1) // gray_work_group_size,
492
+ segment_size,
493
+ ],
494
+ dtype=np.int32, # kernels read __constant int*
495
+ ),
496
+ True,
497
+ )
498
+ gray_kernel = opencl_context.gray_segmented_kernel if is_segmented else opencl_context.gray_kernel
499
+
500
+ gpu_single = gpu_double = gpu_gray = None
501
+ if is_opencl:
502
+ theta_cache = {}
503
+
504
+ def theta_buf_for(theta):
505
+ if ("theta" not in theta_cache) or not np.array_equal(theta_cache["theta"], theta):
506
+ theta_cache["theta"] = theta.copy()
507
+ theta_cache["buf"] = make_best_theta_buf(theta)
508
+ return theta_cache["buf"]
509
+
510
+ def gpu_single(theta):
511
+ return run_bit_flips_opencl(
512
+ False, n_qubits, single_bit_flips_kernel, theta, theta_buf_for(theta), G_m_buf, is_segmented, *opencl_args
513
+ )
514
+
515
+ def gpu_double(theta):
516
+ return run_bit_flips_opencl(
517
+ True, n_qubits, double_bit_flips_kernel, theta, theta_buf_for(theta), G_m_buf, is_segmented, *opencl_args
518
+ )
519
+
520
+ if n_qubits <= gnl:
521
+
522
+ def gpu_gray(theta):
523
+ return run_gray_search_opencl(
524
+ n_qubits, gray_kernel, theta, make_best_theta_buf_64(theta), G_m_buf, is_segmented, *gray_args
525
+ )
526
+
527
+ best_theta = local_search(
528
+ best_theta,
529
+ is_spin_glass,
530
+ (G_m, None, None, None, None, None),
531
+ gray_iterations,
532
+ gray_seed_multiple,
533
+ deadline,
534
+ gpu_single,
535
+ gpu_double,
536
+ gpu_gray,
537
+ )
538
+
539
+ bitstring, l, r = get_cut(best_theta, nodes, n_qubits)
540
+ # Report values recomputed from the returned bits.
541
+ cut_value = compute_cut(best_theta, G_m, n_qubits)
542
+ energy = compute_energy(best_theta, G_m, n_qubits)
543
+ min_energy = -energy if is_spin_glass else energy
544
+
545
+ return bitstring, float(cut_value), (l, r), float(min_energy)
@@ -0,0 +1,53 @@
1
+ from .maxcut_tfim import maxcut_tfim
2
+ from .spin_glass_solver_sparse import spin_glass_solver_sparse
3
+
4
+ import networkx as nx
5
+
6
+
7
+ def spin_glass_solver_hybrid(
8
+ G,
9
+ quality=None,
10
+ shots=None,
11
+ is_maxcut_gpu=True,
12
+ is_spin_glass=True,
13
+ anneal_t=None,
14
+ anneal_h=None,
15
+ repulsion_base=None,
16
+ is_log=False,
17
+ gray_iterations=None,
18
+ gray_seed_multiple=None,
19
+ bp_scale=None,
20
+ bp_damping=0.5,
21
+ seed=None,
22
+ time_limit=None,
23
+ ):
24
+ import time
25
+ deadline = None if time_limit is None else time.perf_counter() + time_limit
26
+ if not isinstance(G, nx.Graph):
27
+ raise TypeError("G graph must be a networkx.Graph for maxcut_hybrid!")
28
+
29
+ guess, _, _ = maxcut_tfim(
30
+ G,
31
+ quality=quality,
32
+ shots=shots,
33
+ repulsion_base=repulsion_base,
34
+ is_maxcut_gpu=is_maxcut_gpu,
35
+ is_spin_glass=is_spin_glass,
36
+ anneal_t=anneal_t,
37
+ anneal_h=anneal_h,
38
+ seed=seed,
39
+ time_limit=time_limit,
40
+ )
41
+
42
+ return spin_glass_solver_sparse(
43
+ G,
44
+ best_guess=guess,
45
+ is_maxcut_gpu=is_maxcut_gpu,
46
+ is_spin_glass=is_spin_glass,
47
+ is_log=is_log,
48
+ gray_iterations=gray_iterations,
49
+ gray_seed_multiple=gray_seed_multiple,
50
+ bp_scale=bp_scale,
51
+ bp_damping=bp_damping,
52
+ time_limit=None if deadline is None else max(0.0, deadline - time.perf_counter()),
53
+ )