PyQrackIsing 8.0.2__tar.gz → 8.1.0__tar.gz

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.
Files changed (30) hide show
  1. {pyqrackising-8.0.2/pyqrackising.egg-info → pyqrackising-8.1.0}/PKG-INFO +1 -1
  2. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/README.md +5 -5
  3. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyproject.toml +1 -1
  4. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising/maxcut_tfim.py +72 -25
  5. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising/maxcut_tfim_sparse.py +79 -34
  6. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising/maxcut_tfim_streaming.py +73 -27
  7. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising/maxcut_tfim_util.py +142 -163
  8. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising/spin_glass_solver.py +5 -5
  9. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising/spin_glass_solver_sparse.py +5 -5
  10. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising/spin_glass_solver_streaming.py +5 -5
  11. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising/tsp.py +25 -19
  12. {pyqrackising-8.0.2 → pyqrackising-8.1.0/pyqrackising.egg-info}/PKG-INFO +1 -1
  13. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/setup.py +1 -1
  14. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/CMakeLists.txt +0 -0
  15. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/LICENSE.md +0 -0
  16. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/MANIFEST.in +0 -0
  17. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising/__init__.py +0 -0
  18. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising/_pyqrack_ising.cpp +0 -0
  19. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising/convert_tensor_network_to_tsp.py +0 -0
  20. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising/generate_tfim_samples.py +0 -0
  21. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising/kernels.cl +0 -0
  22. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising/spin_glass_solver_util.py +0 -0
  23. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising/tfim_magnetization.py +0 -0
  24. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising/tfim_square_magnetization.py +0 -0
  25. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising/tsp_maxcut.py +0 -0
  26. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising.egg-info/SOURCES.txt +0 -0
  27. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising.egg-info/dependency_links.txt +0 -0
  28. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising.egg-info/not-zip-safe +0 -0
  29. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/pyqrackising.egg-info/top_level.txt +0 -0
  30. {pyqrackising-8.0.2 → pyqrackising-8.1.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrackising
3
- Version: 8.0.2
3
+ Version: 8.1.0
4
4
  Summary: Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)
5
5
  Home-page: https://github.com/vm6502q/PyQrackIsing
6
6
  Author: Dan Strano
@@ -50,10 +50,10 @@ from pyqrackising import maxcut_tfim
50
50
  import networkx as nx
51
51
 
52
52
  G = nx.petersen_graph()
53
- best_solution_bit_string, best_cut_value, best_node_groups = maxcut_tfim(G, quality=2, is_base_maxcut_gpu=True, is_alt_gpu_sampling=True)
53
+ best_solution_bit_string, best_cut_value, best_node_groups = maxcut_tfim(G, quality=5, shots=None, is_spin_glass=False, anneal_t=8.0, anneal_h=8.0)
54
54
  ```
55
55
 
56
- We also provide `maxcut_tfim_sparse(G)`, for `scipy` CSR sparse arrays (or `networkx` graphs). The (integer) `quality` setting is optional, with a default value of `2`, but you can turn it up for higher-quality results, or turn it down to save time. (You can also optionally specify the number of measurement `shots` as an argument, if you want specific fine-grained control over resource usage.) `is_base_maxcut_gpu` enables or disables GPU execution. `is_alt_gpu_sampling` is `False` by default and, if set to `True`, will dispatch almost the entire algorithm on GPU, instead of just the TFIM-heuristic component (although solution quality is often lower). If you want to run MAXCUT on a graph with non-uniform edge weights, specify them as the `weight` attribute of each edge, with `networkx`. (If any `weight` attribute is not defined, the solver assumes it's `1.0` for that edge.)
56
+ We also provide `maxcut_tfim_sparse(G)`, for `scipy` CSR sparse arrays (or `networkx` graphs), and `maxcut_tfim_streaming(G_func, nodes)` for `numba` JIT streaming weights function definitions. The (integer) `quality` setting is optional, with a default value of `5`, but you can turn it up for higher-quality results, or turn it down to save time. (You can also optionally specify the number of measurement `shots` as an argument, if you want specific fine-grained control over resource usage.) `anneal_t` and `anneal_h` control the physical maximum annealing time and `h` transverse field parameter, as in Trotterized Ising model. If you want to run MAXCUT on a graph with non-uniform edge weights, specify them as the `weight` attribute of each edge, with `networkx`. (If any `weight` attribute is not defined, the solver assumes it's `1.0` for that edge.)
57
57
 
58
58
  Based on a combination of the TFIM-inspired MAXCUT solver and another technique for finding ground-state energy in quantum chemistry that we call the _"binary Clifford eigensolver,"_ we also provide an (approximate) spin glass ground-state solver:
59
59
  ```py
@@ -73,12 +73,12 @@ def generate_spin_glass_graph(n_nodes=16, degree=3, seed=None):
73
73
 
74
74
 
75
75
  G = generate_spin_glass_graph(n_nodes=64, seed=42)
76
- solution_bit_string, cut_value, node_groups, energy = spin_glass_solver(G, quality=2, best_guess=None, is_base_maxcut_gpu=True, is_alt_gpu_sampling=True, is_combo_maxcut_gpu=True)
76
+ solution_bit_string, cut_value, node_groups, energy = spin_glass_solver(G, quality=5, shots=None, anneal_t=8.0, anneal_h=8.0, best_guess=None, is_combo_maxcut_gpu=True)
77
77
  # solution_bit_string, cut_value, node_groups, energy = spin_glass_solver(G, best_guess=maxcut_tfim(G, quality=6)[0])
78
78
  ```
79
- We also provide `spin_glass_solver_sparse(G)`, for `scipy` (32-bit) **upper-triangular** CSR sparse arrays (or `networkx` graphs). The (integer) default `quality` setting is `2`. `is_combo_maxcut_gpu` controls whether gradient descent optimization is done on GPU (which is the most costly GPU-based feature), while `is_base_maxcut_gpu` is passed through the underlying `maxcut_tfim(G)` solver. `best_guess` gives the option to seed the algorithm with a best guess as to the maximal cut (as an integer, binary string, or list of booleans). By default, `spin_glass_solver()` uses `maxcut_tfim(G)` with passed-through `quality` as `best_guess`, which typically works well, but it could be seeded with higher `maxcut_tfim()` `quality` or Goemans-Williamson, for example. This function is designed with a sign convention for weights such that it can immediately be used as a MAXCUT solver itself: you might need to reverse the sign convention on your weights for spin glass graphs, but this is only convention.
79
+ We also provide `spin_glass_solver_sparse(G)` and `spin_glass_solver_streaming(G_func, nodes)`. `is_combo_maxcut_gpu` controls whether gradient descent optimization is done on GPU (which is costly and the only GPU-based feature). `best_guess` gives the option to seed the algorithm with a best guess as to the maximal cut (as an integer, binary string, or list of booleans). By default, `spin_glass_solver()` uses `maxcut_tfim(G)` with passed-through `quality` as `best_guess`, which typically works well, but it could be seeded with higher `maxcut_tfim()` `quality` or Goemans-Williamson, for example. This function is designed with a sign convention for weights such that it can immediately be used as a MAXCUT solver itself: you might need to reverse the sign convention on your weights for spin glass graphs, but this is only convention.
80
80
 
81
- From the `spin_glass_solver()`, we provide a (recursive) Traveling Salesman Problem (TSP) solver:
81
+ From the MAXCUT solvers, we provide a (recursive) Traveling Salesman Problem (TSP) solver:
82
82
  ```py
