PyQrackIsing 8.10.0__py3-none-win_amd64.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,317 @@
1
+ import math
2
+ import networkx as nx
3
+ import numpy as np
4
+ import os
5
+ from numba import njit, prange
6
+ from scipy.sparse import lil_matrix
7
+
8
+
9
+ class OpenCLContext:
10
+ def __init__(self, p, a, w, d, e, r, c, q, b, s, x, y):
11
+ self.MAX_GPU_PROC_ELEM = p
12
+ self.IS_OPENCL_AVAILABLE = a
13
+ self.work_group_size = w
14
+ self.dtype = d
15
+ self.epsilon = e
16
+ self.max_alloc = r
17
+ self.ctx = c
18
+ self.queue = q
19
+ self.bootstrap_kernel = b
20
+ self.bootstrap_sparse_kernel = s
21
+ self.bootstrap_segmented_kernel = x
22
+ self.bootstrap_sparse_segmented_kernel = y
23
+ self.G_m_buf = None
24
+ self.G_data_buf = None
25
+ self.G_rows_buf = None
26
+ self.G_cols_buf = None
27
+
28
+ IS_OPENCL_AVAILABLE = True
29
+ ctx = None
30
+ queue = None
31
+ compute_units = None
32
+ dtype = np.float32
33
+ epsilon = 2 ** -23
34
+ work_group_size = 32
35
+ max_alloc = 0xFFFFFFFFFFFFFFFF
36
+ bootstrap_kernel = None
37
+ bootstrap_sparse_kernel = None
38
+ bootstrap_segmented_kernel = None
39
+ bootstrap_sparse_segmented_kernel = None
40
+
41
+ dtype_bits = int(os.getenv('PYQRACKISING_FPPOW', '5'))
42
+ kernel_src = ''
43
+ if dtype_bits <= 4:
44
+ dtype = np.float16
45
+ epsilon = 2 ** -10
46
+ kernel_src += "#pragma OPENCL EXTENSION cl_khr_fp16 : enable\n"
47
+ kernel_src += "#define FP16 1\n"
48
+ kernel_src += "#define real1 half\n"
49
+ kernel_src += "#define qint short\n"
50
+ kernel_src += "#define EPSILON ((half)0.00097656f)\n"
51
+ kernel_src += "#define ZERO_R1 ((half)0.0f)\n"
52
+ kernel_src += "#define ONE_R1 ((half)1.0f)\n"
53
+ kernel_src += "#define TWO_R1 ((half)2.0f)\n"
54
+ elif dtype_bits >= 6:
55
+ dtype = np.float64
56
+ epsilon = 2 ** -52
57
+ kernel_src += "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"
58
+ kernel_src += "#define real1 double\n"
59
+ kernel_src += "#define qint long\n"
60
+ kernel_src += "#define EPSILON DBL_EPSILON\n"
61
+ kernel_src += "#define ZERO_R1 0.0\n"
62
+ kernel_src += "#define ONE_R1 1.0\n"
63
+ kernel_src += "#define TWO_R1 2.0\n"
64
+ else:
65
+ dtype = np.float32
66
+ epsilon = 2 ** -23
67
+ kernel_src += "#define real1 float\n"
68
+ kernel_src += "#define qint int\n"
69
+ kernel_src += "#define EPSILON FLT_EPSILON\n"
70
+ kernel_src += "#define ZERO_R1 0.0f\n"
71
+ kernel_src += "#define ONE_R1 1.0f\n"
72
+ kernel_src += "#define TWO_R1 2.0f\n"
73
+
74
+ try:
75
+ import pyopencl as cl
76
+ import warnings
77
+
78
+ warnings.simplefilter("ignore", cl.CompilerWarning)
79
+
80
+ # Pick a device (GPU if available)
81
+ ctx = cl.create_some_context()
82
+ queue = cl.CommandQueue(ctx)
83
+ compute_units = int(os.getenv('PYQRACKISING_MAX_GPU_PROC_ELEM', str(ctx.devices[0].get_info(cl.device_info.MAX_COMPUTE_UNITS))))
84
+
85
+ # Load and build OpenCL kernels
86
+ kernel_src += f"#define MAX_PROC_ELEM {compute_units}\n"
87
+ kernel_src += f"#define TOP_N {os.getenv('PYQRACKISING_GPU_TOP_N', '32')}\n"
88
+ kernel_src += open(os.path.dirname(os.path.abspath(__file__)) + "/kernels.cl").read()
89
+ program = cl.Program(ctx, kernel_src).build()
90
+ bootstrap_kernel = program.bootstrap
91
+ bootstrap_sparse_kernel = program.bootstrap_sparse
92
+ bootstrap_segmented_kernel = program.bootstrap_segmented
93
+ bootstrap_sparse_segmented_kernel = program.bootstrap_sparse_segmented
94
+
95
+ work_group_size = bootstrap_kernel.get_work_group_info(
96
+ cl.kernel_work_group_info.PREFERRED_WORK_GROUP_SIZE_MULTIPLE,
97
+ ctx.devices[0]
98
+ )
99
+
100
+ max_alloc = ctx.devices[0].get_info(cl.device_info.MAX_MEM_ALLOC_SIZE)
101
+ except ImportError:
102
+ IS_OPENCL_AVAILABLE = False
103
+ print("PyOpenCL not installed. (If you have any OpenCL accelerator devices with available ICDs, you might want to optionally install pyopencl.)")
104
+
105
+ opencl_context = OpenCLContext(compute_units, IS_OPENCL_AVAILABLE, work_group_size, dtype, epsilon, max_alloc, ctx, queue, bootstrap_kernel, bootstrap_sparse_kernel, bootstrap_segmented_kernel, bootstrap_sparse_segmented_kernel)
106
+
107
+
108
+ @njit
109
+ def get_cut(solution, nodes):
110
+ bit_string = ""
111
+ l, r = [], []
112
+ for i in range(len(solution)):
113
+ if solution[i]:
114
+ bit_string += "1"
115
+ r.append(nodes[i])
116
+ else:
117
+ bit_string += "0"
118
+ l.append(nodes[i])
119
+
120
+ return bit_string, l, r
121
+
122
+
123
+ @njit
124
+ def binary_search(l, t):
125
+ left = 0
126
+ right = len(l) - 1
127
+
128
+ while left <= right:
129
+ mid = (left + right) >> 1
130
+
131
+ if l[mid] == t:
132
+ return mid
133
+
134
+ if l[mid] < t:
135
+ left = mid + 1
136
+ else:
137
+ right = mid - 1
138
+
139
+ return len(l)
140
+
141
+
142
+ def to_scipy_sparse_upper_triangular(G, nodes, n_nodes):
143
+ lil = lil_matrix((n_nodes, n_nodes), dtype=dtype)
144
+ for u in range(n_nodes):
145
+ u_node = nodes[u]
146
+ for v in range(u + 1, n_nodes):
147
+ v_node = nodes[v]
148
+ if G.has_edge(u_node, v_node):
149
+ lil[u, v] = G[u_node][v_node].get('weight', 1.0)
150
+
151
+ return lil.tocsr()
152
+
153
+
154
+ @njit(parallel=True)
155
+ def init_theta(h_mult, n_qubits, J_eff, degrees):
156
+ theta = np.empty(n_qubits, dtype=np.float64)
157
+ h_mult = abs(h_mult)
158
+ for q in prange(n_qubits):
159
+ J = J_eff[q]
160
+ z = degrees[q]
161
+ zJ = z * J
162
+ 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)))
163
+
164
+ return theta
165
+
166
+
167
+ @njit
168
+ def init_thresholds(n_qubits):
169
+ n_bias = n_qubits - 1
170
+ thresholds = np.empty(n_bias, dtype=np.float64)
171
+ tot_prob = 0
172
+ p = 1.0
173
+ if n_qubits & 1:
174
+ q = n_qubits // 2
175
+ thresholds[q - 1] = p
176
+ tot_prob = p
177
+ p /= 2
178
+ for q in range(1, n_qubits // 2):
179
+ thresholds[q - 1] = p
180
+ thresholds[n_bias - q] = p
181
+ tot_prob += 2 * p
182
+ p /= 2
183
+ thresholds /= tot_prob
184
+
185
+ return thresholds
186
+
187
+
188
+ @njit
189
+ def probability_by_hamming_weight(J, h, z, theta, t, n_bias):
190
+ zJ = z * J
191
+ 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)))
192
+
193
+ p = (
194
+ 2.0 ** (abs(J / h) - 1.0)
195
+ * (1.0 + np.sin(theta - theta_c) * np.cos(1.5 * np.pi * J * t + theta) / (1.0 + np.sqrt(t)))
196
+ - 0.5
197
+ )
198
+
199
+
200
+ bias = np.empty(n_bias, dtype=np.float64)
201
+ factor = 2.0 ** -(p / n_bias)
202
+ result = 1.0
203
+ for q in range(n_bias):
204
+ result *= factor
205
+ bias[q] = result
206
+
207
+ if (result == 0.0) or np.isnan(result) or np.isinf(result):
208
+ print("[WARN]: probability_by_hamming_weight() went below maximum precision.")
209
+
210
+ if J > 0.0:
211
+ return bias[::-1]
212
+
213
+ return bias
214
+
215
+
216
+ @njit(parallel=True)
217
+ def maxcut_hamming_cdf(n_qubits, J_func, degrees, quality, tot_t, h_mult):
218
+ hamming_prob = init_thresholds(n_qubits)
219
+
220
+ n_steps = 1 << quality
221
+ delta_t = tot_t / n_steps
222
+ n_bias = n_qubits + 1
223
+
224
+ theta = init_theta(h_mult, n_qubits, J_func, degrees)
225
+
226
+ for qc in prange(n_qubits, n_steps * n_qubits):
227
+ step = qc // n_qubits
228
+ q = qc % n_qubits
229
+ J_eff = J_func[q]
230
+ if abs(J_eff) < epsilon:
231
+ continue
232
+ z = degrees[q]
233
+ theta_eff = theta[q]
234
+ t = step * delta_t
235
+ tm1 = (step - 1) * delta_t
236
+ h_t = h_mult * (tot_t - t)
237
+ bias = probability_by_hamming_weight(J_eff, h_t, z, theta_eff, t, n_bias)
238
+ last_bias = probability_by_hamming_weight(J_eff, h_t, z, theta_eff, tm1, n_bias)
239
+ for i in range(n_bias):
240
+ hamming_prob[i] += bias[i] - last_bias[i]
241
+
242
+ cum_prob = fix_cdf(hamming_prob)
243
+
244
+ return cum_prob
245
+
246
+ @njit
247
+ def fix_cdf(hamming_prob):
248
+ hamming_prob /= hamming_prob.sum() - (hamming_prob[0] + hamming_prob[-1])
249
+ tot_prob = 0.0
250
+ n_bias = len(hamming_prob) - 2
251
+ cum_prob = np.empty(n_bias, dtype=np.float64)
252
+ for i in range(n_bias):
253
+ tot_prob += hamming_prob[i + 1]
254
+ cum_prob[i] = tot_prob
255
+ cum_prob[-1] = 2.0
256
+
257
+ return cum_prob
258
+
259
+ @njit
260
+ def sample_mag(cum_prob):
261
+ p = np.random.random()
262
+ m = 0
263
+ left = 0
264
+ right = len(cum_prob) - 1
265
+ while True:
266
+ m = (left + right) >> 1
267
+
268
+ if (cum_prob[m] >= p) and ((m == 0) or cum_prob[m - 1] < p):
269
+ break
270
+
271
+ if cum_prob[m] < p:
272
+ left = m + 1
273
+ else:
274
+ right = m - 1
275
+
276
+ return m + 1
277
+
278
+ @njit
279
+ def init_bit_pick(weights, tot_init_weight, n):
280
+ r = np.random.rand()
281
+ cum = 0.0
282
+ node = 0
283
+ for i in range(n):
284
+ cum += weights[i]
285
+ if (tot_init_weight * r) < cum:
286
+ node = i
287
+ break
288
+
289
+ return node
290
+
291
+ @njit
292
+ def bit_pick(weights, used, n):
293
+ # Count available
294
+ total_w = 0.0
295
+ for i in range(n):
296
+ if used[i]:
297
+ continue
298
+ total_w += weights[i]
299
+
300
+ # Normalize & sample
301
+ r = np.random.rand()
302
+ cum = 0.0
303
+ node = -1
304
+ for i in range(n):
305
+ if used[i]:
306
+ continue
307
+ cum += weights[i]
308
+ if (total_w * r) < cum:
309
+ node = i
310
+ break
311
+
312
+ if node == -1:
313
+ node = 0
314
+ while used[node]:
315
+ node += 1
316
+
317
+ return node
@@ -0,0 +1,323 @@
1
+ from .maxcut_tfim import maxcut_tfim
2
+ from .maxcut_tfim_util import opencl_context
3
+ from .spin_glass_solver_util import get_cut_from_bit_array, int_to_bitstring
4
+ import itertools
5
+ import networkx as nx
6
+ import numpy as np
7
+ from numba import njit, prange
8
+ import os
9
+ import random
10
+
11
+
12
+ IS_OPENCL_AVAILABLE = True
13
+ try:
14
+ import pyopencl as cl
15
+ except ImportError:
16
+ IS_OPENCL_AVAILABLE = False
17
+
18
+
19
+ @njit
20
+ def evaluate_cut_edges(theta_bits, G_m):
21
+ n_qubits = len(G_m)
22
+ cut = 0
23
+ for u in range(n_qubits):
24
+ for v in range(u + 1, n_qubits):
25
+ if theta_bits[u] != theta_bits[v]:
26
+ cut += G_m[u, v]
27
+
28
+ return cut
29
+
30
+
31
+ @njit
32
+ def compute_energy(theta_bits, G_m):
33
+ n_qubits = len(G_m)
34
+ energy = 0
35
+ for u in range(n_qubits):
36
+ for v in range(u + 1, n_qubits):
37
+ energy += G_m[u, v] if theta_bits[u] == theta_bits[v] else -G_m[u, v]
38
+
39
+ return energy
40
+
41
+
42
+ @njit
43
+ def bootstrap_worker(theta, G_m, indices, is_spin_glass):
44
+ local_theta = theta.copy()
45
+ for i in indices:
46
+ local_theta[i] = not local_theta[i]
47
+ energy = compute_energy(local_theta, G_m) if is_spin_glass else -evaluate_cut_edges(local_theta, G_m)
48
+
49
+ return energy
50
+
51
+
52
+ @njit(parallel=True)
53
+ def bootstrap(best_theta, G_m, indices_array, k, min_energy, dtype, is_spin_glass):
54
+ n = len(indices_array) // k
55
+ energies = np.empty(n, dtype=dtype)
56
+ for i in prange(n):
57
+ j = i * k
58
+ energies[i] = bootstrap_worker(best_theta, G_m, indices_array[j : j + k], is_spin_glass)
59
+
60
+ energy = energies.min()
61
+ if energy < min_energy:
62
+ index_match = np.random.choice(np.where(energies == energy)[0])
63
+ indices = indices_array[(index_match * k) : ((index_match + 1) * k)]
64
+ min_energy = energy
65
+ for i in indices:
66
+ best_theta[i] = not best_theta[i]
67
+
68
+ return min_energy
69
+
70
+
71
+ def run_bootstrap_opencl(best_theta, G_m_buf, indices_array_np, k, min_energy, is_segmented, segment_size, is_spin_glass):
72
+ ctx = opencl_context.ctx
73
+ queue = opencl_context.queue
74
+ bootstrap_kernel = opencl_context.bootstrap_segmented_kernel if is_segmented else opencl_context.bootstrap_kernel
75
+ dtype = opencl_context.dtype
76
+ epsilon = opencl_context.epsilon
77
+ wgs = opencl_context.work_group_size
78
+
79
+ n = best_theta.shape[0]
80
+ combo_count = len(indices_array_np) // k
81
+
82
+ best_theta_np = np.array([(1 if b else 0) for b in best_theta], dtype=np.int8)
83
+
84
+ # Args: [n, k, combo_count, segment_size]
85
+ args_np = np.array([n, k, combo_count, is_spin_glass, segment_size], dtype=np.int32)
86
+
87
+ # Buffers
88
+ mf = cl.mem_flags
89
+ best_theta_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=best_theta_np)
90
+ indices_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=indices_array_np)
91
+ args_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=args_np)
92
+
93
+ # Local memory allocation (1 float per work item)
94
+ local_size = min(wgs, n)
95
+ max_global_size = ((opencl_context.MAX_GPU_PROC_ELEM + local_size - 1) // local_size) * local_size # corresponds to MAX_PROC_ELEM macro in OpenCL kernel program
96
+ global_size = min(((combo_count + local_size - 1) // local_size) * local_size, max_global_size)
97
+ local_energy_buf = cl.LocalMemory(np.dtype(dtype).itemsize * local_size)
98
+ local_index_buf = cl.LocalMemory(np.dtype(np.int32).itemsize * local_size)
99
+
100
+ # Allocate min_energy and min_index result buffers per workgroup
101
+ min_energy_host = np.empty(global_size, dtype=dtype)
102
+ min_index_host = np.empty(global_size, dtype=np.int32)
103
+
104
+ min_energy_buf = cl.Buffer(ctx, mf.WRITE_ONLY, min_energy_host.nbytes)
105
+ min_index_buf = cl.Buffer(ctx, mf.WRITE_ONLY, min_index_host.nbytes)
106
+
107
+ # Set kernel args
108
+ if is_segmented:
109
+ bootstrap_kernel.set_args(
110
+ np.random.randint(1<<32, dtype='uint32'),
111
+ G_m_buf[0],
112
+ G_m_buf[1],
113
+ G_m_buf[2],
114
+ G_m_buf[3],
115
+ best_theta_buf,
116
+ indices_buf,
117
+ args_buf,
118
+ min_energy_buf,
119
+ min_index_buf,
120
+ local_energy_buf,
121
+ local_index_buf
122
+ )
123
+ else:
124
+ bootstrap_kernel.set_args(
125
+ np.random.randint(1<<32, dtype='uint32'),
126
+ G_m_buf,
127
+ best_theta_buf,
128
+ indices_buf,
129
+ args_buf,
130
+ min_energy_buf,
131
+ min_index_buf,
132
+ local_energy_buf,
133
+ local_index_buf
134
+ )
135
+
136
+ cl.enqueue_nd_range_kernel(queue, bootstrap_kernel, (global_size,), (local_size,))
137
+
138
+ # Read results
139
+ cl.enqueue_copy(queue, min_energy_host, min_energy_buf)
140
+ cl.enqueue_copy(queue, min_index_host, min_index_buf)
141
+ queue.finish()
142
+
143
+ # Find global minimum
144
+ energy = min_energy_host.min()
145
+ if min_energy < energy:
146
+ return min_energy
147
+
148
+ atol = dtype(epsilon)
149
+ rtol = dtype(0)
150
+ choices = np.where(np.isclose(min_energy_host, energy, atol=atol, rtol=rtol))[0]
151
+ best_i = np.random.choice(choices) if len(choices) else np.argmin(min_energy_host)
152
+
153
+ flip_index_start = best_i * k
154
+ indices_to_flip = indices_array_np[flip_index_start : flip_index_start + k]
155
+
156
+ for i in indices_to_flip:
157
+ best_theta[i] = not best_theta[i]
158
+
159
+ return min_energy_host[best_i]
160
+
161
+
162
+ def log_intermediate(theta, G_m, nodes, min_energy, is_spin_glass):
163
+ bitstring, l, r = get_cut_from_bit_array(theta, nodes)
164
+ if is_spin_glass:
165
+ cut_value = evaluate_cut_edges(theta, G_m)
166
+ else:
167
+ cut_value = -min_energy
168
+ min_energy = compute_energy(theta, G_m)
169
+ print(bitstring, float(cut_value), (l, r), float(min_energy))
170
+
171
+
172
+ def spin_glass_solver(
173
+ G,
174
+ quality=None,
175
+ shots=None,
176
+ best_guess=None,
177
+ is_combo_maxcut_gpu=True,
178
+ is_spin_glass=True,
179
+ anneal_t=None,
180
+ anneal_h=None,
181
+ repulsion_base=None,
182
+ min_order=1,
183
+ max_order=None,
184
+ is_log=False,
185
+ reheat_tries=0
186
+ ):
187
+ dtype = opencl_context.dtype
188
+ nodes = None
189
+ n_qubits = 0
190
+ G_m = None
191
+ if isinstance(G, nx.Graph):
192
+ nodes = list(G.nodes())
193
+ n_qubits = len(nodes)
194
+ G_m = nx.to_numpy_array(G, weight='weight', nonedge=0.0, dtype=dtype)
195
+ else:
196
+ n_qubits = len(G)
197
+ nodes = list(range(n_qubits))
198
+ G_m = G
199
+
200
+ segment_size = G_m.shape[0] ** 2
201
+ is_segmented = (G_m.nbytes << 1) > opencl_context.max_alloc
202
+ if is_segmented and is_alt_gpu_sampling:
203
+ print("[WARN] Using segmented solver, so disabling is_alt_gpu_sampling.")
204
+ is_alt_gpu_sampling = False
205
+
206
+ if n_qubits < 3:
207
+ if n_qubits == 0:
208
+ return "", 0, ([], []), 0
209
+
210
+ if n_qubits == 1:
211
+ return "0", 0, (nodes, []), 0
212
+
213
+ if n_qubits == 2:
214
+ weight = G_m[0, 1]
215
+ if weight < 0.0:
216
+ return "00", 0, (nodes, []), weight
217
+
218
+ return "01", weight, ([nodes[0]], [nodes[1]]), -weight
219
+
220
+ bitstring = ""
221
+ if isinstance(best_guess, str):
222
+ bitstring = best_guess
223
+ elif isinstance(best_guess, int):
224
+ bitstring = int_to_bitstring(best_guess, n_qubits)
225
+ elif isinstance(best_guess, list):
226
+ bitstring = "".join(["1" if b else "0" for b in best_guess])
227
+ else:
228
+ bitstring, _, _ = maxcut_tfim(G_m, quality=quality, shots=shots, is_spin_glass=is_spin_glass, anneal_t=anneal_t, anneal_h=anneal_h, repulsion_base=repulsion_base)
229
+ best_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
230
+
231
+ if is_combo_maxcut_gpu and IS_OPENCL_AVAILABLE:
232
+ if not (opencl_context.G_m_buf is None):
233
+ G_m_buf = opencl_context.G_m_buf
234
+ else:
235
+ mf = cl.mem_flags
236
+ ctx = opencl_context.ctx
237
+ if is_segmented:
238
+ o_shape = segment_size
239
+ segment_size = (segment_size + 3) >> 2
240
+ n_shape = segment_size << 2
241
+ _G_m = np.reshape(G_m, (o_shape,))
242
+ if n_shape != o_shape:
243
+ np.resize(_G_m, (n_shape,))
244
+ _G_m_segments = np.split(_G_m, 4)
245
+ G_m_buf = [
246
+ cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=seg)
247
+ for seg in _G_m_segments
248
+ ]
249
+ _G_m = None
250
+ _G_m_segments = None
251
+ else:
252
+ G_m_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=G_m)
253
+
254
+ if max_order is None:
255
+ max_order = n_qubits
256
+
257
+ min_energy = compute_energy(best_theta, G_m) if is_spin_glass else -evaluate_cut_edges(best_theta, G_m)
258
+
259
+ if is_log:
260
+ log_intermediate(best_theta, G_m, nodes, min_energy, is_spin_glass)
261
+
262
+ combos_list = []
263
+ reheat_theta = best_theta.copy()
264
+ reheat_min_energy = min_energy
265
+ for reheat_round in range(reheat_tries + 1):
266
+ improved = True
267
+ correction_quality = min_order
268
+ while improved:
269
+ improved = False
270
+ k = 1
271
+ while (k <= correction_quality) and (k <= max_order):
272
+ if n_qubits < k:
273
+ break
274
+
275
+ combos = []
276
+ if len(combos_list) < k:
277
+ combos = np.array(list(
278
+ item for sublist in itertools.combinations(range(n_qubits), k) for item in sublist
279
+ ))
280
+ combos_list.append(combos)
281
+ else:
282
+ combos = combos_list[k - 1]
283
+
284
+ if is_combo_maxcut_gpu and IS_OPENCL_AVAILABLE:
285
+ energy = run_bootstrap_opencl(reheat_theta, G_m_buf, combos, k, reheat_min_energy, is_segmented, segment_size, is_spin_glass)
286
+ else:
287
+ energy = bootstrap(reheat_theta, G_m, combos, k, reheat_min_energy, dtype, is_spin_glass)
288
+
289
+ if energy < reheat_min_energy:
290
+ reheat_min_energy = energy
291
+ improved = True
292
+ if correction_quality < (k + 1):
293
+ correction_quality = k + 1
294
+ if is_log:
295
+ log_intermediate(reheat_theta, G_m, nodes, reheat_min_energy, is_spin_glass)
296
+
297
+ break
298
+
299
+ k = k + 1
300
+
301
+ if min_energy < reheat_min_energy:
302
+ reheat_theta = best_theta.copy()
303
+ else:
304
+ best_theta = reheat_theta.copy()
305
+ min_energy = reheat_min_energy
306
+
307
+ if reheat_round < reheat_tries:
308
+ num_to_flip = int(np.round(np.log2(n_qubits)))
309
+ bits_to_flip = random.sample(list(range(n_qubits)), num_to_flip)
310
+ for bit in bits_to_flip:
311
+ reheat_theta[bit] = not reheat_theta[bit]
312
+ reheat_min_energy = compute_energy(reheat_theta, G_m) if is_spin_glass else -evaluate_cut_edges(reheat_theta, G_m)
313
+
314
+ opencl_context.G_m_buf = None
315
+
316
+ bitstring, l, r = get_cut_from_bit_array(best_theta, nodes)
317
+ if is_spin_glass:
318
+ cut_value = evaluate_cut_edges(best_theta, G_m)
319
+ else:
320
+ cut_value = -min_energy
321
+ min_energy = compute_energy(best_theta, G_m)
322
+
323
+ return bitstring, float(cut_value), (l, r), float(min_energy)