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,518 @@
1
+ import networkx as nx
2
+ import numpy as np
3
+ from numba import njit, prange
4
+ import os
5
+ import time
6
+
7
+ from .maxcut_tfim_util import (
8
+ binary_search,
9
+ compute_cut_sparse,
10
+ compute_energy_sparse,
11
+ convert_bool_to_uint,
12
+ get_cut,
13
+ get_cut_base,
14
+ heuristic_threshold_sparse,
15
+ init_thresholds,
16
+ make_G_m_csr_buf,
17
+ make_theta_buf,
18
+ maxcut_hamming_cdf,
19
+ opencl_context,
20
+ sample_mag,
21
+ setup_opencl,
22
+ bit_pick_u,
23
+ as_upper_csr,
24
+ resolve_seed,
25
+ rng_init,
26
+ rng_uniform,
27
+ sample_mag_u,
28
+ to_scipy_sparse_upper_triangular,
29
+ )
30
+
31
+ IS_OPENCL_AVAILABLE = True
32
+ try:
33
+ import pyopencl as cl
34
+ except ImportError:
35
+ IS_OPENCL_AVAILABLE = False
36
+
37
+
38
+ epsilon = opencl_context.epsilon
39
+ dtype = opencl_context.dtype
40
+
41
+
42
+ @njit(cache=True)
43
+ def update_repulsion_choice(G_data, G_rows, G_cols, R_data, weights, n, node, repulsion_base):
44
+ # Select node
45
+ weights[node] = 0.0
46
+
47
+ if abs(1.0 - repulsion_base) <= epsilon:
48
+ return
49
+
50
+ # Repulsion: penalize neighbors
51
+ for j in range(G_rows[node], G_rows[node + 1]):
52
+ nbr = G_cols[j]
53
+ if weights[nbr] == 0.0:
54
+ continue
55
+ weights[nbr] *= R_data[j]
56
+
57
+ for nbr in range(node):
58
+ if weights[nbr] == 0.0:
59
+ continue
60
+ start = G_rows[nbr]
61
+ end = G_rows[nbr + 1]
62
+ j = binary_search(G_cols[start:end], node) + start
63
+ if j < end:
64
+ weights[nbr] *= R_data[j]
65
+
66
+
67
+ # Written by Elara (OpenAI custom GPT) and improved by Dan Strano
68
+ @njit(cache=True)
69
+ def local_repulsion_choice(G_data, G_rows, G_cols, R_data, repulsion_base, n, m, s, rng):
70
+ """
71
+ Pick m nodes out of n with repulsion bias:
72
+ - High-degree nodes are already less likely
73
+ - After choosing a node, its neighbors' probabilities are further reduced
74
+ R_data = repulsion_base ** -G_data (precomputed per edge); rng is this
75
+ shot's counter-based generator state.
76
+ """
77
+
78
+ # First bit:
79
+ node = s % n
80
+ if m == 1:
81
+ used = np.zeros(n, dtype=np.bool_)
82
+ used[node] = True
83
+ return used
84
+
85
+ weights = np.ones(n, dtype=np.float64)
86
+ update_repulsion_choice(G_data, G_rows, G_cols, R_data, weights, n, node, repulsion_base)
87
+
88
+ for _ in range(1, m - 1):
89
+ rng, u = rng_uniform(rng)
90
+ node = bit_pick_u(weights, n, u)
91
+ update_repulsion_choice(G_data, G_rows, G_cols, R_data, weights, n, node, repulsion_base)
92
+
93
+ rng, u = rng_uniform(rng)
94
+ node = bit_pick_u(weights, n, u)
95
+ weights[node] = 0.0
96
+
97
+ return weights == 0.0
98
+
99
+
100
+ @njit(parallel=True, cache=True)
101
+ def sample_round(G_data, G_rows, G_cols, R_data, shot_segment, thread_count, thresholds, repulsion_base, is_spin_glass,
102
+ base_seed, rnd, solutions, energies):
103
+ n = G_rows.shape[0] - 1
104
+ for i in prange(thread_count):
105
+ s_offset = i * shot_segment
106
+ for j in range(shot_segment):
107
+ s = s_offset + j
108
+ rng = rng_init(base_seed, rnd, s)
109
+
110
+ # First dimension: Hamming weight
111
+ rng, u = rng_uniform(rng)
112
+ m = sample_mag_u(thresholds, u)
113
+
114
+ # Second dimension: permutation within Hamming weight
115
+ sample = local_repulsion_choice(G_data, G_rows, G_cols, R_data, repulsion_base, n, m, s, rng)
116
+ if is_spin_glass:
117
+ energy = compute_energy_sparse(sample, G_data, G_rows, G_cols, n)
118
+ else:
119
+ energy = compute_cut_sparse(sample, G_data, G_rows, G_cols, n)
120
+
121
+ if energy > energies[i]:
122
+ solutions[i], energies[i] = sample, energy
123
+
124
+
125
+ def sample_measurement(G_data, G_rows, G_cols, R_data, shots, thread_count, thresholds, repulsion_base, is_spin_glass,
126
+ base_seed, deadline):
127
+ # Rounds run from Python so a time limit can stop between them.
128
+ shot_segment = (max(1, shots >> 1) + thread_count - 1) // thread_count
129
+ shots = shot_segment * thread_count
130
+ n = G_rows.shape[0] - 1
131
+
132
+ solutions = np.zeros((thread_count, n), dtype=np.bool_)
133
+ energies = np.full(thread_count, np.finfo(dtype).min, dtype=dtype)
134
+
135
+ best_solution = solutions[0].copy()
136
+ best_energy = -float("inf")
137
+
138
+ rnd = 0
139
+ improved = True
140
+ while improved and (rnd == 0 or time.perf_counter() < deadline):
141
+ improved = False
142
+ sample_round(G_data, G_rows, G_cols, R_data, shot_segment, thread_count, thresholds, repulsion_base, is_spin_glass,
143
+ base_seed, rnd, solutions, energies)
144
+ rnd += 1
145
+
146
+ best_index = np.argmax(energies)
147
+ energy = energies[best_index]
148
+ if energy > best_energy:
149
+ best_energy = energy
150
+ best_solution = solutions[best_index].copy()
151
+ improved = True
152
+
153
+ if is_spin_glass:
154
+ # (was computed from the last sample drawn, not from the best solution)
155
+ best_energy = compute_cut_sparse(best_solution, G_data, G_rows, G_cols, n)
156
+
157
+ return best_solution, best_energy
158
+
159
+
160
+ @njit(parallel=True, cache=True)
161
+ def shot_loop(G_data, G_rows, G_cols, R_data, thresholds, repulsion_base, n, shots, solutions, base_seed, rnd):
162
+ for s in prange(shots):
163
+ rng = rng_init(base_seed, rnd, s)
164
+ # First dimension: Hamming weight
165
+ rng, u = rng_uniform(rng)
166
+ m = sample_mag_u(thresholds, u)
167
+ # Second dimension: permutation within Hamming weight
168
+ solutions[s] = local_repulsion_choice(G_data, G_rows, G_cols, R_data, repulsion_base, n, m, s, rng)
169
+
170
+
171
+ def sample_for_opencl(
172
+ G_data,
173
+ G_rows,
174
+ G_cols,
175
+ R_data,
176
+ G_data_buf,
177
+ G_rows_buf,
178
+ G_cols_buf,
179
+ shots,
180
+ thresholds,
181
+ repulsion_base,
182
+ is_spin_glass,
183
+ is_segmented,
184
+ segment_size,
185
+ theta_segment_size,
186
+ base_seed,
187
+ deadline,
188
+ ):
189
+ shots = ((max(1, shots >> 1) + 31) >> 5) << 5
190
+ n = G_rows.shape[0] - 1
191
+
192
+ solutions = np.empty((shots, n), dtype=np.bool_)
193
+
194
+ best_solution = np.zeros(n, dtype=np.bool_)
195
+ best_energy = compute_energy_sparse(best_solution, G_data, G_rows, G_cols, n) if is_spin_glass else 0.0
196
+
197
+ opencl_args = setup_opencl(
198
+ shots,
199
+ shots,
200
+ np.array([n, shots, is_spin_glass, segment_size, theta_segment_size], dtype=np.int32),
201
+ )
202
+
203
+ rnd = 0
204
+ improved = True
205
+ while improved and (rnd == 0 or time.perf_counter() < deadline):
206
+ improved = False
207
+ shot_loop(G_data, G_rows, G_cols, R_data, thresholds, repulsion_base, n, shots, solutions, base_seed, rnd)
208
+ rnd += 1
209
+ solution, energy = run_cut_opencl(best_energy, solutions, G_data_buf, G_rows_buf, G_cols_buf, is_segmented, *opencl_args)
210
+ if energy > best_energy:
211
+ best_energy = energy
212
+ best_solution = solution
213
+ improved = True
214
+
215
+ if is_spin_glass:
216
+ best_energy = compute_cut_sparse(best_solution, G_data, G_rows, G_cols, n)
217
+
218
+ return best_solution, float(best_energy)
219
+
220
+
221
+ def init_J_and_z(G_m, repulsion_base):
222
+ """Same result as the former element-by-element Python loop over all n^2
223
+ (row, column) pairs, computed from the stored entries in O(nnz + n):
224
+ every implicit zero contributes val = -G_min."""
225
+ G_min = float(G_m.min())
226
+ n_qubits = G_m.shape[0]
227
+ return _init_J_and_z_csr(np.asarray(G_m.data, dtype=np.float64), G_m.indptr, n_qubits, G_min)
228
+
229
+
230
+ @njit(cache=True)
231
+ def _init_J_and_z_csr(G_data, G_rows, n_qubits, G_min):
232
+ degrees = np.empty(n_qubits, dtype=np.uint32)
233
+ J_eff = np.empty(n_qubits, dtype=np.float64)
234
+ zero_val = -G_min
235
+ for n in range(n_qubits):
236
+ degree = 0
237
+ J = 0.0
238
+ stored = G_rows[n + 1] - G_rows[n]
239
+ for k in range(G_rows[n], G_rows[n + 1]):
240
+ val = G_data[k] - G_min
241
+ if val <= epsilon:
242
+ continue
243
+ degree += 1
244
+ J += val
245
+ if zero_val > epsilon:
246
+ implicit = n_qubits - stored
247
+ degree += implicit
248
+ J += implicit * zero_val
249
+ if degree > 0:
250
+ J = -J / degree
251
+ degrees[n] = degree
252
+ J_eff[n] = J
253
+
254
+ return J_eff, degrees
255
+
256
+
257
+ def run_cut_opencl(
258
+ best_energy,
259
+ samples,
260
+ G_data_buf,
261
+ G_rows_buf,
262
+ G_cols_buf,
263
+ is_segmented,
264
+ local_size,
265
+ global_size,
266
+ args_buf,
267
+ local_energy_buf,
268
+ local_index_buf,
269
+ max_energy_host,
270
+ max_index_host,
271
+ max_energy_buf,
272
+ max_index_buf,
273
+ ):
274
+ queue = opencl_context.queue
275
+ calculate_cut_kernel = opencl_context.calculate_cut_sparse_segmented_kernel if is_segmented else opencl_context.calculate_cut_sparse_kernel
276
+
277
+ shots = samples.shape[0]
278
+ n = samples.shape[1]
279
+
280
+ # Buffers
281
+ mf = cl.mem_flags
282
+ theta_buf = make_theta_buf(convert_bool_to_uint(samples), is_segmented, shots, n)
283
+
284
+ # Set kernel args
285
+ if is_segmented:
286
+ calculate_cut_kernel.set_args(
287
+ G_data_buf[0],
288
+ G_data_buf[1],
289
+ G_data_buf[2],
290
+ G_data_buf[3],
291
+ G_rows_buf,
292
+ G_cols_buf,
293
+ theta_buf[0],
294
+ theta_buf[1],
295
+ theta_buf[2],
296
+ theta_buf[3],
297
+ args_buf,
298
+ max_energy_buf,
299
+ max_index_buf,
300
+ local_energy_buf,
301
+ local_index_buf,
302
+ )
303
+ else:
304
+ calculate_cut_kernel.set_args(
305
+ G_data_buf,
306
+ G_rows_buf,
307
+ G_cols_buf,
308
+ theta_buf,
309
+ args_buf,
310
+ max_energy_buf,
311
+ max_index_buf,
312
+ local_energy_buf,
313
+ local_index_buf,
314
+ )
315
+
316
+ cl.enqueue_nd_range_kernel(queue, calculate_cut_kernel, (global_size,), (local_size,))
317
+
318
+ # Read results
319
+ cl.enqueue_copy(queue, max_energy_host, max_energy_buf)
320
+ queue.finish()
321
+
322
+ # Queue read for results we might not need
323
+ cl.enqueue_copy(queue, max_index_host, max_index_buf)
324
+
325
+ # Find global minimum
326
+ best_x = np.argmax(max_energy_host)
327
+ energy = max_energy_host[best_x]
328
+
329
+ if energy <= best_energy:
330
+ # No improvement: we can exit early
331
+ return samples[0].copy(), max_energy_host[0]
332
+
333
+ # We need the best index
334
+ queue.finish()
335
+
336
+ return samples[max_index_host[best_x]].copy(), energy
337
+
338
+
339
+ @njit(cache=True)
340
+ def exact_maxcut(G_data, G_rows, G_cols):
341
+ """Brute-force exact MAXCUT solver using Numba JIT."""
342
+ n = G_rows.shape[0] - 1
343
+ max_cut = -1.0
344
+ best_mask = 0
345
+
346
+ # Enumerate all 2^n possible bitstrings
347
+ for mask in range(1 << n):
348
+ cut = 0.0
349
+ for i in range(n):
350
+ bi = (mask >> i) & 1
351
+ for j in range(i + 1, n):
352
+ if bi != ((mask >> j) & 1):
353
+ u, v = (i, j) if i < j else (j, i)
354
+ start = G_rows[u]
355
+ end = G_rows[u + 1]
356
+ k = binary_search(G_cols[start:end], v) + start
357
+ if k < end:
358
+ cut += G_data[k]
359
+ if cut > max_cut:
360
+ max_cut = cut
361
+ best_mask = mask
362
+
363
+ # Reconstruct best bitstring
364
+ best_bits = np.zeros(n, dtype=np.bool_)
365
+ for i in range(n):
366
+ best_bits[i] = (best_mask >> i) & 1
367
+
368
+ return best_bits, max_cut
369
+
370
+
371
+ @njit(cache=True)
372
+ def exact_spin_glass(G_data, G_rows, G_cols):
373
+ """Brute-force exact spin-glass solver using Numba JIT."""
374
+ n = G_rows.shape[0] - 1
375
+ max_cut = -1.0
376
+ best_mask = 0
377
+
378
+ # Enumerate all 2^n possible bitstrings
379
+ for mask in range(1 << n):
380
+ cut = 0.0
381
+ for i in range(n):
382
+ bi = (mask >> i) & 1
383
+ for j in range(i + 1, n):
384
+ u, v = (i, j) if i < j else (j, i)
385
+ start = G_rows[u]
386
+ end = G_rows[u + 1]
387
+ k = binary_search(G_cols[start:end], v) + start
388
+ if k < end:
389
+ val = G_data[k]
390
+ cut += -val if bi == ((mask >> j) & 1) else val # spin-glass energy: +w across the cut (was reversed)
391
+ if cut > max_cut:
392
+ max_cut = cut
393
+ best_mask = mask
394
+
395
+ # Reconstruct best bitstring
396
+ best_bits = np.zeros(n, dtype=np.bool_)
397
+ for i in range(n):
398
+ best_bits[i] = (best_mask >> i) & 1
399
+
400
+ return best_bits, max_cut
401
+
402
+
403
+ def maxcut_tfim_sparse(
404
+ G,
405
+ quality=None,
406
+ shots=None,
407
+ is_spin_glass=False,
408
+ anneal_t=None,
409
+ anneal_h=None,
410
+ repulsion_base=None,
411
+ is_maxcut_gpu=True,
412
+ is_nested=False,
413
+ seed=None,
414
+ time_limit=None,
415
+ ):
416
+ """
417
+ seed, time_limit: as for maxcut_tfim. A scipy input matrix is read as its
418
+ strict upper triangle (a full symmetric matrix gives the same graph).
419
+ """
420
+ deadline = float("inf") if time_limit is None else time.perf_counter() + time_limit
421
+ nodes = None
422
+ n_qubits = 0
423
+ G_m = None
424
+ if isinstance(G, nx.Graph):
425
+ nodes = list(G.nodes())
426
+ n_qubits = len(nodes)
427
+ G_m = to_scipy_sparse_upper_triangular(G, nodes, n_qubits)
428
+ else:
429
+ n_qubits = G.shape[0]
430
+ nodes = list(range(n_qubits))
431
+ G_m = as_upper_csr(G)
432
+
433
+ if n_qubits < heuristic_threshold_sparse:
434
+ best_solution, best_value = (
435
+ exact_spin_glass(G_m.data, G_m.indptr, G_m.indices) if is_spin_glass else exact_maxcut(G_m.data, G_m.indptr, G_m.indices)
436
+ )
437
+ bit_string, l, r = get_cut(best_solution, nodes, n_qubits)
438
+
439
+ if best_value < 0.0:
440
+ # Best cut is trivial partition, all/empty
441
+ return "0" * n_qubits, 0.0, (nodes, [])
442
+
443
+ return bit_string, best_value, (l, r)
444
+
445
+ if quality is None:
446
+ quality = 6
447
+
448
+ if shots is None:
449
+ # Number of measurement shots
450
+ shots = n_qubits << quality
451
+
452
+ if anneal_t is None:
453
+ anneal_t = 8.0
454
+
455
+ if anneal_h is None:
456
+ anneal_h = 8.0
457
+
458
+ if repulsion_base is None:
459
+ repulsion_base = 5.0
460
+
461
+ n_qubits = G_m.shape[0]
462
+
463
+ J_eff, degrees = init_J_and_z(G_m, repulsion_base)
464
+ cum_prob = maxcut_hamming_cdf(init_thresholds(n_qubits), n_qubits, J_eff, degrees, quality, anneal_t, anneal_h)
465
+
466
+ degrees = None
467
+ J_eff = None
468
+
469
+ base_seed = resolve_seed(seed)
470
+ R_data = np.power(np.float64(repulsion_base), -np.asarray(G_m.data, dtype=np.float64))
471
+
472
+ if is_maxcut_gpu and opencl_context.IS_OPENCL_AVAILABLE:
473
+ wgs = opencl_context.work_group_size
474
+ segment_size = (G_m.data.shape[0] + 3) >> 2
475
+ theta_segment_size = (((n_qubits + 31) >> 5) * (((shots + wgs - 1) // wgs) * wgs) + 3) >> 2
476
+ is_segmented = (G_m.data.nbytes << 1) > opencl_context.max_alloc or ((theta_segment_size << 3) > opencl_context.max_alloc)
477
+ G_data_buf, G_rows_buf, G_cols_buf = make_G_m_csr_buf(G_m, is_segmented, segment_size)
478
+ best_solution, best_value = sample_for_opencl(
479
+ G_m.data,
480
+ G_m.indptr,
481
+ G_m.indices,
482
+ R_data,
483
+ G_data_buf,
484
+ G_rows_buf,
485
+ G_cols_buf,
486
+ shots,
487
+ cum_prob,
488
+ repulsion_base,
489
+ is_spin_glass,
490
+ is_segmented,
491
+ segment_size,
492
+ theta_segment_size,
493
+ base_seed,
494
+ deadline,
495
+ )
496
+ else:
497
+ thread_count = os.cpu_count() ** 2
498
+ best_solution, best_value = sample_measurement(
499
+ G_m.data,
500
+ G_m.indptr,
501
+ G_m.indices,
502
+ R_data,
503
+ shots,
504
+ thread_count,
505
+ cum_prob,
506
+ repulsion_base,
507
+ is_spin_glass,
508
+ base_seed,
509
+ deadline,
510
+ )
511
+
512
+ bit_string, l, r = get_cut(best_solution, nodes, n_qubits)
513
+
514
+ if best_value < 0.0:
515
+ # Best cut is trivial partition, all/empty
516
+ return "0" * n_qubits, 0.0, (nodes, [])
517
+
518
+ return bit_string, best_value, (l, r)