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