83
83
  from pyqrackising import tsp_symmetric
84
84
  import networkx as nx
@@ -12,7 +12,7 @@ build-backend = "setuptools.build_meta"
12
12
 
13
13
  [project]
14
14
  name = "pyqrackising"
15
- version = "8.0.2"
15
+ version = "8.1.0"
16
16
  requires-python = ">=3.8"
17
17
  description = "Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)"
18
18
  readme = {file = "README.txt", content-type = "text/markdown"}
@@ -4,10 +4,11 @@ import numpy as np
4
4
  import os
5
5
  from numba import njit, prange
6
6
 
7
- from .maxcut_tfim_util import fix_cdf, get_cut, init_theta, init_thresholds, maxcut_hamming_cdf, opencl_context
7
+ from .maxcut_tfim_util import get_cut, maxcut_hamming_cdf, opencl_context
8
8
 
9
9
 
10
10
  epsilon = opencl_context.epsilon
11
+ dtype = opencl_context.dtype
11
12
 
12
13
 
13
14
  @njit
@@ -120,8 +121,19 @@ def compute_energy(sample, G_m, n_qubits):
120
121
  return energy
121
122
 
122
123
 
124
+ @njit
125
+ def compute_cut(sample, G_m, n_qubits):
126
+ cut = 0
127
+ for u in range(n_qubits):
128
+ for v in range(u + 1, n_qubits):
129
+ if sample[u] != sample[v]:
130
+ cut += G_m[u, v]
131
+
132
+ return cut
133
+
134
+
123
135
  @njit(parallel=True)
124
- def sample_for_solution(G_m, shots, thresholds, weights, dtype):
136
+ def sample_for_energy(G_m, shots, thresholds, weights):
125
137
  shots = max(1, shots >> 1)
126
138
  n = len(G_m)
127
139
  max_edge = G_m.max()
@@ -156,44 +168,74 @@ def sample_for_solution(G_m, shots, thresholds, weights, dtype):
156
168
  best_solution = solutions[best_index].copy()
157
169
  improved = True
158
170
 
159
- best_value = 0.0
160
- for u in range(n):
161
- for v in range(u + 1, n):
162
- if best_solution[u] != best_solution[v]:
163
- best_value += G_m[u, v]
171
+ return best_solution, compute_cut(best_solution, G_m, n)
172
+
173
+
174
+ @njit(parallel=True)
175
+ def sample_for_cut(G_m, shots, thresholds, weights):
176
+ shots = max(1, shots >> 1)
177
+ n = len(G_m)
178
+ max_edge = G_m.max()
179
+ tot_init_weight = weights.sum()
180
+
181
+ solutions = np.empty((shots, n), dtype=np.bool_)
182
+ cuts = np.empty(shots, dtype=dtype)
183
+
184
+ best_solution = solutions[0]
185
+ best_cut = -float("inf")
186
+
187
+ improved = True
188
+ while improved:
189
+ improved = False
190
+ for s in prange(shots):
191
+ # First dimension: Hamming weight
192
+ mag_prob = np.random.random()
193
+ m = 0
194
+ while thresholds[m] < mag_prob:
195
+ m += 1
196
+ m += 1
197
+
198
+ # Second dimension: permutation within Hamming weight
199
+ sample = local_repulsion_choice(G_m, max_edge, weights, tot_init_weight, n, m)
200
+ solutions[s] = sample
201
+ cuts[s] = compute_cut(sample, G_m, n)
164
202
 
165
- return best_solution, best_value
203
+ best_index = np.argmax(cuts)
204
+ cut = cuts[best_index]
205
+ if cut > best_cut:
206
+ best_cut = cut
207
+ best_solution = solutions[best_index].copy()
208
+ improved = True
209
+
210
+ return best_solution, best_cut
166
211
 
167
212
 
168
213
  @njit(parallel=True)
169
- def init_J_and_z(G_m, dtype):
214
+ def init_J_and_z(G_m):
170
215
  n_qubits = len(G_m)
171
216
  degrees = np.empty(n_qubits, dtype=np.uint32)
172
217
  J_eff = np.empty(n_qubits, dtype=dtype)
173
- J_max = -float("inf")
174
218
  for n in prange(n_qubits):
175
219
  degree = sum(G_m[n] != 0.0)
176
220
  J = (-G_m[n].sum() / degree) if degree > 0 else 0
177
221
  degrees[n] = degree
178
222
  J_eff[n] = J
179
- J_abs = abs(J)
180
- J_max = max(J_abs, J_max)
181
- J_eff /= J_max
182
223
 
183
224
  return J_eff, degrees
184
225
 
185
226
 
186
227
  @njit
187
- def cpu_footer(shots, quality, n_qubits, G_m, nodes, dtype):
188
- J_eff, degrees = init_J_and_z(G_m, dtype)
189
- hamming_prob = init_thresholds(n_qubits, dtype)
190
-
191
- maxcut_hamming_cdf(n_qubits, J_eff, degrees, quality, hamming_prob, dtype)
228
+ def cpu_footer(shots, quality, n_qubits, G_m, nodes, is_spin_glass, anneal_t, anneal_h):
229
+ J_eff, degrees = init_J_and_z(G_m)
230
+ hamming_prob = maxcut_hamming_cdf(n_qubits, J_eff, degrees, quality, anneal_t, anneal_h)
192
231
 
193
232
  degrees = None
194
233
  J_eff = 1.0 / (1.0 + epsilon - J_eff)
195
234
 
196
- best_solution, best_value = sample_for_solution(G_m, shots, hamming_prob, J_eff, dtype)
235
+ if is_spin_glass:
236
+ best_solution, best_value = sample_for_energy(G_m, shots, hamming_prob, J_eff)
237
+ else:
238
+ best_solution, best_value = sample_for_cut(G_m, shots, hamming_prob, J_eff)
197
239
 
198
240
  bit_string, l, r = get_cut(best_solution, nodes)
199
241
 
@@ -203,9 +245,11 @@ def cpu_footer(shots, quality, n_qubits, G_m, nodes, dtype):
203
245
  def maxcut_tfim(
204
246
  G,
205
247
  quality=None,
206
- shots=None
248
+ shots=None,
249
+ is_spin_glass=False,
250
+ anneal_t=None,
251
+ anneal_h=None
207
252
  ):
208
- dtype = opencl_context.dtype
209
253
  wgs = opencl_context.work_group_size
210
254
  nodes = None
211
255
  n_qubits = 0
