PyQrackIsing 8.10.0__py3-none-macosx_15_0_arm64.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,12 @@
1
+ from .generate_tfim_samples import generate_tfim_samples
2
+ from .tfim_magnetization import tfim_magnetization
3
+ from .tfim_square_magnetization import tfim_square_magnetization
4
+ from .maxcut_tfim import maxcut_tfim
5
+ from .maxcut_tfim_sparse import maxcut_tfim_sparse
6
+ from .maxcut_tfim_streaming import maxcut_tfim_streaming
7
+ from .spin_glass_solver import spin_glass_solver
8
+ from .spin_glass_solver_sparse import spin_glass_solver_sparse
9
+ from .spin_glass_solver_streaming import spin_glass_solver_streaming
10
+ from .tsp import tsp_symmetric, tsp_asymmetric
11
+ from .tsp_maxcut import tsp_maxcut, tsp_maxcut_sparse, tsp_maxcut_streaming
12
+ from .convert_tensor_network_to_tsp import convert_tensor_network_to_tsp, convert_quimb_tree_to_tsp
@@ -0,0 +1,97 @@
1
+ # Provided by Elara, the custom OpenAI GPT
2
+ from collections import defaultdict
3
+ import itertools
4
+ import numpy as np
5
+
6
+
7
+ def convert_tensor_network_to_tsp(tensors, index_dims, dtype=np.float32):
8
+ """
9
+ Converts a tensor network to a symmetric TSP distance matrix based on pairwise contraction costs.
10
+
11
+ Args:
12
+ tensors: List of dictionaries, each with keys:
13
+ - 'id': Unique tensor identifier (str)
14
+ - 'indices': Set of indices (Set[str])
15
+ index_dims: Dictionary mapping index name to its dimension (e.g., {'i': 2, 'j': 4})
16
+
17
+ Returns:
18
+ A tuple containing:
19
+ - A normalized 2D numpy array representing the symmetric TSP distance matrix.
20
+ - A list of tensor IDs corresponding to the node order in the distance matrix.
21
+ """
22
+ # Step 1: Build inverse map: index -> tensors using it
23
+ index_to_tensors = defaultdict(set)
24
+ for tensor in tensors:
25
+ for idx in tensor["indices"]:
26
+ index_to_tensors[idx].add(tensor["id"])
27
+
28
+ # Step 2: Build graph of neighboring tensors
29
+ graph = defaultdict(set)
30
+ for idx, tensor_ids in index_to_tensors.items():
31
+ for t1, t2 in itertools.combinations(tensor_ids, 2):
32
+ graph[t1].add(t2)
33
+ graph[t2].add(t1)
34
+
35
+ # Step 3: Estimate pairwise contraction costs
36
+ def estimate_cost(t1, t2):
37
+ common = t1["indices"] & t2["indices"]
38
+ if not common:
39
+ return float("inf")
40
+ all_indices = t1["indices"] | t2["indices"]
41
+ return sum(index_dims.get(i, 1) for i in all_indices)
42
+
43
+ max_cost = float("-inf")
44
+ edge_costs = {}
45
+ for t1, neighbors in graph.items():
46
+ for t2 in neighbors:
47
+ key = tuple(sorted([t1, t2]))
48
+ if key not in edge_costs:
49
+ t1_data = next(t for t in tensors if t["id"] == t1)
50
+ t2_data = next(t for t in tensors if t["id"] == t2)
51
+ cost = estimate_cost(t1_data, t2_data)
52
+ edge_costs[key] = cost
53
+ if (cost < float("inf")) and (cost > max_cost):
54
+ max_cost = cost
55
+
56
+ # Step 4: Build distance matrix
57
+ tensor_ids = [t["id"] for t in tensors]
58
+ id_to_node = {tid: i for i, tid in enumerate(tensor_ids)}
59
+ n = len(tensor_ids)
60
+ dist_matrix = np.full((n, n), np.sqrt(np.finfo(dtype).max), dtype=dtype)
61
+
62
+ for (t1, t2), cost in edge_costs.items():
63
+ if cost == float("inf"):
64
+ continue
65
+ i, j = id_to_node[t1], id_to_node[t2]
66
+ dist_matrix[i, j] = dist_matrix[j, i] = cost / max_cost
67
+
68
+ return dist_matrix, tensor_ids
69
+
70
+
71
+
72
+ def convert_quimb_tree_to_tsp(tn, dtype=np.float32):
73
+ """
74
+ Converts a quimb TensorNetwork to a TSP distance matrix for contraction optimization.
75
+
76
+ Args:
77
+ tn: A quimb.tensor.TensorNetwork instance.
78
+
79
+ Returns:
80
+ - Normalized symmetric distance matrix (2D numpy array of floats)
81
+ - List of tensor IDs (tags) corresponding to the matrix order
82
+ """
83
+ tensors = []
84
+ index_dims = {}
85
+
86
+ for tensor in tn.tensors:
87
+ # Use a unique tag or fallback to name
88
+ tensor_id = frozenset(tensor.tags) if tensor.tags else str(tensor.name)
89
+ tensors.append({
90
+ "id": tensor_id,
91
+ "indices": set(tensor.inds)
92
+ })
93
+
94
+ for ind, dim in zip(tensor.inds, tensor.shape):
95
+ index_dims[ind] = dim # capture dimension size
96
+
97
+ return convert_tensor_network_to_tsp(tensors, index_dims, dtype)
@@ -0,0 +1,142 @@
1
+ from .maxcut_tfim_util import probability_by_hamming_weight, sample_mag
2
+ import itertools
3
+ import math
4
+ import numpy as np
5
+ from numba import njit
6
+
7
+
8
+ @njit
9
+ def factor_width(width, is_transpose=False):
10
+ col_len = math.floor(math.sqrt(width))
11
+ while ((width // col_len) * col_len) != width:
12
+ col_len -= 1
13
+ row_len = width // col_len
14
+
15
+ return (col_len, row_len) if is_transpose else (row_len, col_len)
16
+
17
+
18
+ # By Gemini (Google Search AI)
19
+ def int_to_bitstring(integer, length):
20
+ return bin(integer)[2:].zfill(length)
21
+
22
+
23
+ # Drafted by Elara (OpenAI custom GPT), improved by Dan Strano
24
+ def closeness_like_bits(perm, n_rows, n_cols):
25
+ """
26
+ Compute closeness-of-like-bits metric C(state) for a given bitstring on an LxL toroidal grid.
27
+
28
+ Parameters:
29
+ perm: integer representing basis state, bit-length n_rows * n_cols
30
+ n_rows: row count of torus
31
+ n_cols: column count of torus
32
+
33
+ Returns:
34
+ normalized_closeness: float, in [-1, +1]
35
+ +1 means all neighbors are like-like, -1 means all neighbors are unlike
36
+ """
37
+ # reshape the bitstring into LxL grid
38
+ bitstring = list(int_to_bitstring(perm, n_rows * n_cols))
39
+ grid = np.array(bitstring).reshape((n_rows, n_cols))
40
+ total_edges = 0
41
+ like_count = 0
42
+
43
+ # iterate over each site, count neighbors (right and down to avoid double-count)
44
+ for i in range(n_rows):
45
+ for j in range(n_cols):
46
+ s = grid[i, j]
47
+
48
+ # right neighbor (wrap around)
49
+ s_right = grid[i, (j + 1) % n_cols]
50
+ like_count += 1 if s == s_right else -1
51
+ total_edges += 1
52
+
53
+ # down neighbor (wrap around)
54
+ s_down = grid[(i + 1) % n_rows, j]
55
+ like_count += 1 if s == s_down else -1
56
+ total_edges += 1
57
+
58
+ # normalize
59
+ normalized_closeness = like_count / total_edges
60
+ return normalized_closeness
61
+
62
+
63
+ @njit
64
+ def comb(n, k):
65
+ if (k < 0) or (k > n):
66
+ return 0
67
+ if (k == 0) or (k == n):
68
+ return 1
69
+ res = 1
70
+ for i in range(1, k + 1):
71
+ res = res * (n - k + i) // i
72
+ return res
73
+
74
+
75
+ @njit
76
+ def expected_closeness_weight(n_rows, n_cols, hamming_weight):
77
+ L = n_rows * n_cols
78
+ same_pairs = comb(hamming_weight, 2) + comb(L - hamming_weight, 2)
79
+ total_pairs = comb(L, 2)
80
+ mu_k = same_pairs / total_pairs
81
+ return 2.0 * mu_k - 1.0
82
+
83
+
84
+ @njit
85
+ def sample_hamming_weight(thresholds, shots):
86
+ hamming_samples = np.zeros(shots, dtype=np.int32)
87
+ for s in range(shots):
88
+ hamming_samples[s] = sample_mag(thresholds)
89
+
90
+ return hamming_samples
91
+
92
+ @njit
93
+ def fix_cdf(hamming_prob):
94
+ hamming_prob /= hamming_prob.sum()
95
+ tot_prob = 0.0
96
+ n_bias = len(hamming_prob)
97
+ cum_prob = np.empty(n_bias, dtype=np.float64)
98
+ for i in range(n_bias):
99
+ tot_prob += hamming_prob[i]
100
+ cum_prob[i] = tot_prob
101
+ cum_prob[-1] = 2.0
102
+
103
+ return cum_prob
104
+
105
+
106
+ def generate_tfim_samples(
107
+ J=-1.0, h=2.0, z=4, theta=0.174532925199432957, t=5, n_qubits=56, shots=100
108
+ ):
109
+ n_rows, n_cols = factor_width(n_qubits)
110
+
111
+ # First dimension: Hamming weight
112
+ thresholds = fix_cdf(probability_by_hamming_weight(J, h, z, theta, t, n_qubits + 1))
113
+ hamming_samples = sample_hamming_weight(thresholds, shots)
114
+
115
+ samples = []
116
+ for m in range(len(hamming_samples)):
117
+ # Second dimension: permutation within Hamming weight
118
+ # (Written with help from Elara, the custom OpenAI GPT)
119
+ hs = hamming_samples[m]
120
+ rands = []
121
+ for s in range(hs):
122
+ rands.append(np.random.random())
123
+ rands.sort()
124
+ state_int = 0
125
+ tot_prob = 0
126
+ s = 0
127
+ for combo in itertools.combinations(range(n_qubits), m):
128
+ state_int = sum(1 << pos for pos in combo)
129
+ tot_prob += (1.0 + closeness_like_bits(state_int, n_rows, n_cols)) / (
130
+ 1.0 + expected_closeness_weight(n_rows, n_cols, m)
131
+ )
132
+ while (s < hs) and (rands[s] <= tot_prob):
133
+ samples.append(state_int)
134
+ s += 1
135
+ if s == hs:
136
+ break
137
+ for r in range(hs - s):
138
+ samples.append(state_int)
139
+
140
+ np.random.shuffle(samples)
141
+
142
+ return samples
@@ -0,0 +1,440 @@
1
+ #if FP16
2
+ #define fwrapper(f, a) (half)f((float)(a))
3
+ #define fwrapper2(f, a, b) (half)f((float)(a), (float)(b))
4
+ #else
5
+ #define fwrapper(f, a) f(a)
6
+ #define fwrapper2(f, a, b) f(a, b)
7
+ #endif
8
+
9
+ inline uint xorshift32(uint *state) {
10
+ uint x = *state;
11
+ x ^= x << 13;
12
+ x ^= x >> 17;
13
+ x ^= x << 5;
14
+ *state = x;
15
+ return x;
16
+ }
17
+
18
+ real1 bootstrap_worker(__constant char* theta, __global const real1* G_m, __constant int* indices, const int k, const int n, const bool is_spin_glass) {
19
+ real1 energy = ZERO_R1;
20
+ const size_t n_st = (size_t)n;
21
+ for (int u = 0; u < n; ++u) {
22
+ const size_t u_offset = u * n_st;
23
+ bool u_bit = theta[u];
24
+ for (int x = 0; x < k; ++x) {
25
+ if (indices[x] == u) {
26
+ u_bit = !u_bit;
27
+ break;
28
+ }
29
+ }
30
+ for (int v = u + 1; v < n; ++v) {
31
+ const real1 val = G_m[u_offset + v];
32
+ bool v_bit = theta[v];
33
+ for (int x = 0; x < k; ++x) {
34
+ if (indices[x] == v) {
35
+ v_bit = !v_bit;
36
+ break;
37
+ }
38
+ }
39
+ if (u_bit != v_bit) {
40
+ energy -= val;
41
+ } else if (is_spin_glass) {
42
+ energy += val;
43
+ }
44
+ }
45
+ }
46
+
47
+ return energy;
48
+ }
49
+
50
+ __kernel void bootstrap(
51
+ uint prng_seed,
52
+ __global const real1* G_m,
53
+ __constant char* best_theta,
54
+ __constant int* indices_array,
55
+ __constant int* args, // args[0] = n, args[1] = k
56
+ __global real1* min_energy_ptr, // output: per-group min energy
57
+ __global int* min_index_ptr, // output: per-group best index (i)
58
+ __local real1* loc_energy, // local memory buffer
59
+ __local int* loc_index // local memory buffer
60
+ ) {
61
+ const int n = args[0];
62
+ const int k = args[1];
63
+ const int combo_count = args[2];
64
+ const bool is_spin_glass = args[3];
65
+ int i = get_global_id(0);
66
+
67
+ // The inputs are chaotic, and this doesn't need to be high-quality, just uniform.
68
+ prng_seed ^= (uint)i;
69
+
70
+ real1 best_energy = INFINITY;
71
+ int best_i = i;
72
+
73
+ for (; i < combo_count; i += MAX_PROC_ELEM) {
74
+ const int j = i * k;
75
+ const real1 energy = bootstrap_worker(best_theta, G_m, indices_array + j, k, n, is_spin_glass);
76
+ if (energy < best_energy) {
77
+ best_energy = energy;
78
+ best_i = i;
79
+ } else if (((energy - best_energy) <= EPSILON) && ((xorshift32(&prng_seed) >> 31) & 1)) {
80
+ best_i = i;
81
+ }
82
+ }
83
+
84
+ const int lt_id = get_local_id(0);
85
+ const int lt_size = get_local_size(0);
86
+
87
+ loc_energy[lt_id] = best_energy;
88
+ loc_index[lt_id] = best_i;
89
+
90
+ // Reduce within workgroup
91
+ for (int offset = lt_size >> 1; offset > 0; offset >>= 1) {
92
+ barrier(CLK_LOCAL_MEM_FENCE);
93
+ if (lt_id < offset) {
94
+ real1 hid_energy = loc_energy[lt_id + offset];
95
+ real1 lid_energy = loc_energy[lt_id];
96
+ if (hid_energy < lid_energy) {
97
+ loc_energy[lt_id] = hid_energy;
98
+ loc_index[lt_id] = loc_index[lt_id + offset];
99
+ } else if (((hid_energy - lid_energy) <= EPSILON) && ((xorshift32(&prng_seed) >> 31) & 1)) {
100
+ loc_index[lt_id] = loc_index[lt_id + offset];
101
+ }
102
+ }
103
+ }
104
+
105
+ // Write out per-group result
106
+ if (lt_id == 0) {
107
+ min_energy_ptr[get_group_id(0)] = loc_energy[0];
108
+ min_index_ptr[get_group_id(0)] = loc_index[0];
109
+ }
110
+ }
111
+
112
+ real1 bootstrap_worker_sparse(__constant char* theta, __global const real1* G_data, __global const uint* G_rows, __global const uint* G_cols, __constant int* indices, const int k, const int n, const bool is_spin_glass) {
113
+ real1 energy = ZERO_R1;
114
+ for (int u = 0; u < n; ++u) {
115
+ bool u_bit = theta[u];
116
+ for (int x = 0; x < k; ++x) {
117
+ if (indices[x] == u) {
118
+ u_bit = !u_bit;
119
+ break;
120
+ }
121
+ }
122
+ const size_t mCol = G_rows[u + 1];
123
+ for (int col = G_rows[u]; col < mCol; ++col) {
124
+ const int v = G_cols[col];
125
+ const real1 val = G_data[col];
126
+ bool v_bit = theta[v];
127
+ for (int x = 0; x < k; ++x) {
128
+ if (indices[x] == v) {
129
+ v_bit = !v_bit;
130
+ break;
131
+ }
132
+ }
133
+ if (u_bit != v_bit) {
134
+ energy -= val;
135
+ } else if (is_spin_glass) {
136
+ energy += val;
137
+ }
138
+ }
139
+ }
140
+
141
+ return energy;
142
+ }
143
+
144
+ __kernel void bootstrap_sparse(
145
+ uint prng_seed,
146
+ __global const real1* G_data,
147
+ __global const uint* G_rows,
148
+ __global const uint* G_cols,
149
+ __constant char* best_theta,
150
+ __constant int* indices_array,
151
+ __constant int* args, // args[0] = n, args[1] = k
152
+ __global real1* min_energy_ptr, // output: per-group min energy
153
+ __global int* min_index_ptr, // output: per-group best index (i)
154
+ __local real1* loc_energy, // local memory buffer
155
+ __local int* loc_index // local memory buffer
156
+ ) {
157
+ const int n = args[0];
158
+ const int k = args[1];
159
+ const int combo_count = args[2];
160
+ const bool is_spin_glass = args[3];
161
+ int i = get_global_id(0);
162
+
163
+ prng_seed ^= (uint)i;
164
+
165
+ real1 best_energy = INFINITY;
166
+ int best_i = i;
167
+
168
+ for (; i < combo_count; i += MAX_PROC_ELEM) {
169
+ const int j = i * k;
170
+ const real1 energy = bootstrap_worker_sparse(best_theta, G_data, G_rows, G_cols, indices_array + j, k, n, is_spin_glass);
171
+ if (energy < best_energy) {
172
+ best_energy = energy;
173
+ best_i = i;
174
+ } else if (((energy - best_energy) <= EPSILON) && ((xorshift32(&prng_seed) >> 31) & 1)) {
175
+ best_i = i;
176
+ }
177
+ }
178
+
179
+ const int lt_id = get_local_id(0);
180
+ const int lt_size = get_local_size(0);
181
+
182
+ loc_energy[lt_id] = best_energy;
183
+ loc_index[lt_id] = best_i;
184
+
185
+ // Reduce within workgroup
186
+ for (int offset = lt_size >> 1; offset > 0; offset >>= 1) {
187
+ barrier(CLK_LOCAL_MEM_FENCE);
188
+ if (lt_id < offset) {
189
+ real1 hid_energy = loc_energy[lt_id + offset];
190
+ real1 lid_energy = loc_energy[lt_id];
191
+ if (hid_energy < lid_energy) {
192
+ loc_energy[lt_id] = hid_energy;
193
+ loc_index[lt_id] = loc_index[lt_id + offset];
194
+ } else if (((hid_energy - lid_energy) <= EPSILON) && ((xorshift32(&prng_seed) >> 31) & 1)) {
195
+ loc_index[lt_id] = loc_index[lt_id + offset];
196
+ }
197
+ }
198
+ }
199
+
200
+ // Write out per-group result
201
+ if (lt_id == 0) {
202
+ min_energy_ptr[get_group_id(0)] = loc_energy[0];
203
+ min_index_ptr[get_group_id(0)] = loc_index[0];
204
+ }
205
+ }
206
+
207
+ // Helper to read from segmented G_m
208
+ inline real1 get_G_m(
209
+ __global const real1** G_m,
210
+ size_t flat_idx,
211
+ int segment_size
212
+ ) {
213
+ return G_m[flat_idx / segment_size][flat_idx % segment_size];
214
+ }
215
+
216
+ real1 bootstrap_worker_segmented(
217
+ __constant char* theta,
218
+ __global const real1** G_m,
219
+ __constant int* indices,
220
+ const int k,
221
+ const int n,
222
+ const int segment_size,
223
+ const bool is_spin_glass
224
+ ) {
225
+ real1 energy = ZERO_R1;
226
+ const size_t n_st = (size_t)n;
227
+
228
+ for (int u = 0; u < n; ++u) {
229
+ const size_t u_offset = u * n_st;
230
+ bool u_bit = theta[u];
231
+ for (int x = 0; x < k; ++x) {
232
+ if (indices[x] == u) {
233
+ u_bit = !u_bit;
234
+ break;
235
+ }
236
+ }
237
+ for (int v = u + 1; v < n; ++v) {
238
+ size_t flat_idx = u_offset + v;
239
+ real1 val = get_G_m(G_m, flat_idx, segment_size);
240
+
241
+ bool v_bit = theta[v];
242
+ for (int x = 0; x < k; ++x) {
243
+ if (indices[x] == v) {
244
+ v_bit = !v_bit;
245
+ break;
246
+ }
247
+ }
248
+
249
+ if (u_bit != v_bit) {
250
+ energy -= val;
251
+ } else if (is_spin_glass) {
252
+ energy += val;
253
+ }
254
+ }
255
+ }
256
+
257
+ return energy;
258
+ }
259
+
260
+
261
+ __kernel void bootstrap_segmented(
262
+ uint prng_seed,
263
+ __global const real1* G_m0,
264
+ __global const real1* G_m1,
265
+ __global const real1* G_m2,
266
+ __global const real1* G_m3,
267
+ __constant char* best_theta,
268
+ __constant int* indices_array,
269
+ __constant int* args, // args[0]=n, args[1]=k, args[2]=combo_count, args[3]=segment_size
270
+ __global real1* min_energy_ptr,
271
+ __global int* min_index_ptr,
272
+ __local real1* loc_energy,
273
+ __local int* loc_index
274
+ ) {
275
+ __global const real1* G_m[4] = { G_m0, G_m1, G_m2, G_m3 };
276
+
277
+ const int n = args[0];
278
+ const int k = args[1];
279
+ const int combo_count = args[2];
280
+ const bool is_spin_glass = args[3];
281
+ const int segment_size = args[4];
282
+ int i = get_global_id(0);
283
+
284
+ prng_seed ^= (uint)i;
285
+
286
+ real1 best_energy = INFINITY;
287
+ int best_i = i;
288
+
289
+ for (; i < combo_count; i += MAX_PROC_ELEM) {
290
+ const int j = i * k;
291
+ const real1 energy = bootstrap_worker_segmented(best_theta, G_m, indices_array + j, k, n, segment_size, is_spin_glass);
292
+ if (energy < best_energy) {
293
+ best_energy = energy;
294
+ best_i = i;
295
+ } else if (((energy - best_energy) <= EPSILON) && ((xorshift32(&prng_seed) >> 31) & 1)) {
296
+ best_i = i;
297
+ }
298
+ }
299
+
300
+ const int lt_id = get_local_id(0);
301
+ const int lt_size = get_local_size(0);
302
+
303
+ loc_energy[lt_id] = best_energy;
304
+ loc_index[lt_id] = best_i;
305
+
306
+ for (int offset = lt_size >> 1; offset > 0; offset >>= 1) {
307
+ barrier(CLK_LOCAL_MEM_FENCE);
308
+ if (lt_id < offset) {
309
+ real1 hid_energy = loc_energy[lt_id + offset];
310
+ real1 lid_energy = loc_energy[lt_id];
311
+ if (hid_energy < lid_energy) {
312
+ loc_energy[lt_id] = hid_energy;
313
+ loc_index[lt_id] = loc_index[lt_id + offset];
314
+ } else if (((hid_energy - lid_energy) <= EPSILON) && ((xorshift32(&prng_seed) >> 31) & 1)) {
315
+ loc_index[lt_id] = loc_index[lt_id + offset];
316
+ }
317
+ }
318
+ }
319
+
320
+ if (lt_id == 0) {
321
+ min_energy_ptr[get_group_id(0)] = loc_energy[0];
322
+ min_index_ptr[get_group_id(0)] = loc_index[0];
323
+ }
324
+ }
325
+
326
+ real1 bootstrap_worker_sparse_segmented(
327
+ __constant char* theta,
328
+ __global const real1** G_data,
329
+ __global const uint* G_rows,
330
+ __global const uint* G_cols,
331
+ __constant int* indices,
332
+ const int k,
333
+ const int n,
334
+ const int segment_size,
335
+ const bool is_spin_glass
336
+ ) {
337
+ real1 energy = ZERO_R1;
338
+
339
+ for (int u = 0; u < n; ++u) {
340
+ bool u_bit = theta[u];
341
+ for (int x = 0; x < k; ++x) {
342
+ if (indices[x] == u) {
343
+ u_bit = !u_bit;
344
+ break;
345
+ }
346
+ }
347
+
348
+ const uint row_start = G_rows[u];
349
+ const uint row_end = G_rows[u + 1];
350
+
351
+ for (uint col = row_start; col < row_end; ++col) {
352
+ const int v = G_cols[col];
353
+ real1 val = get_G_m(G_data, col, segment_size);
354
+
355
+ bool v_bit = theta[v];
356
+ for (int x = 0; x < k; ++x) {
357
+ if (indices[x] == v) {
358
+ v_bit = !v_bit;
359
+ break;
360
+ }
361
+ }
362
+
363
+ if (u_bit != v_bit) {
364
+ energy -= val;
365
+ } else if (is_spin_glass) {
366
+ energy += val;
367
+ }
368
+ }
369
+ }
370
+
371
+ return energy;
372
+ }
373
+
374
+ __kernel void bootstrap_sparse_segmented(
375
+ uint prng_seed,
376
+ __global const real1* G_data0,
377
+ __global const real1* G_data1,
378
+ __global const real1* G_data2,
379
+ __global const real1* G_data3,
380
+ __global const uint* G_rows,
381
+ __global const uint* G_cols,
382
+ __constant char* best_theta,
383
+ __constant int* indices_array,
384
+ __constant int* args, // args[0] = n, args[1] = k, args[2] = combo_count, args[3] = segment_size
385
+ __global real1* min_energy_ptr,
386
+ __global int* min_index_ptr,
387
+ __local real1* loc_energy,
388
+ __local int* loc_index
389
+ ) {
390
+ __global const real1* G_data[4] = { G_data0, G_data1, G_data2, G_data3 };
391
+
392
+ const int n = args[0];
393
+ const int k = args[1];
394
+ const int combo_count = args[2];
395
+ const bool is_spin_glass = args[3];
396
+ const int segment_size = args[4];
397
+ int i = get_global_id(0);
398
+
399
+ prng_seed ^= (uint)i;
400
+
401
+ real1 best_energy = INFINITY;
402
+ int best_i = i;
403
+
404
+ for (; i < combo_count; i += MAX_PROC_ELEM) {
405
+ const int j = i * k;
406
+ const real1 energy = bootstrap_worker_sparse_segmented(best_theta, G_data, G_rows, G_cols, indices_array + j, k, n, segment_size, is_spin_glass);
407
+ if (energy < best_energy) {
408
+ best_energy = energy;
409
+ best_i = i;
410
+ } else if (((energy - best_energy) <= EPSILON) && ((xorshift32(&prng_seed) >> 31) & 1)) {
411
+ best_i = i;
412
+ }
413
+ }
414
+
415
+ const int lt_id = get_local_id(0);
416
+ const int lt_size = get_local_size(0);
417
+
418
+ loc_energy[lt_id] = best_energy;
419
+ loc_index[lt_id] = best_i;
420
+
421
+ for (int offset = lt_size >> 1; offset > 0; offset >>= 1) {
422
+ barrier(CLK_LOCAL_MEM_FENCE);
423
+ if (lt_id < offset) {
424
+ real1 hid_energy = loc_energy[lt_id + offset];
425
+ real1 lid_energy = loc_energy[lt_id];
426
+ if (hid_energy < lid_energy) {
427
+ loc_energy[lt_id] = hid_energy;
428
+ loc_index[lt_id] = loc_index[lt_id + offset];
429
+ } else if (((hid_energy - lid_energy) <= EPSILON) && ((xorshift32(&prng_seed) >> 31) & 1)) {
430
+ loc_index[lt_id] = loc_index[lt_id + offset];
431
+ }
432
+ }
433
+ }
434
+
435
+ if (lt_id == 0) {
436
+ min_energy_ptr[get_group_id(0)] = loc_energy[0];
437
+ min_index_ptr[get_group_id(0)] = loc_index[0];
438
+ }
439
+ }
440
+