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,401 @@
1
+ # SPDX-License-Identifier: LGPL-3.0-or-later
2
+ # Copyright (C) 2026 Daniel Strano and the Qrack contributors
3
+ #
4
+ # Drafted by (Anthropic) Claude.
5
+ #
6
+ # One CPU local search (single flips, double flips, Gray-code search and the
7
+ # "reheat" cascade) shared by the dense, sparse and streaming spin glass /
8
+ # MaxCut solvers.
9
+ #
10
+ # Everything is written in terms of single-flip gains: g_i, the change in cut
11
+ # value from flipping node i, is a sum over i's neighbours. Only that
12
+ # neighbour loop depends on how the graph is stored, so the kernels take all
13
+ # three representations' arguments
14
+ #
15
+ # (A, data, rows, cols, G_func, nodes)
16
+ #
17
+ # with the unused ones passed as None, and the representation-specific
18
+ # helpers below are resolved by numba @overload at COMPILE time from which
19
+ # arguments are None: each representation gets its own specialised machine
20
+ # code (measured at parity with the former hand-written variants), and
21
+ # cache=True works.
22
+ #
23
+ # dense A = symmetric (n, n) weight matrix
24
+ # sparse data, rows, cols = symmetric CSR with sorted column indices
25
+ # streaming G_func = numba-jitted weight function, nodes = node labels
26
+ #
27
+ # Spin-glass energy gains are 2 g. All kernels return gains ("deltas")
28
+ # relative to the state they are given.
29
+
30
+ import time
31
+
32
+ import numpy as np
33
+ from numba import njit, prange
34
+ from numba.core import types
35
+ from numba.extending import overload
36
+
37
+ from .maxcut_tfim_util import gray_code_next, gray_mutation
38
+
39
+
40
+ # ---------------------------------------------------------------------------
41
+ # Representation-specific helpers (compile-time dispatch)
42
+ # ---------------------------------------------------------------------------
43
+
44
+
45
+ def _is_none(t):
46
+ return isinstance(t, (types.NoneType, types.Omitted)) or t is None
47
+
48
+
49
+ def row_range(i, A, rows, G_func, nodes):
50
+ pass
51
+
52
+
53
+ def entry(k, i, A, data, cols, G_func, nodes):
54
+ pass
55
+
56
+
57
+ def pair_weight(i, j, A, data, rows, cols, G_func, nodes):
58
+ pass
59
+
60
+
61
+ def best_nonadjacent_pair(g, best_val, rows, cols, A, G_func):
62
+ pass
63
+
64
+
65
+ @overload(row_range, inline="always")
66
+ def _row_range(i, A, rows, G_func, nodes):
67
+ if not _is_none(G_func):
68
+ return lambda i, A, rows, G_func, nodes: (0, len(nodes))
69
+ if not _is_none(A):
70
+ return lambda i, A, rows, G_func, nodes: (0, A.shape[0])
71
+ return lambda i, A, rows, G_func, nodes: (rows[i], rows[i + 1])
72
+
73
+
74
+ @overload(entry, inline="always")
75
+ def _entry(k, i, A, data, cols, G_func, nodes):
76
+ """(neighbour index j, weight w_ij) for the k-th entry of row i. Dense and
77
+ streaming rows run over every j (including j == i, which callers skip)."""
78
+ if not _is_none(G_func):
79
+ return lambda k, i, A, data, cols, G_func, nodes: (k, np.float64(G_func(nodes[i], nodes[k])))
80
+ if not _is_none(A):
81
+ return lambda k, i, A, data, cols, G_func, nodes: (k, np.float64(A[i, k]))
82
+ return lambda k, i, A, data, cols, G_func, nodes: (cols[k], np.float64(data[k]))
83
+
84
+
85
+ @overload(pair_weight, inline="always")
86
+ def _pair_weight(i, j, A, data, rows, cols, G_func, nodes):
87
+ if not _is_none(G_func):
88
+ return lambda i, j, A, data, rows, cols, G_func, nodes: np.float64(G_func(nodes[i], nodes[j]))
89
+ if not _is_none(A):
90
+ return lambda i, j, A, data, rows, cols, G_func, nodes: np.float64(A[i, j])
91
+
92
+ def impl(i, j, A, data, rows, cols, G_func, nodes):
93
+ lo = rows[i]
94
+ hi = rows[i + 1] - 1
95
+ while lo <= hi:
96
+ mid = (lo + hi) >> 1
97
+ c = cols[mid]
98
+ if c == j:
99
+ return np.float64(data[mid])
100
+ if c < j:
101
+ lo = mid + 1
102
+ else:
103
+ hi = mid - 1
104
+ return 0.0
105
+
106
+ return impl
107
+
108
+
109
+ @overload(best_nonadjacent_pair)
110
+ def _best_nonadjacent_pair(g, best_val, rows, cols, A, G_func):
111
+ """Sparse only: the best pair NOT joined by an edge, whose gain is just
112
+ g_i + g_j, found by walking the gains in descending order. Dense and
113
+ streaming rows already cover every pair, so this is a no-op for them."""
114
+ if not (_is_none(A) and _is_none(G_func)):
115
+ return lambda g, best_val, rows, cols, A, G_func: (best_val, -1, -1)
116
+
117
+ def impl(g, best_val, rows, cols, A, G_func):
118
+ n = g.shape[0]
119
+ order = np.argsort(-g)
120
+ bi = -1
121
+ bj = -1
122
+ for a in range(n - 1):
123
+ ia = order[a]
124
+ if g[ia] + g[order[a + 1]] <= best_val:
125
+ break
126
+ for b in range(a + 1, n):
127
+ ib = order[b]
128
+ if g[ia] + g[ib] <= best_val:
129
+ break
130
+ lo = rows[ia]
131
+ hi = rows[ia + 1] - 1
132
+ adjacent = False
133
+ while lo <= hi:
134
+ mid = (lo + hi) >> 1
135
+ c = cols[mid]
136
+ if c == ib:
137
+ adjacent = True
138
+ break
139
+ if c < ib:
140
+ lo = mid + 1
141
+ else:
142
+ hi = mid - 1
143
+ if not adjacent:
144
+ best_val = g[ia] + g[ib]
145
+ bi = ia
146
+ bj = ib
147
+ break
148
+ return best_val, bi, bj
149
+
150
+ return impl
151
+
152
+
153
+ # ---------------------------------------------------------------------------
154
+ # Kernels
155
+ # ---------------------------------------------------------------------------
156
+
157
+
158
+ @njit(cache=True)
159
+ def flip_gain(i, state, A, data, rows, cols, G_func, nodes):
160
+ """MaxCut gain of flipping node i in state."""
161
+ b = state[i]
162
+ acc = 0.0
163
+ lo, hi = row_range(i, A, rows, G_func, nodes)
164
+ for k in range(lo, hi):
165
+ j, w = entry(k, i, A, data, cols, G_func, nodes)
166
+ if j != i:
167
+ acc += w if b == state[j] else -w
168
+ return acc
169
+
170
+
171
+ @njit(parallel=True, cache=True)
172
+ def gains(state, A, data, rows, cols, G_func, nodes):
173
+ n = state.shape[0]
174
+ g = np.empty(n, dtype=np.float64)
175
+ for i in prange(n):
176
+ g[i] = flip_gain(i, state, A, data, rows, cols, G_func, nodes)
177
+ return g
178
+
179
+
180
+ @njit(cache=True)
181
+ def best_single_flip(state, is_spin_glass, A, data, rows, cols, G_func, nodes):
182
+ """(gain, new state) of the best single-node flip."""
183
+ g = gains(state, A, data, rows, cols, G_func, nodes)
184
+ i = np.argmax(g)
185
+ out = state.copy()
186
+ out[i] = not out[i]
187
+ return (2.0 if is_spin_glass else 1.0) * g[i], out
188
+
189
+
190
+ @njit(parallel=True, cache=True)
191
+ def best_double_flip(state, is_spin_glass, A, data, rows, cols, G_func, nodes):
192
+ """(gain, new state) of the best two-node flip, over ALL pairs.
193
+
194
+ Flipping i and j gains g_i + g_j - 2 w_ij sigma_ij (sigma_ij = +1 if they
195
+ are on the same side), since edge (i, j) itself is unchanged. Dense and
196
+ streaming: O(n^2). Sparse: O(nnz + n log n), edges directly and
197
+ non-adjacent pairs via the sorted gains.
198
+ """
199
+ n = state.shape[0]
200
+ g = gains(state, A, data, rows, cols, G_func, nodes)
201
+ row_best = np.full(n, -np.inf)
202
+ row_j = np.zeros(n, dtype=np.int64)
203
+ for i in prange(n):
204
+ bi = state[i]
205
+ gi = g[i]
206
+ rb = -np.inf
207
+ rj = -1
208
+ lo, hi = row_range(i, A, rows, G_func, nodes)
209
+ for k in range(lo, hi):
210
+ j, w = entry(k, i, A, data, cols, G_func, nodes)
211
+ if j <= i:
212
+ continue
213
+ val = gi + g[j] - (2.0 * w if bi == state[j] else -2.0 * w)
214
+ if val > rb:
215
+ rb = val
216
+ rj = j
217
+ row_best[i] = rb
218
+ row_j[i] = rj
219
+
220
+ b = np.argmax(row_best)
221
+ best_val = row_best[b]
222
+ best_i = b
223
+ best_j = row_j[b]
224
+
225
+ nv, ni, nj = best_nonadjacent_pair(g, best_val, rows, cols, A, G_func)
226
+ if ni >= 0:
227
+ best_val = nv
228
+ best_i = ni
229
+ best_j = nj
230
+
231
+ out = state.copy()
232
+ if best_j >= 0:
233
+ out[best_i] = not out[best_i]
234
+ out[best_j] = not out[best_j]
235
+ else:
236
+ best_val = 0.0 # no pair at all (edgeless sparse graph of < 2 nodes)
237
+
238
+ return (2.0 if is_spin_glass else 1.0) * best_val, out
239
+
240
+
241
+ @njit(parallel=True, cache=True)
242
+ def pick_gray_seeds(state, thread_count, gray_seed_multiple, is_spin_glass, A, data, rows, cols, G_func, nodes):
243
+ """Gray-code mutations of state (64-bit blocks); returns the best
244
+ thread_count of them and their gains relative to state, best first."""
245
+ n = state.shape[0]
246
+ blocks = (n + 63) >> 6
247
+ block_size = thread_count * gray_seed_multiple
248
+ seed_count = block_size * blocks
249
+ scale = 2.0 if is_spin_glass else 1.0
250
+
251
+ seeds = np.empty((seed_count, n), dtype=np.bool_)
252
+ deltas = np.empty(seed_count, dtype=np.float64)
253
+
254
+ for s in prange(seed_count):
255
+ i = s % block_size
256
+ offset = (s // block_size) << 6
257
+ seed = gray_mutation(i, state, offset)
258
+ # apply the mutation one bit at a time, summing single-flip gains
259
+ work = state.copy()
260
+ d = 0.0
261
+ for k in range(n):
262
+ if seed[k] != state[k]:
263
+ d += flip_gain(k, work, A, data, rows, cols, G_func, nodes)
264
+ work[k] = not work[k]
265
+ deltas[s] = scale * d
266
+ seeds[s] = seed
267
+
268
+ tc = min(thread_count, seed_count)
269
+ indices = np.argsort(-deltas)[:tc]
270
+ best_seeds = np.empty((tc, n), dtype=np.bool_)
271
+ best_deltas = np.empty(tc, dtype=np.float64)
272
+ for i in range(tc):
273
+ best_seeds[i] = seeds[indices[i]]
274
+ best_deltas[i] = deltas[indices[i]]
275
+
276
+ return best_seeds, best_deltas
277
+
278
+
279
+ @njit(parallel=True, cache=True)
280
+ def gray_optimization(iterators, deltas, gray_iterations, is_spin_glass, A, data, rows, cols, G_func, nodes):
281
+ """Greedy Gray-code walk from each seed, keeping only improving flips.
282
+ deltas[i] is seed i's gain relative to the solver's current best state,
283
+ so the returned gain is relative to that state too."""
284
+ thread_count = iterators.shape[0]
285
+ n = iterators.shape[1]
286
+ thread_iterations = (gray_iterations + thread_count - 1) // thread_count
287
+ blocks = (n + 63) >> 6
288
+ scale = 2.0 if is_spin_glass else 1.0
289
+ totals = deltas.copy()
290
+
291
+ for t in prange(thread_count):
292
+ iterator = iterators[t]
293
+ cur = totals[t]
294
+ for curr_idx in range(thread_iterations):
295
+ for block in range(blocks):
296
+ flip_bit = gray_code_next(iterator, curr_idx, block << 6)
297
+ # gain of the flip just made = -(gain of flipping it back)
298
+ d = -scale * flip_gain(flip_bit, iterator, A, data, rows, cols, G_func, nodes)
299
+ if d > 0.0:
300
+ cur += d
301
+ else:
302
+ iterator[flip_bit] = not iterator[flip_bit]
303
+ totals[t] = cur
304
+
305
+ b = np.argmax(totals)
306
+ return totals[b], iterators[b].copy()
307
+
308
+
309
+ # ---------------------------------------------------------------------------
310
+ # Driver
311
+ # ---------------------------------------------------------------------------
312
+
313
+
314
+ def local_search(
315
+ best_theta,
316
+ is_spin_glass,
317
+ graph,
318
+ gray_iterations,
319
+ gray_seed_multiple,
320
+ deadline=float("inf"),
321
+ gpu_single=None,
322
+ gpu_double=None,
323
+ gpu_gray=None,
324
+ ):
325
+ """
326
+ The solvers' cascade: single flips, then double flips, then a Gray-code
327
+ search, then one "reheat" (single and double flips from the Gray-code
328
+ result even if it was worse), repeating while anything improves and the
329
+ deadline has not passed.
330
+
331
+ graph = (A, data, rows, cols, G_func, nodes) as described at the top.
332
+ gpu_* are optional callables theta -> (gain, new theta) that replace the
333
+ CPU kernels (gpu_gray may be None, e.g. above the GPU Gray node limit).
334
+ Returns the final state.
335
+ """
336
+ A, data, rows, cols, G_func, nodes = graph
337
+
338
+ def single(theta):
339
+ if gpu_single is not None:
340
+ return gpu_single(theta)
341
+ return best_single_flip(theta, is_spin_glass, A, data, rows, cols, G_func, nodes)
342
+
343
+ def double(theta):
344
+ if gpu_double is not None:
345
+ return gpu_double(theta)
346
+ return best_double_flip(theta, is_spin_glass, A, data, rows, cols, G_func, nodes)
347
+
348
+ thread_count = gray_seed_multiple
349
+ improved = True
350
+ while improved and time.perf_counter() < deadline:
351
+ improved = False
352
+
353
+ energy, state = single(best_theta)
354
+ if energy > 0.0:
355
+ best_theta = state
356
+ improved = True
357
+ continue
358
+
359
+ energy, state = double(best_theta)
360
+ if energy > 0.0:
361
+ best_theta = state
362
+ improved = True
363
+ continue
364
+
365
+ if gpu_gray is not None:
366
+ energy, state = gpu_gray(best_theta)
367
+ else:
368
+ seeds, seed_deltas = pick_gray_seeds(
369
+ best_theta, thread_count, gray_seed_multiple, is_spin_glass, A, data, rows, cols, G_func, nodes
370
+ )
371
+ if seed_deltas[0] > 0.0:
372
+ best_theta = seeds[0].copy()
373
+ improved = True
374
+ continue
375
+ energy, state = gray_optimization(seeds, seed_deltas, gray_iterations, is_spin_glass, A, data, rows, cols, G_func, nodes)
376
+ if energy > 0.0:
377
+ best_theta = state
378
+ improved = True
379
+ continue
380
+
381
+ # Post-reheat phase: continue from the Gray-code result even though it
382
+ # is not better, and accept if the combined move improves.
383
+ reheat_theta = state.copy()
384
+ reheat_energy = energy
385
+
386
+ energy, state = single(reheat_theta)
387
+ if (energy + reheat_energy) > 0.0:
388
+ best_theta = state
389
+ improved = True
390
+ continue
391
+
392
+ if energy > 0.0:
393
+ reheat_theta = state.copy()
394
+ reheat_energy += energy
395
+
396
+ energy, state = double(reheat_theta)
397
+ if (energy + reheat_energy) > 0.0:
398
+ best_theta = state
399
+ improved = True
400
+
401
+ return best_theta