@@ -234,13 +278,16 @@ def maxcut_tfim(
234
278
  return "01", weight, ([nodes[0]], [nodes[1]])
235
279
 
236
280
  if quality is None:
237
- quality = 2
281
+ quality = 5
238
282
 
239
283
  if shots is None:
240
284
  # Number of measurement shots
241
285
  shots = n_qubits << quality
242
286
 
243
- n_steps = n_qubits << quality
244
- grid_size = n_steps * n_qubits
287
+ if anneal_t is None:
288
+ anneal_t = 8.0
289
+
290
+ if anneal_h is None:
291
+ anneal_h = 8.0
245
292
 
246
- return cpu_footer(shots, quality, n_qubits, G_m, nodes, dtype)
293
+ return cpu_footer(shots, quality, n_qubits, G_m, nodes, is_spin_glass, anneal_t, anneal_h)
@@ -4,10 +4,11 @@ import numpy as np
4
4
  import os
5
5
  from numba import njit, prange
6
6
 
7
- from .maxcut_tfim_util import binary_search, fix_cdf, get_cut, init_theta, init_thresholds, maxcut_hamming_cdf, opencl_context, to_scipy_sparse_upper_triangular
7
+ from .maxcut_tfim_util import binary_search, get_cut, maxcut_hamming_cdf, opencl_context, to_scipy_sparse_upper_triangular
8
8
 
9
9
 
10
10
  epsilon = opencl_context.epsilon
11
+ dtype = opencl_context.dtype
11
12
 
12
13
 
13
14
  @njit
@@ -120,8 +121,7 @@ def local_repulsion_choice(G_cols, G_data, G_rows, max_edge, weights, tot_init_w
120
121
 
121
122
 
122
123
  @njit
123
- def compute_energy(sample, G_data, G_rows, G_cols):
124
- n_qubits = G_rows.shape[0] - 1
124
+ def compute_energy(sample, G_data, G_rows, G_cols, n_qubits):
125
125
  energy = 0
126
126
  for u in range(n_qubits):
127
127
  for col in range(G_rows[u], G_rows[u + 1]):
@@ -132,8 +132,20 @@ def compute_energy(sample, G_data, G_rows, G_cols):
132
132
  return energy
133
133
 
134
134
 
135
+ @njit
136
+ def compute_cut(sample, G_data, G_rows, G_cols, n_qubits):
137
+ cut = 0
138
+ for u in range(n_qubits):
139
+ for col in range(G_rows[u], G_rows[u + 1]):
140
+ v = G_cols[col]
141
+ if sample[u] != sample[v]:
142
+ cut += G_data[col]
143
+
144
+ return cut
145
+
146
+
135
147
  @njit(parallel=True)
136
- def sample_for_solution(G_data, G_rows, G_cols, shots, thresholds, weights, dtype):
148
+ def sample_for_energy(G_data, G_rows, G_cols, shots, thresholds, weights):
137
149
  shots = max(1, shots >> 1)
138
150
  n = G_rows.shape[0] - 1
139
151
  max_edge = G_data.max()
@@ -159,7 +171,7 @@ def sample_for_solution(G_data, G_rows, G_cols, shots, thresholds, weights, dtyp
159
171
  # Second dimension: permutation within Hamming weight
160
172
  sample = local_repulsion_choice(G_cols, G_data, G_rows, max_edge, weights, tot_init_weight, n, m)
161
173
  solutions[s] = sample
162
- energies[s] = compute_energy(sample, G_data, G_rows, G_cols)
174
+ energies[s] = compute_energy(sample, G_data, G_rows, G_cols, n)
163
175
 
164
176
  best_index = np.argmin(energies)
165
177
  energy = energies[best_index]
@@ -168,21 +180,53 @@ def sample_for_solution(G_data, G_rows, G_cols, shots, thresholds, weights, dtyp
168
180
  best_solution = solutions[best_index].copy()
169
181
  improved = True
170
182
 
171
- best_value = 0.0
172
- for u in range(n):
173
- for col in range(G_rows[u], G_rows[u + 1]):
174
- v = G_cols[col]
175
- if best_solution[u] != best_solution[v]:
176
- best_value += G_data[col]
183
+ return best_solution, compute_cut(best_solution, G_data, G_rows, G_cols, n)
184
+
185
+
186
+ @njit(parallel=True)
187
+ def sample_for_cut(G_data, G_rows, G_cols, shots, thresholds, weights):
188
+ shots = max(1, shots >> 1)
189
+ n = G_rows.shape[0] - 1
190
+ max_edge = G_data.max()
191
+ tot_init_weight = weights.sum()
192
+
193
+ solutions = np.empty((shots, n), dtype=np.bool_)
194
+ cuts = np.empty(shots, dtype=dtype)
195
+
196
+ best_solution = solutions[0]
197
+ best_cut = -float("inf")
177
198
 
178
- return best_solution, best_value
199
+ improved = True
200
+ while improved:
201
+ improved = False
202
+ for s in prange(shots):
203
+ # First dimension: Hamming weight
204
+ mag_prob = np.random.random()
205
+ m = 0
206
+ while thresholds[m] < mag_prob:
207
+ m += 1
208
+ m += 1
209
+
210
+ # Second dimension: permutation within Hamming weight
211
+ sample = local_repulsion_choice(G_cols, G_data, G_rows, max_edge, weights, tot_init_weight, n, m)
212
+ solutions[s] = sample
213
+ cuts[s] = compute_cut(sample, G_data, G_rows, G_cols, n)
214
+
215
+ best_index = np.argmax(cuts)
216
+ cut = cuts[best_index]
217
+ if cut > best_cut:
218
+ best_cut = cut
219
+ best_solution = solutions[best_index].copy()
220
+ improved = True
221
+
222
+ return best_solution, best_cut
179
223
 
180
224
 
181
225
  @njit(parallel=True)
182
- def init_J_and_z(G_data, G_rows, G_cols, dtype):
226
+ def init_J_and_z(G_data, G_rows, G_cols):
183
227
  n_qubits = G_rows.shape[0] - 1
184
- degrees = np.empty(n_qubits, dtype=np.uint32)
185
- J_eff = np.empty(n_qubits, dtype=dtype)
228
+ degrees = np.zeros(n_qubits, dtype=np.uint32)
229
+ J_eff = np.zeros(n_qubits, dtype=dtype)
186
230
  for r in prange(n_qubits):
187
231
  # Row sum
188
232
  start = G_rows[r]
@@ -199,29 +243,25 @@ def init_J_and_z(G_data, G_rows, G_cols, dtype):
199
243
  degrees[c] += 1
200
244
  J_eff[c] += G_data[idx]
201
245
 
202
- J_max = -float("inf")
203
246
  for r in prange(n_qubits):
204
- J = J_eff[r]
205
247
  degree = degrees[r]
206
- J_eff[r] = -J / degree if degree > 0 else 0
207
- J_abs = abs(J)
208
- J_max = max(J_abs, J_max)
209
- J_eff /= J_max
248
+ J_eff[r] = -J_eff[r] / degree if degree > 0 else 0
210
249
 
211
250
  return J_eff, degrees
212
251
 
213
252
 
214
253
  @njit
215
- def cpu_footer(shots, quality, n_qubits, G_data, G_rows, G_col, nodes, dtype):
216
- J_eff, degrees = init_J_and_z(G_data, G_rows, G_col, dtype)
217
- hamming_prob = init_thresholds(n_qubits, dtype)
218
-
219
- maxcut_hamming_cdf(n_qubits, J_eff, degrees, quality, hamming_prob, dtype)
254
+ def cpu_footer(shots, quality, n_qubits, G_data, G_rows, G_col, nodes, is_spin_glass, anneal_t, anneal_h):
255
+ J_eff, degrees = init_J_and_z(G_data, G_rows, G_col)
256
+ hamming_prob = maxcut_hamming_cdf(n_qubits, J_eff, degrees, quality, anneal_t, anneal_h)
220
257
 
221
258
  degrees = None
222
259
  J_eff = 1.0 / (1.0 + epsilon - J_eff)
223
260
 
224
- best_solution, best_value = sample_for_solution(G_data, G_rows, G_col, shots, hamming_prob, J_eff, dtype)
261
+ if is_spin_glass:
262
+ best_solution, best_value = sample_for_energy(G_data, G_rows, G_col, shots, hamming_prob, J_eff)
263
+ else:
264
+ best_solution, best_value = sample_for_cut(G_data, G_rows, G_col, shots, hamming_prob, J_eff)
225
265
 
226
266
  bit_string, l, r = get_cut(best_solution, nodes)
227
267
 
@@ -231,9 +271,11 @@ def cpu_footer(shots, quality, n_qubits, G_data, G_rows, G_col, nodes, dtype):
231
271
  def maxcut_tfim_sparse(
232
272
  G,
233
273
  quality=None,
234
- shots=None
274
+ shots=None,
275
+ is_spin_glass=False,
276
+ anneal_t=None,
277
+ anneal_h=None
235
278
  ):
236
- dtype = opencl_context.dtype
237
279
  wgs = opencl_context.work_group_size
238
280
  nodes = None
239
281
  n_qubits = 0
@@ -241,7 +283,7 @@ def maxcut_tfim_sparse(
241
283
  if isinstance(G, nx.Graph):
242
284
  nodes = list(G.nodes())
243
285
  n_qubits = len(nodes)
244
- G_m = to_scipy_sparse_upper_triangular(G, nodes, n_qubits, dtype)
286
+ G_m = to_scipy_sparse_upper_triangular(G, nodes, n_qubits)
245
287
  else:
246
288
  n_qubits = G.shape[0]
247
289
  nodes = list(range(n_qubits))
@@ -262,13 +304,16 @@ def maxcut_tfim_sparse(
262
304
  return "01", weight, ([nodes[0]], [nodes[1]])
263
305
 
264
306
  if quality is None:
265
- quality = 2
307
+ quality = 5
266
308
 
267
309
  if shots is None:
268
310
  # Number of measurement shots
269
311
  shots = n_qubits << quality
270
312
 
271
- n_steps = n_qubits << quality
272
- grid_size = n_steps * n_qubits
313
+ if anneal_t is None:
314
+ anneal_t = 8.0
315
+
316
+ if anneal_h is None:
317
+ anneal_h = 8.0
273
318
 
274
- return cpu_footer(shots, quality, n_qubits, G_m.data, G_m.indptr, G_m.indices, nodes, dtype)
319
+ return cpu_footer(shots, quality, n_qubits, G_m.data, G_m.indptr, G_m.indices, nodes, is_spin_glass, anneal_t, anneal_h)
@@ -4,10 +4,11 @@ import numpy as np
4
4
  import os
5
5
  from numba import njit, prange
6
6
 
7
- from .maxcut_tfim_util import fix_cdf, get_cut, init_theta, init_thresholds, maxcut_hamming_cdf, opencl_context, probability_by_hamming_weight
7
+ from .maxcut_tfim_util import get_cut, maxcut_hamming_cdf, opencl_context
8
8
 
9
9
 
10
10
  epsilon = opencl_context.epsilon
11
+ dtype = opencl_context.dtype
11
12
 
12
13
 
13
14
  @njit
@@ -121,8 +122,19 @@ def compute_energy(sample, G_func, nodes, n_qubits):
121
122
  return energy
122
123
 
123
124
 
125
+ @njit
126
+ def compute_cut(sample, G_func, nodes, n_qubits):
127
+ cut = 0
128
+ for u in range(n_qubits):
129
+ for v in range(u + 1, n_qubits):
130
+ if sample[u] != sample[v]:
131
+ cut += G_func(nodes[u], nodes[v])
132
+
133
+ return cut
134
+
135
+
124
136
  @njit(parallel=True)
125
- def sample_for_solution(G_func, nodes, max_edge, shots, thresholds, degrees_sum, weights, n, dtype):
137
+ def sample_for_energy(G_func, nodes, max_edge, shots, thresholds, degrees_sum, weights, n):
126
138
  shots = max(1, shots >> 1)
127
139
  tot_init_weight = weights.sum()
128
140
 
@@ -155,21 +167,51 @@ def sample_for_solution(G_func, nodes, max_edge, shots, thresholds, degrees_sum,
155
167
  best_solution = solutions[best_index].copy()
156
168
  improved = True
157
169
 
158
- best_value = 0.0
159
- for u in range(n):
160
- for v in range(u + 1, n):
161
- if best_solution[u] != best_solution[v]:
162
- best_value += G_func(nodes[u], nodes[v])
170
+ return best_solution, compute_cut(best_solution, G_func, nodes, n)
163
171
 
164
- return best_solution, best_value
172
+
173
+ @njit(parallel=True)
174
+ def sample_for_cut(G_func, nodes, max_edge, shots, thresholds, degrees_sum, weights, n):
175
+ shots = max(1, shots >> 1)
176
+ tot_init_weight = weights.sum()
177
+
178
+ solutions = np.empty((shots, n), dtype=np.bool_)
179
+ cuts = np.empty(shots, dtype=dtype)
180
+
181
+ best_solution = solutions[0]
182
+ best_cut = -float("inf")
183
+
184
+ improved = True
185
+ while improved:
186
+ improved = False
187
+ for s in prange(shots):
188
+ # First dimension: Hamming weight
189
+ mag_prob = np.random.random()
190
+ m = 0
191
+ while thresholds[m] < mag_prob:
192
+ m += 1
193
+ m += 1
194
+
195
+ # Second dimension: permutation within Hamming weight
196
+ sample = local_repulsion_choice(G_func, nodes, max_edge, weights, tot_init_weight, n, m)
197
+ solutions[s] = sample
198
+ cuts[s] = compute_cut(sample, G_func, nodes, n)
199
+
200
+ best_index = np.argmax(cuts)
201
+ cut = cuts[best_index]
202
+ if cut > best_cut:
203
+ best_cut = cut
204
+ best_solution = solutions[best_index].copy()
205
+ improved = True
206
+
207
+ return best_solution, best_cut
165
208
 
166
209
 
167
210
  @njit(parallel=True)
168
- def init_J_and_z(G_func, nodes, dtype):
211
+ def init_J_and_z(G_func, nodes):
169
212
  n_qubits = len(nodes)
170
213
  degrees = np.empty(n_qubits, dtype=np.uint32)
171
214
  J_eff = np.empty(n_qubits, dtype=dtype)
172
- J_max = -float("inf")
173
215
  G_max = -float("inf")
174
216
  for n in prange(n_qubits):
175
217
  degree = 0
@@ -179,29 +221,28 @@ def init_J_and_z(G_func, nodes, dtype):
179
221
  if val != 0.0:
180
222
  degree += 1
181
223
  J += val
182
- G_max = max(val, G_max)
224
+ if val > G_max:
225
+ G_max = val
183
226
  J = -J / degree if degree > 0 else 0
184
227
  degrees[n] = degree
185
228
  J_eff[n] = J
186
- J_abs = abs(J)
187
- J_max = max(J_abs, J_max)
188
- J_eff /= J_max
189
229
 
190
230
  return J_eff, degrees, G_max
191
231
 
192
232
 
193
233
  @njit
194
- def cpu_footer(shots, quality, n_qubits, G_func, nodes, dtype):
195
- J_eff, degrees, G_max = init_J_and_z(G_func, nodes, dtype)
196
- hamming_prob = init_thresholds(n_qubits, dtype)
234
+ def cpu_footer(shots, quality, n_qubits, G_func, nodes, is_spin_glass, anneal_t, anneal_h):
235
+ J_eff, degrees, G_max = init_J_and_z(G_func, nodes)
236
+ hamming_prob = maxcut_hamming_cdf(n_qubits, J_eff, degrees, quality, anneal_t, anneal_h)
197
237
  max_edge = degrees.sum()
198
238
 
199
- maxcut_hamming_cdf(n_qubits, J_eff, degrees, quality, hamming_prob, dtype)
200
-
201
239
  degrees = None
202
240
  J_eff = 1.0 / (1.0 + epsilon - J_eff)
203
241
 
204
- best_solution, best_value = sample_for_solution(G_func, nodes, G_max, shots, hamming_prob, max_edge, J_eff, n_qubits, dtype)
242
+ if is_spin_glass:
243
+ best_solution, best_value = sample_for_energy(G_func, nodes, G_max, shots, hamming_prob, max_edge, J_eff, n_qubits)
244
+ else:
245
+ best_solution, best_value = sample_for_cut(G_func, nodes, G_max, shots, hamming_prob, max_edge, J_eff, n_qubits)
205
246
 
206
247
  bit_string, l, r = get_cut(best_solution, nodes)
207
248
 
@@ -212,9 +253,11 @@ def maxcut_tfim_streaming(
212
253
  G_func,
213
254
  nodes,
214
255
  quality=None,
215
- shots=None
256
+ shots=None,
257
+ is_spin_glass=False,
258
+ anneal_t=None,
259
+ anneal_h=None
216
260
  ):
217
- dtype = opencl_context.dtype
218
261
  wgs = opencl_context.work_group_size
219
262
  n_qubits = len(nodes)
220
263
 
@@ -233,13 +276,16 @@ def maxcut_tfim_streaming(
233
276
  return "01", weight, ([nodes[0]], [nodes[1]])
234
277
 
235
278
  if quality is None:
236
- quality = 2
279
+ quality = 5
280
+
281
+ if anneal_t is None:
282
+ anneal_t = 8.0
283
+
284
+ if anneal_h is None:
285
+ anneal_h = 8.0
237
286
 
238
287
  if shots is None:
239
288
  # Number of measurement shots
240
289
  shots = n_qubits << quality
241
290
 
242
- n_steps = n_qubits << quality
243
- grid_size = n_steps * n_qubits
244
-
245
- return cpu_footer(shots, quality, n_qubits, G_func, nodes, dtype)
291
+ return cpu_footer(shots, quality, n_qubits, G_func, nodes, is_spin_glass, anneal_t, anneal_h)
@@ -6,6 +6,105 @@ from numba import njit, prange
6
6
  from scipy.sparse import lil_matrix
7
7
 
8
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
+
9
108
  @njit
10
109
  def get_cut(solution, nodes):
11
110
  bit_string = ""
@@ -40,8 +139,8 @@ def binary_search(l, t):
40
139
  return len(l)
41
140
 
42
141
 
43
- def to_scipy_sparse_upper_triangular(G, nodes, n_nodes, dtype):
44
- lil = lil_matrix((n_nodes, n_nodes), dtype=opencl_context.dtype)
142
+ def to_scipy_sparse_upper_triangular(G, nodes, n_nodes):
143
+ lil = lil_matrix((n_nodes, n_nodes), dtype=dtype)
45
144
  for u in range(n_nodes):
46
145
  u_node = nodes[u]
47
146
  for v in range(u + 1, n_nodes):
@@ -53,27 +152,20 @@ def to_scipy_sparse_upper_triangular(G, nodes, n_nodes, dtype):
53
152
 
54
153
 
55
154
  @njit(parallel=True)
56
- def init_theta(h_mult, n_qubits, J_eff, degrees, dtype):
155
+ def init_theta(h_mult, n_qubits, J_eff, degrees):
57
156
  theta = np.empty(n_qubits, dtype=dtype)
58
157
  h_mult = abs(h_mult)
59
158
  for q in prange(n_qubits):
60
159
  J = J_eff[q]
61
160
  z = degrees[q]
62
- theta[q] = np.arcsin(
63
- max(
64
- -1.0,
65
- min(
66
- 1.0,
67
- np.sign(J) if np.isclose(abs(z * J), 0.0) else (h_mult / (z * J)),
68
- ),
69
- )
70
- )
161
+ abs_zJ = abs(z * J)
162
+ theta[q] = (np.pi if J > 0 else -np.pi) if abs_zJ < epsilon else np.arcsin(max(-1.0, min(1.0, h_mult / (z * J))))
71
163
 
72
164
  return theta
73
165
 
74
166
 
75
167
  @njit
76
- def init_thresholds(n_qubits, dtype):
168
+ def init_thresholds(n_qubits):
77
169
  n_bias = n_qubits - 1
78
170
  thresholds = np.empty(n_bias, dtype=dtype)
79
171
  tot_prob = 0
@@ -93,45 +185,64 @@ def init_thresholds(n_qubits, dtype):
93
185
  return thresholds
94
186
 
95
187
 
188
+ @njit
189
+ def probability_by_hamming_weight(J, h, z, theta, t, n_qubits):
190
+ if abs(J) < epsilon:
191
+ return np.full((n_qubits - 1,), 1.0 / (n_qubits - 1), dtype=dtype)
192
+
193
+ ratio = max(1.0, min(-1.0, abs(h) / (z * J)))
194
+ theta_c = np.arcsin(ratio)
195
+
196
+ p = (
197
+ pow(2.0, abs(J / h) - 1.0)
198
+ * (1.0 + np.sin(theta - theta_c) * np.cos(1.5 * np.pi * J * t + theta) / (1.0 + np.sqrt(t)))
199
+ - 0.5
200
+ )
201
+
202
+ numerator = pow(2.0, (n_qubits + 2) * p) - 1.0
203
+ denominator = pow(2.0, p) - 1.0
204
+
205
+ bias = np.empty(n_qubits - 1, dtype=dtype)
206
+ for q in range(n_qubits - 1):
207
+ result = numerator * pow(2.0, -((n_qubits + 1) * p) - p * q) / denominator
208
+ bias[q] = 0.0 if np.isnan(result) or np.isinf(result) else result
209
+
210
+ if J > 0.0:
211
+ return bias[::-1]
212
+
213
+ return bias
214
+
215
+
96
216
  @njit(parallel=True)
97
- def maxcut_hamming_cdf(n_qubits, J_func, degrees, quality, hamming_prob, dtype):
217
+ def maxcut_hamming_cdf(n_qubits, J_func, degrees, quality, tot_t, h_mult):
98
218
  if n_qubits < 2:
99
- hamming_prob.fill(0.0)
100
- return
219
+ return np.full((n_qubits,), 1.0 / n_qubits, dtype=dtype)
220
+
221
+ hamming_prob = init_thresholds(n_qubits)
101
222
 
102
223
  n_steps = 1 << quality
103
224
  delta_t = 1.0 / n_steps
104
- tot_t = 2.0 * n_steps * delta_t
105
- h_mult = 2.0 / tot_t
106
225
  n_bias = n_qubits - 1
107
226
 
108
- theta = init_theta(h_mult, n_qubits, J_func, degrees, dtype)
227
+ theta = init_theta(h_mult, n_qubits, J_func, degrees)
109
228
 
110
229
  for qc in prange(n_qubits, n_steps * n_qubits):
111
230
  step = qc // n_qubits
112
231
  q = qc % n_qubits
113
232
  J_eff = J_func[q]
114
- if np.isclose(abs(J_eff), 0.0):
115
- continue
116
233
  z = degrees[q]
117
234
  theta_eff = theta[q]
118
235
  t = step * delta_t
119
236
  tm1 = (step - 1) * delta_t
120
237
  h_t = h_mult * (tot_t - t)
121
- bias = probability_by_hamming_weight(J_eff, h_t, z, theta_eff, t, n_qubits, dtype)
122
- last_bias = probability_by_hamming_weight(J_eff, h_t, z, theta_eff, tm1, n_qubits, dtype)
238
+ bias = probability_by_hamming_weight(J_eff, h_t, z, theta_eff, t, n_qubits)
239
+ last_bias = probability_by_hamming_weight(J_eff, h_t, z, theta_eff, tm1, n_qubits)
123
240
  for i in range(n_bias):
124
241
  hamming_prob[i] += bias[i] - last_bias[i]
125
242
 
126
- tot_prob = hamming_prob.sum()
127
- hamming_prob /= tot_prob
128
-
129
- tot_prob = 0.0
130
- for i in range(n_bias):
131
- tot_prob += hamming_prob[i]
132
- hamming_prob[i] = tot_prob
133
- hamming_prob[-1] = 2.0
243
+ fix_cdf(hamming_prob)
134
244
 
245
+ return hamming_prob
135
246
 
136
247
  @njit
137
248
  def fix_cdf(hamming_prob):
@@ -142,135 +253,3 @@ def fix_cdf(hamming_prob):
142
253
  hamming_prob[i] = tot_prob
143
254
  hamming_prob[-1] = 2.0
144
255
 
145
-
146
- @njit
147
- def probability_by_hamming_weight(J, h, z, theta, t, n_qubits, dtype):
148
- # critical angle
149
- theta_c = np.arcsin(max(-1.0, min(1.0, abs(h) / (z * J))))
150
-
151
- p = (
152
- pow(2.0, abs(J / h) - 1.0)
153
- * (1.0 + np.sin(theta - theta_c) * np.cos(1.5 * np.pi * J * t + theta) / (1.0 + np.sqrt(t)))
154
- - 0.5
155
- )
156
-
157
- if (p * n_qubits) >= 1024:
158
- return np.zeros(n_qubits - 1, dtype=dtype)
159
-
160
- bias = np.empty(n_qubits - 1, dtype=dtype)
161
- tot_n = 1.0 + 1.0 / pow(2.0, p * n_qubits)
162
- factor = pow(2.0, -p)
163
- n = 1.0
164
- for q in range(1, n_qubits):
165
- n *= factor
166
- bias[q - 1] = n
167
- tot_n += n
168
-
169
- if np.isnan(tot_n) or np.isinf(tot_n):
170
- return np.zeros(n_qubits - 1, dtype=dtype)
171
-
172
- bias /= tot_n
173
-
174
- if J > 0.0:
175
- return bias[::-1]
176
-
177
- return bias
178
-
179
-
180
- class OpenCLContext:
181
- def __init__(self, p, a, w, d, e, r, c, q, b, s, x, y):
182
- self.MAX_GPU_PROC_ELEM = p
183
- self.IS_OPENCL_AVAILABLE = a
184
- self.work_group_size = w
185
- self.dtype = d
186
- self.epsilon = e
187
- self.max_alloc = r
188
- self.ctx = c
189
- self.queue = q
190
- self.bootstrap_kernel = b
191
- self.bootstrap_sparse_kernel = s
192
- self.bootstrap_segmented_kernel = x
193
- self.bootstrap_sparse_segmented_kernel = y
194
- self.G_m_buf = None
195
- self.G_data_buf = None
196
- self.G_rows_buf = None
197
- self.G_cols_buf = None
198
-
199
- IS_OPENCL_AVAILABLE = True
200
- ctx = None
201
- queue = None
202
- compute_units = None
203
- dtype = np.float32
204
- epsilon = 2 ** -23
205
- work_group_size = 32
206
- max_alloc = 0xFFFFFFFFFFFFFFFF
207
- bootstrap_kernel = None
208
- bootstrap_sparse_kernel = None
209
- bootstrap_segmented_kernel = None
210
- bootstrap_sparse_segmented_kernel = None
211
-
212
- dtype_bits = int(os.getenv('PYQRACKISING_FPPOW', '5'))
213
- kernel_src = ''
214
- if dtype_bits <= 4:
215
- dtype = np.float16
216
- epsilon = 2 ** -10
217
- kernel_src += "#pragma OPENCL EXTENSION cl_khr_fp16 : enable\n"
218
- kernel_src += "#define FP16 1\n"
219
- kernel_src += "#define real1 half\n"
220
- kernel_src += "#define qint short\n"
221
- kernel_src += "#define EPSILON ((half)0.00097656f)\n"
222
- kernel_src += "#define ZERO_R1 ((half)0.0f)\n"
223
- kernel_src += "#define ONE_R1 ((half)1.0f)\n"
224
- kernel_src += "#define TWO_R1 ((half)2.0f)\n"
225
- elif dtype_bits >= 6:
226
- dtype = np.float64
227
- epsilon = 2 ** -52
228
- kernel_src += "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"
229
- kernel_src += "#define real1 double\n"
230
- kernel_src += "#define qint long\n"
231
- kernel_src += "#define EPSILON DBL_EPSILON\n"
232
- kernel_src += "#define ZERO_R1 0.0\n"
233
- kernel_src += "#define ONE_R1 1.0\n"
234
- kernel_src += "#define TWO_R1 2.0\n"
235
- else:
236
- dtype = np.float32
237
- epsilon = 2 ** -23
238
- kernel_src += "#define real1 float\n"
239
- kernel_src += "#define qint int\n"
240
- kernel_src += "#define EPSILON FLT_EPSILON\n"
241
- kernel_src += "#define ZERO_R1 0.0f\n"
242
- kernel_src += "#define ONE_R1 1.0f\n"
243
- kernel_src += "#define TWO_R1 2.0f\n"
244
-
245
- try:
246
- import pyopencl as cl
247
- import warnings
248
-
249
- warnings.simplefilter("ignore", cl.CompilerWarning)
250
-
251
- # Pick a device (GPU if available)
252
- ctx = cl.create_some_context()
253
- queue = cl.CommandQueue(ctx)
254
- compute_units = int(os.getenv('PYQRACKISING_MAX_GPU_PROC_ELEM', str(ctx.devices[0].get_info(cl.device_info.MAX_COMPUTE_UNITS))))
255
-
256
- # Load and build OpenCL kernels
257
- kernel_src += f"#define MAX_PROC_ELEM {compute_units}\n"
258
- kernel_src += f"#define TOP_N {os.getenv('PYQRACKISING_GPU_TOP_N', '32')}\n"
259
- kernel_src += open(os.path.dirname(os.path.abspath(__file__)) + "/kernels.cl").read()
260
- program = cl.Program(ctx, kernel_src).build()
261
- bootstrap_kernel = program.bootstrap
262
- bootstrap_sparse_kernel = program.bootstrap_sparse
263
- bootstrap_segmented_kernel = program.bootstrap_segmented
264
- bootstrap_sparse_segmented_kernel = program.bootstrap_sparse_segmented
265
-
266
- work_group_size = bootstrap_kernel.get_work_group_info(
267
- cl.kernel_work_group_info.PREFERRED_WORK_GROUP_SIZE_MULTIPLE,
268
- ctx.devices[0]
269
- )
270
-
271
- max_alloc = ctx.devices[0].get_info(cl.device_info.MAX_MEM_ALLOC_SIZE)
272
- except ImportError:
273
- IS_OPENCL_AVAILABLE = False
274
- print("PyOpenCL not installed. (If you have any OpenCL accelerator devices with available ICDs, you might want to optionally install pyopencl.)")
275
-
276
- 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)
@@ -163,7 +163,10 @@ def spin_glass_solver(
163
163
  quality=None,
164
164
  shots=None,
165
165
  best_guess=None,
166
- is_combo_maxcut_gpu=True
166
+ is_combo_maxcut_gpu=True,
167
+ is_spin_glass=True,
168
+ anneal_t=None,
169
+ anneal_h=None
167
170
  ):
168
171
  dtype = opencl_context.dtype
169
172
  nodes = None
@@ -198,9 +201,6 @@ def spin_glass_solver(
198
201
 
199
202
  return "01", weight, ([nodes[0]], [nodes[1]]), -weight
200
203
 
201
- if quality is None:
202
- quality = 3
203
-
204
204
  bitstring = ""
205
205
  if isinstance(best_guess, str):
206
206
  bitstring = best_guess
@@ -209,7 +209,7 @@ def spin_glass_solver(
209
209
  elif isinstance(best_guess, list):
210
210
  bitstring = "".join(["1" if b else "0" for b in best_guess])
211
211
  else:
212
- bitstring, _, _ = maxcut_tfim(G_m, quality=quality, shots=shots)
212
+ bitstring, _, _ = maxcut_tfim(G_m, quality=quality, shots=shots, is_spin_glass=is_spin_glass, anneal_t=anneal_t, anneal_h=anneal_h)
213
213
  best_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
214
214
 
215
215
  if is_combo_maxcut_gpu and IS_OPENCL_AVAILABLE:
@@ -182,7 +182,10 @@ def spin_glass_solver_sparse(
182
182
  quality=None,
183
183
  shots=None,
184
184
  best_guess=None,
185
- is_combo_maxcut_gpu=True
185
+ is_combo_maxcut_gpu=True,
186
+ is_spin_glass=True,
187
+ anneal_t=None,
188
+ anneal_h=None
186
189
  ):
187
190
  dtype = opencl_context.dtype
188
191
  nodes = None
@@ -217,9 +220,6 @@ def spin_glass_solver_sparse(
217
220
  print("[WARN] Using segmented solver, so disabling is_alt_gpu_sampling.")
218
221
  is_alt_gpu_sampling = False
219
222
 
220
- if quality is None:
221
- quuality = 3
222
-
223
223
  bitstring = ""
224
224
  if isinstance(best_guess, str):
225
225
  bitstring = best_guess
@@ -228,7 +228,7 @@ def spin_glass_solver_sparse(
228
228
  elif isinstance(best_guess, list):
229
229
  bitstring = "".join(["1" if b else "0" for b in best_guess])
230
230
  else:
231
- bitstring, _, _ = maxcut_tfim_sparse(G_m, quality=quality, shots=shots)
231
+ bitstring, _, _ = maxcut_tfim_sparse(G_m, quality=quality, shots=shots, is_spin_glass=is_spin_glass, anneal_t=anneal_t, anneal_h=anneal_h)
232
232
  best_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
233
233
 
234
234
  if is_combo_maxcut_gpu and IS_OPENCL_AVAILABLE:
@@ -71,7 +71,10 @@ def spin_glass_solver_streaming(
71
71
  nodes,
72
72
  quality=None,
73
73
  shots=None,
74
- best_guess=None
74
+ best_guess=None,
75
+ is_spin_glass=True,
76
+ anneal_t=None,
77
+ anneal_h=None
75
78
  ):
76
79
  dtype = opencl_context.dtype
77
80
  n_qubits = len(nodes)
@@ -90,9 +93,6 @@ def spin_glass_solver_streaming(
90
93
 
91
94
  return "01", weight, ([nodes[0]], [nodes[1]]), -weight
92
95
 
93
- if quality is None:
94
- quality = 3
95
-
96
96
  bitstring = ""
97
97
  if isinstance(best_guess, str):
98
98
  bitstring = best_guess
@@ -101,7 +101,7 @@ def spin_glass_solver_streaming(
101
101
  elif isinstance(best_guess, list):
102
102
  bitstring = "".join(["1" if b else "0" for b in best_guess])
103
103
  else:
104
- bitstring, _, _ = maxcut_tfim_streaming(G_func, nodes, quality=quality, shots=shots)
104
+ bitstring, _, _ = maxcut_tfim_streaming(G_func, nodes, quality=quality, shots=shots, is_spin_glass=is_spin_glass, anneal_t=anneal_t, anneal_h=anneal_h)
105
105
  best_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
106
106
 
107
107
  min_energy = compute_energy(best_theta, G_func, nodes)
@@ -1,5 +1,5 @@
1
- from .spin_glass_solver import spin_glass_solver
2
1
  from .maxcut_tfim_util import binary_search, opencl_context, to_scipy_sparse_upper_triangular
2
+ from .maxcut_tfim import maxcut_tfim
3
3
  from concurrent.futures import ProcessPoolExecutor
4
4
  import time
5
5
  import itertools
@@ -627,7 +627,8 @@ def tsp_symmetric(
627
627
  end_node=None,
628
628
  quality=None,
629
629
  shots=None,
630
- is_combo_maxcut_gpu=True,
630
+ anneal_t=None,
631
+ anneal_h=None,
631
632
  monte_carlo=True,
632
633
  k_neighbors=20,
633
634
  is_cyclic=True,
@@ -675,13 +676,13 @@ def tsp_symmetric(
675
676
  if monte_carlo:
676
677
  a, b = monte_carlo_loop(n_nodes)
677
678
  else:
678
- best_energy = float("inf")
679
+ best_cut = -float("inf")
679
680
  for _ in range(multi_start):
680
681
  bits = ([], [])
681
682
  while (len(bits[0]) == 0) or (len(bits[1]) == 0):
682
- _, _, bits, energy = spin_glass_solver(G_m, quality=quality, shots=shots, is_combo_maxcut_gpu=is_combo_maxcut_gpu)
683
- if energy < best_energy:
684
- best_energy = energy
683
+ _, cut_value, bits = maxcut_tfim(G_m, quality=quality, shots=shots, anneal_t=anneal_t, anneal_h=anneal_h)
684
+ if cut_value > best_cut:
685
+ best_cut = cut_value
685
686
  a, b = bits
686
687
  else:
687
688
  is_cyclic = False
@@ -696,15 +697,16 @@ def tsp_symmetric(
696
697
 
697
698
  if monte_carlo and is_parallel and (parallel_level < max_parallel_level) and (len(a) > 3) and (len(b) > 3):
698
699
  with ProcessPoolExecutor(max_workers=1) as executor:
699
- f = executor.submit(tsp_symmetric, G_a, None, None, quality, shots, is_combo_maxcut_gpu, True, 0, False, multi_start, False, True, parallel_level + 1)
700
- sol_b = tsp_symmetric(G_b, None, None, quality, shots, is_combo_maxcut_gpu, True, 0, False, multi_start, False, True, parallel_level + 1)
700
+ f = executor.submit(tsp_symmetric, G_a, None, None, quality, shots, anneal_t, anneal_h, True, 0, False, multi_start, False, True, parallel_level + 1)
701
+ sol_b = tsp_symmetric(G_b, None, None, quality, shots, anneal_t, anneal_h, True, 0, False, multi_start, False, True, parallel_level + 1)
701
702
  sol_a = f.result()
702
703
  else:
703
704
  sol_a = tsp_symmetric(
704
705
  G_a,
705
706
  quality=quality,
706
707
  shots=shots,
707
- is_combo_maxcut_gpu=is_combo_maxcut_gpu,
708
+ anneal_t=anneal_t,
709
+ anneal_h=anneal_h,
708
710
  monte_carlo=monte_carlo,
709
711
  is_cyclic=False,
710
712
  is_top_level=False,
@@ -716,7 +718,8 @@ def tsp_symmetric(
716
718
  G_b,
717
719
  quality=quality,
718
720
  shots=shots,
719
- is_combo_maxcut_gpu=is_combo_maxcut_gpu,
721
+ anneal_t=anneal_t,
722
+ anneal_h=anneal_h,
720
723
  monte_carlo=monte_carlo,
721
724
  is_cyclic=False,
722
725
  is_top_level=False,
@@ -827,7 +830,8 @@ def tsp_asymmetric(
827
830
  end_node=None,
828
831
  quality=None,
829
832
  shots=None,
830
- is_combo_maxcut_gpu=True,
833
+ anneal_t=None,
834
+ anneal_h=None,
831
835
  monte_carlo=True,
832
836
  k_neighbors=20,
833
837
  is_cyclic=True,
@@ -879,13 +883,13 @@ def tsp_asymmetric(
879
883
  if monte_carlo:
880
884
  a, b = monte_carlo_loop(n_nodes)
881
885
  else:
882
- best_energy = float("inf")
886
+ best_cut = -float("inf")
883
887
  for _ in range(multi_start):
884
888
  bits = ([], [])
885
889
  while (len(bits[0]) == 0) or (len(bits[1]) == 0):
886
- _, _, bits, energy = spin_glass_solver((G_m + G_m.T) / 2, quality=quality, shots=shots, is_combo_maxcut_gpu=is_combo_maxcut_gpu)
887
- if energy < best_energy:
888
- best_energy = energy
890
+ _, cut_value, bits = maxcut_tfim((G_m + G_m.T) / 2, quality=quality, shots=shots, anneal_t=anneal_t, anneal_h=anneal_h)
891
+ if cut_value > best_cut:
892
+ best_cut = cut_value
889
893
  a, b = bits
890
894
  else:
891
895
  is_cyclic = False
@@ -900,15 +904,16 @@ def tsp_asymmetric(
900
904
 
901
905
  if monte_carlo and is_parallel and (parallel_level < max_parallel_level) and (len(a) > 2) and (len(b) > 2):
902
906
  with ProcessPoolExecutor(max_workers=1) as executor:
903
- f = executor.submit(tsp_asymmetric, G_a, None, None, quality, shots, is_combo_maxcut_gpu, True, 0, False, multi_start, False, True, parallel_level + 1)
904
- sol_b = tsp_asymmetric(G_b, None, None, quality, shots, is_combo_maxcut_gpu, True, 0, False, multi_start, False, True, parallel_level + 1)
907
+ f = executor.submit(tsp_asymmetric, G_a, None, None, quality, shots, anneal_t, anneal_h, True, 0, False, multi_start, False, True, parallel_level + 1)
908
+ sol_b = tsp_asymmetric(G_b, None, None, quality, shots, anneal_t, anneal_h, True, 0, False, multi_start, False, True, parallel_level + 1)
905
909
  sol_a = f.result()
906
910
  else:
907
911
  sol_a = tsp_asymmetric(
908
912
  G_a,
909
913
  quality=quality,
910
914
  shots=shots,
911
- is_combo_maxcut_gpu=is_combo_maxcut_gpu,
915
+ anneal_t=anneal_t,
916
+ anneal_h=anneal_h,
912
917
  monte_carlo=monte_carlo,
913
918
  is_cyclic=False,
914
919
  is_top_level=False,
@@ -920,7 +925,8 @@ def tsp_asymmetric(
920
925
  G_b,
921
926
  quality=quality,
922
927
  shots=shots,
923
- is_combo_maxcut_gpu=is_combo_maxcut_gpu,
928
+ anneal_t=anneal_t,
929
+ anneal_h=anneal_h,
924
930
  monte_carlo=monte_carlo,
925
931
  is_cyclic=False,
926
932
  is_top_level=False,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrackising
3
- Version: 8.0.2
3
+ Version: 8.1.0
4
4
  Summary: Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)
5
5
  Home-page: https://github.com/vm6502q/PyQrackIsing
6
6
  Author: Dan Strano
@@ -51,7 +51,7 @@ ext_modules = [CMakeExtension('tfim_sampler')]
51
51
 
52
52
  setup(
53
53
  name='pyqrackising',
54
- version='8.0.2',
54
+ version='8.1.0',
55
55
  author='Dan Strano',
56
56
  author_email='stranoj@gmail.com',
57
57
  description='Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)',
File without changes
File without changes
File without changes