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,611 @@
1
+ from .maxcut_tfim_sparse import maxcut_tfim_sparse
2
+ from .maxcut_tfim_util import (
3
+ compute_cut_sparse,
4
+ compute_energy_sparse,
5
+ get_cut,
6
+ gray_code_next,
7
+ gray_mutation,
8
+ heuristic_threshold_sparse,
9
+ int_to_bitstring,
10
+ make_G_m_csr_buf,
11
+ make_best_theta_buf,
12
+ make_best_theta_buf_64,
13
+ opencl_context,
14
+ setup_opencl,
15
+ to_scipy_sparse_upper_triangular,
16
+ as_upper_csr,
17
+ symmetric_csr,
18
+ )
19
+ from .local_search import local_search
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
+ best_energy,
43
+ theta,
44
+ theta_buf,
45
+ G_data_buf,
46
+ G_rows_buf,
47
+ G_cols_buf,
48
+ is_segmented,
49
+ local_size,
50
+ global_size,
51
+ args_buf,
52
+ local_energy_buf,
53
+ local_index_buf,
54
+ max_energy_host,
55
+ max_index_host,
56
+ max_energy_buf,
57
+ max_index_buf,
58
+ ):
59
+ queue = opencl_context.queue
60
+
61
+ # Set kernel args
62
+ if is_segmented:
63
+ kernel.set_args(
64
+ G_data_buf[0],
65
+ G_data_buf[1],
66
+ G_data_buf[2],
67
+ G_data_buf[3],
68
+ G_rows_buf,
69
+ G_cols_buf,
70
+ theta_buf,
71
+ args_buf,
72
+ max_energy_buf,
73
+ max_index_buf,
74
+ local_energy_buf,
75
+ local_index_buf,
76
+ )
77
+ else:
78
+ kernel.set_args(
79
+ G_data_buf,
80
+ G_rows_buf,
81
+ G_cols_buf,
82
+ theta_buf,
83
+ args_buf,
84
+ max_energy_buf,
85
+ max_index_buf,
86
+ local_energy_buf,
87
+ local_index_buf,
88
+ )
89
+
90
+ cl.enqueue_nd_range_kernel(queue, kernel, (global_size,), (local_size,))
91
+
92
+ # Read results
93
+ cl.enqueue_copy(queue, max_energy_host, max_energy_buf)
94
+ queue.finish()
95
+
96
+ # Queue read for results we might not need
97
+ cl.enqueue_copy(queue, max_index_host, max_index_buf)
98
+
99
+ # Find global minimum
100
+ best_x = np.argmax(max_energy_host)
101
+ energy = max_energy_host[best_x]
102
+
103
+ if energy <= best_energy:
104
+ # No improvement: we can exit early
105
+ return best_energy, theta
106
+
107
+ # We need the best index
108
+ queue.finish()
109
+
110
+ s = max_index_host[best_x]
111
+ theta = theta.copy()
112
+
113
+ if is_double:
114
+ c = s
115
+ i = 0
116
+ lcv = n - 1
117
+ while c >= lcv:
118
+ c -= lcv
119
+ i += 1
120
+ lcv -= 1
121
+ if not lcv:
122
+ break
123
+ j = c + i + 1
124
+
125
+ theta[i] = not theta[i]
126
+ theta[j] = not theta[j]
127
+ else:
128
+ theta[s] = not theta[s]
129
+
130
+ return energy, theta
131
+
132
+
133
+ def run_gray_search_opencl(
134
+ n,
135
+ kernel,
136
+ best_energy,
137
+ theta,
138
+ theta_buf,
139
+ G_data_buf,
140
+ G_rows_buf,
141
+ G_cols_buf,
142
+ is_segmented,
143
+ local_size,
144
+ global_size,
145
+ args_buf,
146
+ max_energy_host,
147
+ max_theta_host,
148
+ max_energy_buf,
149
+ max_theta_buf,
150
+ ):
151
+ queue = opencl_context.queue
152
+
153
+ # Set kernel args
154
+ if is_segmented:
155
+ kernel.set_args(
156
+ G_data_buf[0],
157
+ G_data_buf[1],
158
+ G_data_buf[2],
159
+ G_data_buf[3],
160
+ G_rows_buf,
161
+ G_cols_buf,
162
+ theta_buf,
163
+ args_buf,
164
+ max_theta_buf,
165
+ max_energy_buf,
166
+ )
167
+ else:
168
+ kernel.set_args(G_data_buf, G_rows_buf, G_cols_buf, theta_buf, args_buf, max_theta_buf, max_energy_buf)
169
+
170
+ cl.enqueue_nd_range_kernel(queue, kernel, (global_size,), (local_size,))
171
+
172
+ # Read results
173
+ cl.enqueue_copy(queue, max_energy_host, max_energy_buf)
174
+ queue.finish()
175
+
176
+ # Queue read for results we might not need
177
+ cl.enqueue_copy(queue, max_theta_host, max_theta_buf)
178
+
179
+ # Find global minimum
180
+ best_x = np.argmax(max_energy_host)
181
+ energy = max_energy_host[best_x]
182
+
183
+ if energy <= best_energy:
184
+ # No improvement: we can exit early
185
+ return best_energy, theta
186
+
187
+ # We need the best index
188
+ queue.finish()
189
+
190
+ blocks = (n + 63) // 64
191
+ offset = best_x * blocks
192
+ for b in range(blocks):
193
+ s = max_theta_host[offset + b]
194
+ b_offset = b << 6
195
+ for i in range(64):
196
+ j = b_offset + i
197
+ if j >= n:
198
+ break
199
+ theta[j] = (s >> i) & 1
200
+
201
+ return energy, theta
202
+
203
+
204
+ # Belief propagation was added by (Anthropic) Claude
205
+ def belief_propagation_marginals(G_data, G_rows, G_cols, n, bp_scale=1.0, damping=0.5):
206
+ """
207
+ Run loopy belief propagation on the signed graph to produce per-node
208
+ marginals suitable for biasing the initial partition assignment.
209
+
210
+ Messages are defined on directed edges (i->j) in the MaxCut factor graph.
211
+ Since the CSR matrix is upper-triangular, we iterate over stored edges and
212
+ maintain both directions explicitly.
213
+
214
+ Parameters
215
+ ----------
216
+ G_data : ndarray
217
+ Edge weights from upper-triangular CSR.
218
+ G_rows : ndarray
219
+ CSR row pointers.
220
+ G_cols : ndarray
221
+ CSR column indices.
222
+ n : int
223
+ Number of nodes.
224
+ bp_scale : float
225
+ Iteration cap = int(bp_scale * n). Default 1.0 keeps total work
226
+ O(n * m), which is <= O(n^3) for any graph density. User-controlled.
227
+ damping : float
228
+ Message damping factor in [0, 1). Higher values slow convergence
229
+ but stabilise oscillating marginals on dense frustrated graphs.
230
+
231
+ Returns
232
+ -------
233
+ marginals : ndarray, shape (n,)
234
+ Soft assignment in (-1, +1). Positive values favour partition 1,
235
+ negative values favour partition 0.
236
+ """
237
+ max_iterations = max(1, int(bp_scale * n))
238
+
239
+ # Messages: msg[i, j] = current message from i to j.
240
+ # We store all directed edges as two dicts indexed by (src, dst).
241
+ # For memory efficiency on sparse graphs we use flat arrays parallel
242
+ # to the CSR structure, holding both directions.
243
+
244
+ # Number of undirected edges
245
+ m = G_data.shape[0]
246
+
247
+ # For each undirected edge k: (u, v) with u < v (upper triangular)
248
+ # we store two directed messages: fwd[k] = msg u->v, bwd[k] = msg v->u
249
+ msg_fwd = np.zeros(m, dtype=np.float64) # u -> v
250
+ msg_bwd = np.zeros(m, dtype=np.float64) # v -> u
251
+
252
+ # Build a reverse index: for each node, list of (edge_idx, direction)
253
+ # direction=0 means node is the 'u' end (row), direction=1 means 'v' end (col)
254
+ node_edges = [[] for _ in range(n)]
255
+ edge_u = np.empty(m, dtype=np.int32)
256
+ edge_v = np.empty(m, dtype=np.int32)
257
+
258
+ k = 0
259
+ for u in range(n):
260
+ for ptr in range(G_rows[u], G_rows[u + 1]):
261
+ v = G_cols[ptr]
262
+ edge_u[k] = u
263
+ edge_v[k] = v
264
+ node_edges[u].append((k, 0)) # u is src of fwd message
265
+ node_edges[v].append((k, 1)) # v is src of bwd message
266
+ k += 1
267
+
268
+ for _ in range(max_iterations):
269
+ new_fwd = np.empty(m, dtype=np.float64)
270
+ new_bwd = np.empty(m, dtype=np.float64)
271
+
272
+ for k in range(m):
273
+ u = edge_u[k]
274
+ v = edge_v[k]
275
+ w = G_data[k]
276
+
277
+ # Message u -> v: sum of incoming messages to u from all
278
+ # neighbours except v, passed through the edge factor.
279
+ # For MaxCut, the factor encourages u and v to differ;
280
+ # for negative edges it encourages them to agree.
281
+ # The update rule: new_msg(u->v) = atanh(tanh(w) * tanh(sum_excl))
282
+ # where sum_excl is the sum of all incoming messages to u except
283
+ # the one from v.
284
+ h_u = 0.0
285
+ for (ek, direction) in node_edges[u]:
286
+ if ek == k:
287
+ continue # exclude the v->u message
288
+ if direction == 0:
289
+ # u is the fwd src on edge ek, so incoming to u is bwd[ek]
290
+ h_u += msg_bwd[ek]
291
+ else:
292
+ # u is the bwd src on edge ek, so incoming to u is fwd[ek]
293
+ h_u += msg_fwd[ek]
294
+
295
+ tanh_w = np.tanh(w)
296
+ tanh_h = np.tanh(h_u)
297
+ product = tanh_w * tanh_h
298
+ # Clamp to avoid atanh singularity
299
+ product = np.clip(product, -1.0 + 1e-9, 1.0 - 1e-9)
300
+ raw_fwd = np.arctanh(product)
301
+ new_fwd[k] = damping * msg_fwd[k] + (1.0 - damping) * raw_fwd
302
+
303
+ # Message v -> u (symmetric, swap roles)
304
+ h_v = 0.0
305
+ for (ek, direction) in node_edges[v]:
306
+ if ek == k:
307
+ continue # exclude the u->v message
308
+ if direction == 0:
309
+ h_v += msg_bwd[ek]
310
+ else:
311
+ h_v += msg_fwd[ek]
312
+
313
+ tanh_h_v = np.tanh(h_v)
314
+ product_v = tanh_w * tanh_h_v
315
+ product_v = np.clip(product_v, -1.0 + 1e-9, 1.0 - 1e-9)
316
+ raw_bwd = np.arctanh(product_v)
317
+ new_bwd[k] = damping * msg_bwd[k] + (1.0 - damping) * raw_bwd
318
+
319
+ msg_fwd = new_fwd
320
+ msg_bwd = new_bwd
321
+
322
+ # Compute marginals: for each node, sum all incoming messages
323
+ marginals = np.zeros(n, dtype=np.float64)
324
+ for k in range(m):
325
+ u = edge_u[k]
326
+ v = edge_v[k]
327
+ marginals[u] += msg_bwd[k] # incoming to u from v
328
+ marginals[v] += msg_fwd[k] # incoming to v from u
329
+
330
+ return np.tanh(marginals)
331
+
332
+
333
+ def bp_warm_start(G_data, G_rows, G_cols, n, bp_scale=1.0, damping=0.5):
334
+ """
335
+ Produce an initial partition bitstring from BP marginals.
336
+ Nodes with positive marginal go to partition 1, negative to partition 0.
337
+ Falls back to all-zeros (trivial) if BP produces a degenerate result.
338
+ """
339
+ marginals = belief_propagation_marginals(G_data, G_rows, G_cols, n, bp_scale, damping)
340
+ theta = marginals > 0.0
341
+ return theta
342
+
343
+
344
+ def spin_glass_solver_sparse(
345
+ G,
346
+ quality=None,
347
+ shots=None,
348
+ best_guess=None,
349
+ is_maxcut_gpu=True,
350
+ is_spin_glass=True,
351
+ anneal_t=None,
352
+ anneal_h=None,
353
+ repulsion_base=None,
354
+ is_log=False,
355
+ gray_iterations=None,
356
+ gray_seed_multiple=None,
357
+ bp_scale=None,
358
+ bp_damping=0.5,
359
+ seed=None,
360
+ time_limit=None,
361
+ ):
362
+ """
363
+ Spin glass / MaxCut solver with optional belief propagation warm-start.
364
+
365
+ Parameters
366
+ ----------
367
+ seed, time_limit : as for spin_glass_solver.
368
+ A scipy input matrix is read as its strict upper triangle (a full
369
+ symmetric matrix gives the same graph).
370
+ bp_scale : float or None
371
+ Controls BP iteration count as int(bp_scale * n_qubits).
372
+ Default None disables BP. Set to 1.0 to enable with O(n*m) cost
373
+ (<=O(n^3) for any graph density). Increase for more BP iterations
374
+ at proportionally higher cost.
375
+ bp_damping : float
376
+ Message damping in [0, 1). Default 0.5. Higher values help
377
+ convergence on dense or heavily frustrated graphs.
378
+ """
379
+ dtype = opencl_context.dtype
380
+ deadline = float("inf") if time_limit is None else time.perf_counter() + time_limit
381
+ remaining = lambda: None if time_limit is None else max(0.0, deadline - time.perf_counter())
382
+ nodes = None
383
+ n_qubits = 0
384
+ G_m = None
385
+ if isinstance(G, nx.Graph):
386
+ nodes = list(G.nodes())
387
+ n_qubits = len(nodes)
388
+ G_m = to_scipy_sparse_upper_triangular(G, nodes, n_qubits)
389
+ else:
390
+ n_qubits = G.shape[0]
391
+ nodes = list(range(n_qubits))
392
+ G_m = as_upper_csr(G)
393
+
394
+ if n_qubits < 3:
395
+ if n_qubits == 0:
396
+ return "", 0, ([], []), 0
397
+
398
+ if n_qubits == 1:
399
+ return "0", 0, (nodes, []), 0
400
+
401
+ if n_qubits == 2:
402
+ weight = G_m[0, 1]
403
+ if weight < 0.0:
404
+ return "00", 0, (nodes, []), weight
405
+
406
+ return "01", weight, ([nodes[0]], [nodes[1]]), -weight
407
+
408
+ if n_qubits < heuristic_threshold_sparse:
409
+ best_guess = None
410
+
411
+ bitstring = ""
412
+ cut_value = None
413
+ if isinstance(best_guess, str):
414
+ bitstring = best_guess
415
+ elif isinstance(best_guess, int):
416
+ bitstring = int_to_bitstring(best_guess, n_qubits)
417
+ elif isinstance(best_guess, list):
418
+ bitstring = "".join(["1" if b else "0" for b in best_guess])
419
+ else:
420
+ # BP warm-start: run before the sampling heuristic if bp_scale is set,
421
+ # so that the cascade local search begins from a sign-aware partition
422
+ # rather than the TFIM prior alone.
423
+ if bp_scale is not None and n_qubits >= heuristic_threshold_sparse:
424
+ bp_theta = bp_warm_start(
425
+ G_m.data, G_m.indptr, G_m.indices, n_qubits, bp_scale, bp_damping
426
+ )
427
+ bp_bitstring = "".join(["1" if b else "0" for b in bp_theta])
428
+ # Pass BP result as best_guess into maxcut_tfim_sparse so the
429
+ # sampling heuristic can compete against it or build on it.
430
+ bitstring, cut_value, _ = maxcut_tfim_sparse(
431
+ G_m,
432
+ quality=quality,
433
+ shots=shots,
434
+ is_spin_glass=is_spin_glass,
435
+ anneal_t=anneal_t,
436
+ anneal_h=anneal_h,
437
+ repulsion_base=repulsion_base,
438
+ is_maxcut_gpu=is_maxcut_gpu,
439
+ is_nested=True,
440
+ seed=seed,
441
+ time_limit=remaining(),
442
+ )
443
+ # Keep whichever of BP or sampling gave the better cut
444
+ bp_energy = (
445
+ compute_energy_sparse(bp_theta, G_m.data, G_m.indptr, G_m.indices, n_qubits)
446
+ if is_spin_glass
447
+ else compute_cut_sparse(bp_theta, G_m.data, G_m.indptr, G_m.indices, n_qubits)
448
+ )
449
+ sample_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
450
+ sample_energy = (
451
+ compute_energy_sparse(sample_theta, G_m.data, G_m.indptr, G_m.indices, n_qubits)
452
+ if is_spin_glass
453
+ else compute_cut_sparse(sample_theta, G_m.data, G_m.indptr, G_m.indices, n_qubits)
454
+ )
455
+ if bp_energy > sample_energy:
456
+ bitstring = bp_bitstring
457
+ cut_value = bp_energy if not is_spin_glass else None
458
+ else:
459
+ bitstring, cut_value, _ = maxcut_tfim_sparse(
460
+ G_m,
461
+ quality=quality,
462
+ shots=shots,
463
+ is_spin_glass=is_spin_glass,
464
+ anneal_t=anneal_t,
465
+ anneal_h=anneal_h,
466
+ repulsion_base=repulsion_base,
467
+ is_maxcut_gpu=is_maxcut_gpu,
468
+ is_nested=True,
469
+ seed=seed,
470
+ time_limit=remaining(),
471
+ )
472
+
473
+ best_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
474
+ if is_spin_glass:
475
+ max_energy = compute_energy_sparse(best_theta, G_m.data, G_m.indptr, G_m.indices, n_qubits)
476
+ elif cut_value is None:
477
+ max_energy = compute_cut_sparse(best_theta, G_m.data, G_m.indptr, G_m.indices, n_qubits)
478
+ else:
479
+ max_energy = cut_value
480
+
481
+ if n_qubits < heuristic_threshold_sparse:
482
+ bitstring, l, r = get_cut(best_theta, nodes, n_qubits)
483
+ if is_spin_glass:
484
+ cut_value = compute_cut_sparse(best_theta, G_m.data, G_m.indptr, G_m.indices, n_qubits)
485
+ min_energy = -max_energy
486
+ else:
487
+ cut_value = max_energy
488
+ min_energy = compute_energy_sparse(best_theta, G_m.data, G_m.indptr, G_m.indices, n_qubits)
489
+
490
+ return bitstring, float(cut_value), (l, r), float(min_energy)
491
+
492
+ if gray_iterations is None:
493
+ gray_iterations = n_qubits * n_qubits
494
+
495
+ if gray_seed_multiple is None:
496
+ gray_seed_multiple = max(2, os.cpu_count())
497
+
498
+ is_opencl = is_maxcut_gpu and opencl_context.IS_OPENCL_AVAILABLE
499
+
500
+ if is_opencl:
501
+ segment_size = (G_m.data.shape[0] + 3) >> 2
502
+ is_segmented = (G_m.data.nbytes << 1) > opencl_context.max_alloc
503
+ G_data_buf, G_rows_buf, G_cols_buf = make_G_m_csr_buf(G_m, is_segmented, segment_size)
504
+
505
+ local_work_group_size = min(opencl_context.work_group_size, n_qubits)
506
+ global_work_group_size = n_qubits
507
+ opencl_args = setup_opencl(
508
+ local_work_group_size,
509
+ global_work_group_size,
510
+ np.array([n_qubits, is_spin_glass, segment_size], dtype=np.int32), # kernels read __constant int*
511
+ )
512
+
513
+ if is_segmented:
514
+ single_bit_flips_kernel = opencl_context.single_bit_flips_sparse_segmented_kernel
515
+ double_bit_flips_kernel = opencl_context.double_bit_flips_sparse_segmented_kernel
516
+ else:
517
+ single_bit_flips_kernel = opencl_context.single_bit_flips_sparse_kernel
518
+ double_bit_flips_kernel = opencl_context.double_bit_flips_sparse_kernel
519
+
520
+ if n_qubits <= gnl:
521
+ gray_work_group_size = opencl_context.MAX_GPU_PROC_ELEM
522
+ gray_args = setup_opencl(
523
+ 1,
524
+ gray_work_group_size,
525
+ np.array(
526
+ [
527
+ n_qubits,
528
+ is_spin_glass,
529
+ (gray_iterations + gray_work_group_size - 1) // gray_work_group_size,
530
+ segment_size,
531
+ ],
532
+ dtype=np.int32, # kernels read __constant int*
533
+ ),
534
+ True,
535
+ )
536
+ gray_kernel = opencl_context.gray_sparse_segmented_kernel if is_segmented else opencl_context.gray_sparse_kernel
537
+
538
+ def value_of(theta):
539
+ if is_spin_glass:
540
+ return compute_energy_sparse(theta, G_m.data, G_m.indptr, G_m.indices, n_qubits)
541
+ return compute_cut_sparse(theta, G_m.data, G_m.indptr, G_m.indices, n_qubits)
542
+
543
+ gpu_single = gpu_double = gpu_gray = None
544
+ if is_opencl:
545
+ # The sparse kernels report absolute values; the shared driver works in gains.
546
+ theta_cache = {}
547
+
548
+ def theta_buf_for(theta):
549
+ if ("theta" not in theta_cache) or not np.array_equal(theta_cache["theta"], theta):
550
+ theta_cache["theta"] = theta.copy()
551
+ theta_cache["buf"] = make_best_theta_buf(theta)
552
+ return theta_cache["buf"]
553
+
554
+ def gpu_flips(is_double, kernel, theta):
555
+ base_value = value_of(theta)
556
+ energy, state = run_bit_flips_opencl(
557
+ is_double,
558
+ n_qubits,
559
+ kernel,
560
+ base_value,
561
+ theta,
562
+ theta_buf_for(theta),
563
+ G_data_buf,
564
+ G_rows_buf,
565
+ G_cols_buf,
566
+ is_segmented,
567
+ *opencl_args,
568
+ )
569
+ return energy - base_value, state
570
+
571
+ gpu_single = lambda theta: gpu_flips(False, single_bit_flips_kernel, theta)
572
+ gpu_double = lambda theta: gpu_flips(True, double_bit_flips_kernel, theta)
573
+
574
+ if n_qubits <= gnl:
575
+
576
+ def gpu_gray(theta):
577
+ base_value = value_of(theta)
578
+ energy, state = run_gray_search_opencl(
579
+ n_qubits,
580
+ gray_kernel,
581
+ base_value,
582
+ theta,
583
+ make_best_theta_buf_64(theta),
584
+ G_data_buf,
585
+ G_rows_buf,
586
+ G_cols_buf,
587
+ is_segmented,
588
+ *gray_args,
589
+ )
590
+ return energy - base_value, state
591
+
592
+ S = symmetric_csr(G_m)
593
+ best_theta = local_search(
594
+ best_theta,
595
+ is_spin_glass,
596
+ (None, S.data, S.indptr, S.indices, None, None),
597
+ gray_iterations,
598
+ gray_seed_multiple,
599
+ deadline,
600
+ gpu_single,
601
+ gpu_double,
602
+ gpu_gray,
603
+ )
604
+
605
+ bitstring, l, r = get_cut(best_theta, nodes, n_qubits)
606
+ # Report values recomputed from the returned bits.
607
+ cut_value = compute_cut_sparse(best_theta, G_m.data, G_m.indptr, G_m.indices, n_qubits)
608
+ energy = compute_energy_sparse(best_theta, G_m.data, G_m.indptr, G_m.indices, n_qubits)
609
+ min_energy = -energy if is_spin_glass else energy
610
+
611
+ return bitstring, float(cut_value), (l, r), float(min_energy)