PyQrackIsing 9.7.3__tar.gz → 9.7.5__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 (28) hide show
  1. {pyqrackising-9.7.3/pyqrackising.egg-info → pyqrackising-9.7.5}/PKG-INFO +1 -1
  2. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/README.md +2 -2
  3. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyproject.toml +1 -1
  4. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyqrackising/generate_tfim_samples.py +1 -1
  5. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyqrackising/kernels.cl +335 -9
  6. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyqrackising/maxcut_tfim_util.py +42 -8
  7. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyqrackising/spin_glass_solver.py +105 -35
  8. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyqrackising/spin_glass_solver_sparse.py +107 -35
  9. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyqrackising/spin_glass_solver_streaming.py +19 -19
  10. {pyqrackising-9.7.3 → pyqrackising-9.7.5/pyqrackising.egg-info}/PKG-INFO +1 -1
  11. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/setup.py +1 -1
  12. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/LICENSE.md +0 -0
  13. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/MANIFEST.in +0 -0
  14. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyqrackising/__init__.py +0 -0
  15. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyqrackising/convert_tensor_network_to_tsp.py +0 -0
  16. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyqrackising/maxcut_tfim.py +0 -0
  17. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyqrackising/maxcut_tfim_sparse.py +0 -0
  18. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyqrackising/maxcut_tfim_streaming.py +0 -0
  19. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyqrackising/otoc.py +0 -0
  20. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyqrackising/tfim_magnetization.py +0 -0
  21. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyqrackising/tfim_square_magnetization.py +0 -0
  22. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyqrackising/tsp.py +0 -0
  23. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyqrackising/tsp_maxcut.py +0 -0
  24. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyqrackising.egg-info/SOURCES.txt +0 -0
  25. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyqrackising.egg-info/dependency_links.txt +0 -0
  26. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyqrackising.egg-info/not-zip-safe +0 -0
  27. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/pyqrackising.egg-info/top_level.txt +0 -0
  28. {pyqrackising-9.7.3 → pyqrackising-9.7.5}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrackising
3
- Version: 9.7.3
3
+ Version: 9.7.5
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
@@ -185,9 +185,9 @@ Sometimes a solution (or at least near-solution) to a monster of a differential
185
185
 
186
186
  **Special thanks to OpenAI GPT "Elara," for help on the model and converting the original Python scripts to PyBind11, Numba, and PyOpenCL!**
187
187
 
188
- We reduce transverse field Ising model for globally uniform `J` and `h` parameters from a `2^n`-dimensional problem to an `(n+1)`-dimensional (heuristic but near-exact) form that suffers from no Trotter error. Upon noticing most time steps for parameters in a [TFIM experiment published by Quantinuum](https://arxiv.org/abs/2503.20870) had roughly a quarter to a third (or thereabouts) of their marginal probability in `|0>` state, it became obvious that transition to and from `|0>` state should dominate the mechanics, at least far from mean-field equilibrium. Further, the first transition therefore tends to be to or from any state with Hamming weight of 1 (in other words, 1 bit set to 1 and the rest reset 0, or `n` bits set for Hamming weight of `n`). Further, on a torus, probability of all states with Hamming weight of 1 would tend to be exactly symmetric. Assuming approximate symmetry in every respective Hamming weight, the requirement for the overall probability to converge to 1.0 or 100% in the limit of an infinite-dimensional Hilbert space suggests that Hamming weight marginal probability could be distributed like a geometric series. A small correction to exact symmetry should be made to favor _magnetic_ closeness of "like" bits to "like" bits (that is, geometric closeness on the torus of "1" bits to "1" bits and "0" bits to "0" bits), but this does not affect average global magnetization. Adding an oscillation component with angular frequency proportional to `J`, we find excellent agreement with Trotterization with a very small time step, for R^2 (coefficient of determination) of normalized marginal probability distribution of ideal Trotterized simulation as described by the `(n+1)`-dimensional approximate model, as well as for R^2 and RMSE (root-mean-square error) of global magnetization curve values.
188
+ We reduce transverse field Ising model for globally uniform `J` and `h` parameters from a `2^n`-dimensional problem to an `(n+1)`-dimensional (heuristic but near-exact) form that suffers from no Trotter error. Upon noticing most time steps for parameters in a [TFIM experiment published by Quantinuum](https://arxiv.org/abs/2503.20870) had roughly a quarter to a third (or thereabouts) of their marginal probability in `|0>` state, it became obvious that transition to and from `|0>` state should dominate the mechanics, at least far from mean-field equilibrium. Further, the first transition therefore tends to be to or from any state with Hamming weight of 1 (in other words, 1 bit set to 1 and the rest reset to 0, or `n` bits set for Hamming weight of `n`). Further, on a torus, probability of all states with Hamming weight of 1 would tend to be exactly symmetric. Assuming approximate symmetry in every respective Hamming weight, the requirement for the overall probability to converge to 1.0 or 100% in the limit of an infinite-dimensional Hilbert space suggests that Hamming weight marginal probability could be distributed like a geometric series. A small correction to exact symmetry should be made to favor _magnetic_ closeness of "like" bits to "like" bits (that is, geometric closeness on the torus of "1" bits to "1" bits and "0" bits to "0" bits), but this does not affect average global magnetization. Adding an oscillation component with angular frequency proportional to `J`, we find excellent agreement with Trotterization with a very small time step, for R^2 (coefficient of determination) of normalized marginal probability distribution of ideal Trotterized simulation as described by the `(n+1)`-dimensional approximate model, as well as for R^2 and RMSE (root-mean-square error) of global magnetization curve values.
189
189
 
190
- If the above paragraph and the model it describes are true, then it stands to reason that we should be able to apply the TFIM model to **NP-complete** heuristics, so long as we can adapt the model to spatially localized `J` and `h` and adiabatic time dependence of `h`. A reasonable guess for how to spatially localize `J` and `h` is to average the overall behavior for each and every qubit as if `J` and `h` were globally uniform from its local perspective. (`z` parameter is derived from nonzero edge weight count connectivity.) For adiabatic time-dependence of `h`, another reasonable refinement is to use simply **finite-difference simulation**. Initial state should probably be just **uniform superposition**, which implies a specific (non-uniform but regular) distribution of initial probabilities by Hamming weight dimension out of `(n+1)` possible Hamming weights. We observe that the _spatial magnetic effect_ qualitatively agrees with the demands of MAXCUT when it acts like a magnetic _repulsion,_ rather than magnetic attraction, in this case, but we can add that refinement on an arbitrary connectivity topology in just `O(n)` complexity per measurement shot. (This is a complete "recipe": the evidence that it works is the quality of NP-complete heuristic solutions at utility scale.)
190
+ If the above paragraph and the model it describes are true, then it stands to reason that we should be able to apply the TFIM model to **NP-complete** heuristics, so long as we can adapt the model to spatially localized `J` and `h` and adiabatic time dependence of `h`. A reasonable guess for how to spatially localize `J` and `h` is to average the overall behavior for each and every qubit as if `J` and `h` were globally uniform from its local perspective. (`z` parameter is derived from nonzero edge weight count connectivity.) For adiabatic time-dependence of `h`, another reasonable refinement is to use simply **finite-difference simulation**. Initial state should probably be just **uniform superposition**, which implies a specific (non-uniform but regular) distribution of initial probabilities by Hamming weight dimension over `(n+1)` possible Hamming weights. We observe that the _spatial magnetic effect_ qualitatively agrees with the demands of MAXCUT when it acts like a magnetic _repulsion,_ rather than magnetic attraction, in this case, but we can add that refinement on an arbitrary connectivity topology in just `O(n)` complexity per measurement shot. (This is a complete "recipe": the evidence that it works is the quality of NP-complete heuristic solutions at utility scale.)
191
191
 
192
192
  **Elara has drafted this statement, and Dan Strano, as author, agrees with it, and will hold to it:**
193
193
 
@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"
10
10
 
11
11
  [project]
12
12
  name = "pyqrackising"
13
- version = "9.7.3"
13
+ version = "9.7.5"
14
14
  requires-python = ">=3.8"
15
15
  description = "Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)"
16
16
  readme = {file = "README.txt", content-type = "text/markdown"}
@@ -116,7 +116,7 @@ def get_tfim_hamming_distribution(J=-1.0, h=2.0, z=4, theta=0.174532925199432957
116
116
 
117
117
  return bias / bias.sum()
118
118
 
119
- if h <= epsilon:
119
+ if abs(h) <= epsilon:
120
120
  bias = np.empty(n_qubits + 1, dtype=np.float64)
121
121
  if J > 0:
122
122
  bias[-1] = 1.0
@@ -627,10 +627,8 @@ real1 cut_worker_sparse_segmented(
627
627
 
628
628
  for (int u = 0; u < n; ++u) {
629
629
  const bool u_bit = get_bit(theta, u);
630
- const uint row_start = G_rows[u];
631
630
  const uint row_end = G_rows[u + 1];
632
-
633
- for (uint col = row_start; col < row_end; ++col) {
631
+ for (uint col = G_rows[u]; col < row_end; ++col) {
634
632
  const int v = G_cols[col];
635
633
  const real1 val = get_G_m(G_data, col, segment_size);
636
634
  const bool v_bit = get_bit(theta, v);
@@ -707,10 +705,8 @@ real1 single_bit_flip_worker_sparse_segmented(
707
705
  if (u == k) {
708
706
  u_bit = !u_bit;
709
707
  }
710
- const uint row_start = G_rows[u];
711
708
  const uint row_end = G_rows[u + 1];
712
-
713
- for (uint col = row_start; col < row_end; ++col) {
709
+ for (uint col = G_rows[u]; col < row_end; ++col) {
714
710
  const int v = G_cols[col];
715
711
  const real1 val = get_G_m(G_data, col, segment_size);
716
712
  bool v_bit = get_const_bit(theta, v);
@@ -783,10 +779,8 @@ real1 double_bit_flip_worker_sparse_segmented(
783
779
  if ((u == k) || (u == l)) {
784
780
  u_bit = !u_bit;
785
781
  }
786
- const uint row_start = G_rows[u];
787
782
  const uint row_end = G_rows[u + 1];
788
-
789
- for (uint col = row_start; col < row_end; ++col) {
783
+ for (uint col = G_rows[u]; col < row_end; ++col) {
790
784
  const int v = G_cols[col];
791
785
  const real1 val = get_G_m(G_data, col, segment_size);
792
786
  bool v_bit = get_const_bit(theta, v);
@@ -855,3 +849,335 @@ __kernel void double_bit_flips_sparse_segmented(
855
849
 
856
850
  reduce_energy_index(best_energy, best_i, loc_energy, loc_index, max_energy_ptr, max_index_ptr);
857
851
  }
852
+
853
+ void reduce_energy_index_block(real1 energy, int i, int block, __local real1* loc_energy, __local int* loc_index, __local int* loc_block, __global real1* max_energy_ptr, __global int* max_index_ptr, __global int* max_block_ptr) {
854
+ const int lt_id = get_local_id(0);
855
+ const int lt_size = get_local_size(0);
856
+
857
+ loc_energy[lt_id] = energy;
858
+ loc_index[lt_id] = i;
859
+ loc_block[lt_id] = block;
860
+
861
+ // Reduce within workgroup
862
+ for (int offset = lt_size >> 1; offset > 0; offset >>= 1) {
863
+ barrier(CLK_LOCAL_MEM_FENCE);
864
+ real1 hid_energy, lid_energy;
865
+ if (lt_id < offset) {
866
+ hid_energy = loc_energy[lt_id + offset];
867
+ lid_energy = loc_energy[lt_id];
868
+ if (hid_energy > lid_energy) {
869
+ loc_energy[lt_id] = hid_energy;
870
+ loc_index[lt_id] = loc_index[lt_id + offset];
871
+ loc_block[lt_id] = loc_block[lt_id + offset];
872
+ }
873
+ }
874
+ }
875
+
876
+ barrier(CLK_LOCAL_MEM_FENCE);
877
+
878
+ // Write out per-group result
879
+ if (lt_id == 0) {
880
+ max_energy_ptr[get_group_id(0)] = loc_energy[0];
881
+ max_index_ptr[get_group_id(0)] = loc_index[0];
882
+ max_block_ptr[get_group_id(0)] = loc_block[0];
883
+ }
884
+ }
885
+
886
+ inline bool get_local_bit(ulong* theta, const size_t u) {
887
+ return (theta[u >> 6U] >> (u & 63U)) & 1U;
888
+ }
889
+
890
+ inline size_t gray_code_next(ulong* theta, const size_t curr_idx, const size_t offset) {
891
+ size_t prev = curr_idx;
892
+ size_t curr = curr_idx + 1U;
893
+ prev = prev ^ (prev >> 1U);
894
+ curr = curr ^ (curr >> 1U);
895
+ size_t diff = prev ^ curr;
896
+ size_t flip_bit = 0;
897
+ while (!((diff >> flip_bit) & 1U)) {
898
+ ++flip_bit;
899
+ }
900
+ flip_bit += offset;
901
+ theta[flip_bit >> 6U] ^= 1UL << (flip_bit & 63U);
902
+
903
+ return flip_bit;
904
+ }
905
+
906
+ __kernel void gray(
907
+ __global const real1* G_m,
908
+ __constant ulong* theta,
909
+ __constant int* args,
910
+ __global ulong* theta_out,
911
+ __global real1* energy_out
912
+ ) {
913
+ const int n = args[0];
914
+ const bool is_spin_glass = args[1];
915
+ const int gray_iterations = args[2];
916
+ const int blocks = (n + 63) / 64;
917
+ const int last_block = blocks - 1;
918
+
919
+ int i = get_global_id(0);
920
+ const int max_i = get_global_size(0);
921
+
922
+ ulong theta_local[2048];
923
+ for (int b = 0; b < blocks; ++b) {
924
+ theta_local[b] = theta[b];
925
+ }
926
+
927
+ // Initialize different seed per thread
928
+ const int seed = i ^ (i >> 1);
929
+ for (int b = 0; b < 64; ++b) {
930
+ theta_local[last_block] ^= (seed >> (63U - b)) << b;
931
+ }
932
+
933
+ real1 best_energy = -INFINITY;
934
+ int best_i = i;
935
+ int best_block = 0U;
936
+ for (; i < gray_iterations; i += max_i) {
937
+ for (int block = 0; block < blocks; ++block) {
938
+ const size_t flip_bit = gray_code_next(theta_local, i, block << 6U);
939
+ real1 energy = ZERO_R1;
940
+ for (uint u = 0; u < n; u++) {
941
+ const size_t u_offset = u * n;
942
+ int u_bit = get_local_bit(theta_local, u);
943
+ for (uint v = u + 1; v < n; v++) {
944
+ const int v_bit = get_local_bit(theta_local, v);
945
+ const real1 val = G_m[u_offset + v];
946
+ if (u_bit != v_bit) {
947
+ energy += val;
948
+ } else if (is_spin_glass) {
949
+ energy -= val;
950
+ }
951
+ }
952
+ }
953
+
954
+ if (energy > best_energy) {
955
+ best_energy = energy;
956
+ best_i = i;
957
+ } else {
958
+ theta_local[flip_bit >> 6U] ^= 1UL << (flip_bit & 63U);
959
+ }
960
+ }
961
+ }
962
+
963
+ i = get_global_id(0);
964
+ const size_t offset = i * blocks;
965
+ for (int b = 0; b < blocks; ++b) {
966
+ theta_out[offset + b] = theta_local[b];
967
+ }
968
+ energy_out[i] = best_energy;
969
+ }
970
+
971
+ __kernel void gray_segmented(
972
+ __global const real1* G_m0,
973
+ __global const real1* G_m1,
974
+ __global const real1* G_m2,
975
+ __global const real1* G_m3,
976
+ __constant ulong* theta,
977
+ __constant int* args,
978
+ __global ulong* theta_out,
979
+ __global real1* energy_out
980
+ ) {
981
+ __global const real1* G_m[4] = { G_m0, G_m1, G_m2, G_m3 };
982
+
983
+ const int n = args[0];
984
+ const bool is_spin_glass = args[1];
985
+ const int gray_iterations = args[2];
986
+ const int segment_size = args[3];
987
+ const int blocks = (n + 63) / 64;
988
+ const int last_block = blocks - 1;
989
+
990
+ int i = get_global_id(0);
991
+ const int max_i = get_global_size(0);
992
+
993
+ ulong theta_local[2048];
994
+ for (int b = 0; b < blocks; ++b) {
995
+ theta_local[b] = theta[b];
996
+ }
997
+
998
+ // Initialize different seed per thread
999
+ const int seed = i ^ (i >> 1);
1000
+ for (int b = 0; b < 64; ++b) {
1001
+ theta_local[last_block] ^= (seed >> (63U - b)) << b;
1002
+ }
1003
+
1004
+ real1 best_energy = -INFINITY;
1005
+ int best_i = i;
1006
+ int best_block = 0U;
1007
+ for (; i < gray_iterations; i += max_i) {
1008
+ for (int block = 0; block < blocks; ++block) {
1009
+ const size_t flip_bit = gray_code_next(theta_local, i, block << 6U);
1010
+ real1 energy = ZERO_R1;
1011
+ for (uint u = 0; u < n; u++) {
1012
+ const size_t u_offset = u * n;
1013
+ int u_bit = get_local_bit(theta_local, u);
1014
+ for (uint v = u + 1; v < n; v++) {
1015
+ const int v_bit = get_local_bit(theta_local, v);
1016
+ const real1 val = get_G_m(G_m, u_offset + v, segment_size);
1017
+ if (u_bit != v_bit) {
1018
+ energy += val;
1019
+ } else if (is_spin_glass) {
1020
+ energy -= val;
1021
+ }
1022
+ }
1023
+ }
1024
+
1025
+ if (energy > best_energy) {
1026
+ best_energy = energy;
1027
+ best_i = i;
1028
+ } else {
1029
+ theta_local[flip_bit >> 6U] ^= 1UL << (flip_bit & 63U);
1030
+ }
1031
+ }
1032
+ }
1033
+
1034
+ i = get_global_id(0);
1035
+ const size_t offset = i * blocks;
1036
+ for (int b = 0; b < blocks; ++b) {
1037
+ theta_out[offset + b] = theta_local[b];
1038
+ }
1039
+ energy_out[i] = best_energy;
1040
+ }
1041
+
1042
+ __kernel void gray_sparse(
1043
+ __global const real1* G_data,
1044
+ __global const uint* G_rows,
1045
+ __global const uint* G_cols,
1046
+ __constant ulong* theta,
1047
+ __constant int* args,
1048
+ __global ulong* theta_out,
1049
+ __global real1* energy_out
1050
+ ) {
1051
+ const int n = args[0];
1052
+ const bool is_spin_glass = args[1];
1053
+ const int gray_iterations = args[2];
1054
+ const int blocks = (n + 63) / 64;
1055
+ const int last_block = blocks - 1;
1056
+
1057
+ int i = get_global_id(0);
1058
+ const int max_i = get_global_size(0);
1059
+
1060
+ ulong theta_local[2048];
1061
+ for (int b = 0; b < blocks; ++b) {
1062
+ theta_local[b] = theta[b];
1063
+ }
1064
+
1065
+ // Initialize different seed per thread
1066
+ const int seed = i ^ (i >> 1);
1067
+ for (int b = 0; b < 64; ++b) {
1068
+ theta_local[last_block] ^= (seed >> (63U - b)) << b;
1069
+ }
1070
+
1071
+ real1 best_energy = -INFINITY;
1072
+ int best_i = i;
1073
+ int best_block = 0U;
1074
+ for (; i < gray_iterations; i += max_i) {
1075
+ for (int block = 0; block < blocks; ++block) {
1076
+ const size_t flip_bit = gray_code_next(theta_local, i, block << 6U);
1077
+ real1 energy = ZERO_R1;
1078
+ for (uint u = 0; u < n; u++) {
1079
+ int u_bit = get_local_bit(theta_local, u);
1080
+ const size_t mCol = G_rows[u + 1];
1081
+ for (int col = G_rows[u]; col < mCol; ++col) {
1082
+ const int v = G_cols[col];
1083
+ const real1 val = G_data[col];
1084
+ bool v_bit = get_local_bit(theta_local, v);
1085
+ if (u_bit != v_bit) {
1086
+ energy += val;
1087
+ } else if (is_spin_glass) {
1088
+ energy -= val;
1089
+ }
1090
+ }
1091
+ }
1092
+
1093
+ if (energy > best_energy) {
1094
+ best_energy = energy;
1095
+ best_i = i;
1096
+ } else {
1097
+ theta_local[flip_bit >> 6U] ^= 1UL << (flip_bit & 63U);
1098
+ }
1099
+ }
1100
+ }
1101
+
1102
+ i = get_global_id(0);
1103
+ const size_t offset = i * blocks;
1104
+ for (int b = 0; b < blocks; ++b) {
1105
+ theta_out[offset + b] = theta_local[b];
1106
+ }
1107
+ energy_out[i] = best_energy;
1108
+ }
1109
+
1110
+ __kernel void gray_sparse_segmented(
1111
+ __global const real1* G_data0,
1112
+ __global const real1* G_data1,
1113
+ __global const real1* G_data2,
1114
+ __global const real1* G_data3,
1115
+ __global const uint* G_rows,
1116
+ __global const uint* G_cols,
1117
+ __constant ulong* theta,
1118
+ __constant int* args,
1119
+ __global ulong* theta_out,
1120
+ __global real1* energy_out
1121
+ ) {
1122
+ __global const real1* G_data[4] = { G_data0, G_data1, G_data2, G_data3 };
1123
+
1124
+ const int n = args[0];
1125
+ const bool is_spin_glass = args[1];
1126
+ const int gray_iterations = args[2];
1127
+ const int segment_size = args[3];
1128
+ const int blocks = (n + 63) / 64;
1129
+ const int last_block = blocks - 1;
1130
+
1131
+ int i = get_global_id(0);
1132
+ const int max_i = get_global_size(0);
1133
+
1134
+ ulong theta_local[2048];
1135
+ for (int b = 0; b < blocks; ++b) {
1136
+ theta_local[b] = theta[b];
1137
+ }
1138
+
1139
+ // Initialize different seed per thread
1140
+ const int seed = i ^ (i >> 1);
1141
+ for (int b = 0; b < 64; ++b) {
1142
+ theta_local[last_block] ^= (seed >> (63U - b)) << b;
1143
+ }
1144
+
1145
+ real1 best_energy = -INFINITY;
1146
+ int best_i = i;
1147
+ int best_block = 0U;
1148
+ for (; i < gray_iterations; i += max_i) {
1149
+ for (int block = 0; block < blocks; ++block) {
1150
+ const size_t flip_bit = gray_code_next(theta_local, i, block << 6U);
1151
+ real1 energy = ZERO_R1;
1152
+ for (uint u = 0; u < n; u++) {
1153
+ const size_t u_offset = u * n;
1154
+ int u_bit = get_local_bit(theta_local, u);
1155
+ const uint row_end = G_rows[u + 1];
1156
+ for (uint col = G_rows[u]; col < row_end; ++col) {
1157
+ const int v = G_cols[col];
1158
+ const real1 val = get_G_m(G_data, col, segment_size);
1159
+ const bool v_bit = get_local_bit(theta_local, v);
1160
+ if (u_bit != v_bit) {
1161
+ energy += val;
1162
+ } else if (is_spin_glass) {
1163
+ energy -= val;
1164
+ }
1165
+ }
1166
+ }
1167
+
1168
+ if (energy > best_energy) {
1169
+ best_energy = energy;
1170
+ best_i = i;
1171
+ } else {
1172
+ theta_local[flip_bit >> 6U] ^= 1UL << (flip_bit & 63U);
1173
+ }
1174
+ }
1175
+ }
1176
+
1177
+ i = get_global_id(0);
1178
+ const size_t offset = i * blocks;
1179
+ for (int b = 0; b < blocks; ++b) {
1180
+ theta_out[offset + b] = theta_local[b];
1181
+ }
1182
+ energy_out[i] = best_energy;
1183
+ }
@@ -7,7 +7,8 @@ from scipy.sparse import lil_matrix
7
7
 
8
8
 
9
9
  class OpenCLContext:
10
- def __init__(self, a, b, g, d, e, f, c, q, i, j, k, l, m, n, o, p, x, y, z, w):
10
+ def __init__(self, a, b, g, d, e, f, c, q, i, j, k, l, m, n, o, p, x, y, z, w, s, t, u, v):
11
+ self.GRAY_NODE_LIMIT = 131072
11
12
  self.MAX_GPU_PROC_ELEM = a
12
13
  self.IS_OPENCL_AVAILABLE = b
13
14
  self.work_group_size = g
@@ -28,6 +29,10 @@ class OpenCLContext:
28
29
  self.double_bit_flips_sparse_kernel = y
29
30
  self.double_bit_flips_segmented_kernel = z
30
31
  self.double_bit_flips_sparse_segmented_kernel = w
32
+ self.gray_kernel = s
33
+ self.gray_segmented_kernel = t
34
+ self.gray_sparse_kernel = u
35
+ self.gray_sparse_segmented_kernel = v
31
36
 
32
37
  IS_OPENCL_AVAILABLE = True
33
38
  ctx = None
@@ -49,6 +54,10 @@ double_bit_flips_kernel = None
49
54
  double_bit_flips_sparse_kernel = None
50
55
  double_bit_flips_segmented_kernel = None
51
56
  double_bit_flips_sparse_segmented_kernel = None
57
+ gray_kernel = None
58
+ gray_segmented_kernel = None
59
+ gray_sparse_kernel = None
60
+ gray_sparse_segmented_kernel = None
52
61
 
53
62
  dtype_bits = int(os.getenv('PYQRACKISING_FPPOW', '5'))
54
63
  kernel_src = ''
@@ -109,6 +118,10 @@ try:
109
118
  double_bit_flips_sparse_kernel = program.double_bit_flips_sparse
110
119
  double_bit_flips_segmented_kernel = program.double_bit_flips_segmented
111
120
  double_bit_flips_sparse_segmented_kernel = program.double_bit_flips_sparse_segmented
121
+ gray_kernel = program.gray
122
+ gray_segmented_kernel = program.gray_segmented
123
+ gray_sparse_kernel = program.gray_sparse
124
+ gray_sparse_segmented_kernel = program.gray_sparse_segmented
112
125
 
113
126
  work_group_size = calculate_cut_kernel.get_work_group_info(
114
127
  cl.kernel_work_group_info.PREFERRED_WORK_GROUP_SIZE_MULTIPLE,
@@ -120,12 +133,12 @@ except ImportError:
120
133
  IS_OPENCL_AVAILABLE = False
121
134
  print("PyOpenCL not installed. (If you have any OpenCL accelerator devices with available ICDs, you might want to optionally install pyopencl.)")
122
135
 
123
- opencl_context = OpenCLContext(compute_units, IS_OPENCL_AVAILABLE, work_group_size, dtype, epsilon, max_alloc, ctx, queue, calculate_cut_kernel, calculate_cut_sparse_kernel, calculate_cut_segmented_kernel, calculate_cut_sparse_segmented_kernel, single_bit_flips_kernel, single_bit_flips_sparse_kernel, single_bit_flips_segmented_kernel, single_bit_flips_sparse_segmented_kernel, double_bit_flips_kernel, double_bit_flips_sparse_kernel, double_bit_flips_segmented_kernel, double_bit_flips_sparse_segmented_kernel)
136
+ opencl_context = OpenCLContext(compute_units, IS_OPENCL_AVAILABLE, work_group_size, dtype, epsilon, max_alloc, ctx, queue, calculate_cut_kernel, calculate_cut_sparse_kernel, calculate_cut_segmented_kernel, calculate_cut_sparse_segmented_kernel, single_bit_flips_kernel, single_bit_flips_sparse_kernel, single_bit_flips_segmented_kernel, single_bit_flips_sparse_segmented_kernel, double_bit_flips_kernel, double_bit_flips_sparse_kernel, double_bit_flips_segmented_kernel, double_bit_flips_sparse_segmented_kernel, gray_kernel, gray_segmented_kernel, gray_sparse_kernel, gray_sparse_segmented_kernel)
124
137
  heuristic_threshold = 24
125
138
  heuristic_threshold_sparse = 23
126
139
 
127
140
 
128
- def setup_opencl(l, g, args_np):
141
+ def setup_opencl(l, g, args_np, is_gray=False):
129
142
  ctx = opencl_context.ctx
130
143
  queue = opencl_context.queue
131
144
  dtype = opencl_context.dtype
@@ -140,15 +153,21 @@ def setup_opencl(l, g, args_np):
140
153
  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
141
154
  global_size = min(((g + local_size - 1) // local_size) * local_size, max_global_size)
142
155
 
156
+ max_energy_host = np.empty(global_size // local_size, dtype=dtype)
157
+ max_energy_buf = cl.Buffer(ctx, mf.WRITE_ONLY, max_energy_host.nbytes)
158
+
159
+ if is_gray:
160
+ max_theta_host = np.empty(((args_np[0] + 63) // 64) * (global_size // local_size), dtype=np.int64)
161
+ max_theta_buf = cl.Buffer(ctx, mf.WRITE_ONLY, max_theta_host.nbytes)
162
+
163
+ return local_size, global_size, args_buf, max_energy_host, max_theta_host, max_energy_buf, max_theta_buf
164
+
143
165
  # Local memory allocation (1 float per work item)
144
166
  local_energy_buf = cl.LocalMemory(np.dtype(dtype).itemsize * local_size)
145
167
  local_index_buf = cl.LocalMemory(np.dtype(np.int32).itemsize * local_size)
146
168
 
147
169
  # Allocate max_energy and max_index result buffers per workgroup
148
- max_energy_host = np.empty(global_size // local_size, dtype=dtype)
149
170
  max_index_host = np.empty(global_size // local_size, dtype=np.int32)
150
-
151
- max_energy_buf = cl.Buffer(ctx, mf.WRITE_ONLY, max_energy_host.nbytes)
152
171
  max_index_buf = cl.Buffer(ctx, mf.WRITE_ONLY, max_index_host.nbytes)
153
172
 
154
173
  return local_size, global_size, args_buf, local_energy_buf, local_index_buf, max_energy_host, max_index_host, max_energy_buf, max_index_buf
@@ -228,6 +247,19 @@ def make_best_theta_buf(theta):
228
247
 
229
248
  return theta_buf
230
249
 
250
+ def make_best_theta_buf_64(theta):
251
+ n = theta.shape[0]
252
+ n64 = (n + 63) >> 6
253
+ theta_np = np.zeros(n64, dtype=np.uint64)
254
+ for i in range(n):
255
+ if theta[i]:
256
+ theta_np[(i >> 6)] |= 1 << (i & 63)
257
+
258
+ mf = cl.mem_flags
259
+ theta_buf = cl.Buffer(opencl_context.ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=theta_np)
260
+
261
+ return theta_buf
262
+
231
263
 
232
264
  @njit(parallel=True)
233
265
  def convert_bool_to_uint(samples):
@@ -529,8 +561,10 @@ def gray_code_next(state, curr_idx, offset):
529
561
  prev = prev ^ (prev >> 1)
530
562
  curr = curr ^ (curr >> 1)
531
563
  diff = prev ^ curr
532
- flip_bit = int(np.log2(diff))
533
- state[offset + flip_bit] = not state[offset + flip_bit]
564
+ flip_bit = int(np.log2(diff)) + offset
565
+ state[flip_bit] = not state[flip_bit]
566
+
567
+ return flip_bit
534
568
 
535
569
 
536
570
  @njit
@@ -1,5 +1,5 @@
1
1
  from .maxcut_tfim import maxcut_tfim
2
- from .maxcut_tfim_util import compute_cut, compute_energy, get_cut, gray_code_next, gray_mutation, heuristic_threshold, int_to_bitstring, make_G_m_buf, make_best_theta_buf, opencl_context, setup_opencl
2
+ from .maxcut_tfim_util import compute_cut, compute_energy, get_cut, gray_code_next, gray_mutation, heuristic_threshold, int_to_bitstring, make_G_m_buf, make_best_theta_buf, make_best_theta_buf_64, opencl_context, setup_opencl
3
3
  import networkx as nx
4
4
  import numpy as np
5
5
  from numba import njit, prange
@@ -15,6 +15,7 @@ except ImportError:
15
15
 
16
16
  dtype = opencl_context.dtype
17
17
  wgs = opencl_context.work_group_size
18
+ gnl = opencl_context.GRAY_NODE_LIMIT
18
19
 
19
20
 
20
21
  @njit(parallel=True)
@@ -105,7 +106,7 @@ def run_double_bit_flips(best_theta, is_spin_glass, G_m, thread_count):
105
106
 
106
107
  @njit(parallel=True)
107
108
  def pick_gray_seeds(best_theta, thread_count, gray_seed_multiple, G_m, n, is_spin_glass):
108
- blocks = (n + 63) // 64
109
+ blocks = (n + 63) >> 6
109
110
  block_size = thread_count * gray_seed_multiple
110
111
  seed_count = block_size * blocks
111
112
 
@@ -115,14 +116,14 @@ def pick_gray_seeds(best_theta, thread_count, gray_seed_multiple, G_m, n, is_spi
115
116
  if is_spin_glass:
116
117
  for s in prange(seed_count):
117
118
  i = s % block_size
118
- offset = (s // block_size) * 64
119
+ offset = (s // block_size) << 6
119
120
  seed = gray_mutation(i, best_theta, offset)
120
121
  energies[s] = compute_energy(seed, G_m, n)
121
122
  seeds[s] = seed
122
123
  else:
123
124
  for s in prange(seed_count):
124
125
  i = s % block_size
125
- offset = (s // block_size) * 64
126
+ offset = (s // block_size) << 6
126
127
  seed = gray_mutation(i, best_theta, offset)
127
128
  energies[s] = compute_cut(seed, G_m, n)
128
129
  seeds[s] = seed
@@ -143,42 +144,42 @@ def pick_gray_seeds(best_theta, thread_count, gray_seed_multiple, G_m, n, is_spi
143
144
  def run_gray_optimization(best_theta, iterators, energies, gray_iterations, thread_count, is_spin_glass, G_m):
144
145
  n = len(best_theta)
145
146
  thread_iterations = (gray_iterations + thread_count - 1) // thread_count
146
- blocks = (n + 63) // 64
147
-
148
- states = np.empty((thread_count, n), dtype=np.bool_)
147
+ blocks = (n + 63) >> 6
149
148
 
150
149
  if is_spin_glass:
151
150
  for i in prange(thread_count):
152
- iterator = iterators[i].copy()
153
- best_energy, best_iterator = energies[i], iterator.copy()
151
+ iterator = iterators[i]
152
+ best_energy = energies[i]
154
153
  for curr_idx in range(thread_iterations):
155
154
  for block in range(blocks):
156
- gray_code_next(iterator, curr_idx, block * 64)
155
+ flip_bit = gray_code_next(iterator, curr_idx, block << 6)
157
156
  energy = compute_energy(iterator, G_m, n)
158
157
  if energy > best_energy:
159
- best_iterator, best_energy = iterator.copy(), energy
158
+ best_energy = energy
160
159
  else:
161
- iterator = best_iterator.copy()
160
+ # Revert iterator
161
+ iterator[flip_bit] = not iterator[flip_bit]
162
162
  if best_energy > energies[i]:
163
- states[i], energies[i] = best_iterator.copy(), best_energy
163
+ energies[i] = best_energy
164
164
  else:
165
165
  for i in prange(thread_count):
166
- iterator = iterators[i].copy()
167
- best_energy, best_iterator = energies[i], iterator.copy()
166
+ iterator = iterators[i]
167
+ best_energy = energies[i]
168
168
  for curr_idx in range(thread_iterations):
169
169
  for block in range(blocks):
170
- gray_code_next(iterator, curr_idx, block * 64)
170
+ flip_bit = gray_code_next(iterator, curr_idx, block << 6)
171
171
  energy = compute_cut(iterator, G_m, n)
172
172
  if energy > best_energy:
173
- best_iterator, best_energy = iterator.copy(), energy
173
+ best_energy = energy
174
174
  else:
175
- iterator = best_iterator.copy()
175
+ # Revert iterator
176
+ iterator[flip_bit] = not iterator[flip_bit]
176
177
  if best_energy > energies[i]:
177
- states[i], energies[i] = best_iterator.copy(), best_energy
178
+ energies[i] = best_energy
178
179
 
179
180
  best_index = np.argmax(energies)
180
181
  best_energy = energies[best_index]
181
- best_state = states[best_index]
182
+ best_state = iterators[best_index]
182
183
 
183
184
  return best_energy, best_state
184
185
 
@@ -255,6 +256,64 @@ def run_bit_flips_opencl(is_double, n, kernel, best_energy, theta, theta_buf, G_
255
256
  return energy, theta
256
257
 
257
258
 
259
+ def run_gray_search_opencl(n, kernel, best_energy, theta, theta_buf, G_m_buf, is_segmented, local_size, global_size, args_buf, max_energy_host, max_theta_host, max_energy_buf, max_theta_buf):
260
+ queue = opencl_context.queue
261
+
262
+ # Set kernel args
263
+ if is_segmented:
264
+ kernel.set_args(
265
+ G_m_buf[0],
266
+ G_m_buf[1],
267
+ G_m_buf[2],
268
+ G_m_buf[3],
269
+ theta_buf,
270
+ args_buf,
271
+ max_theta_buf,
272
+ max_energy_buf
273
+ )
274
+ else:
275
+ kernel.set_args(
276
+ G_m_buf,
277
+ theta_buf,
278
+ args_buf,
279
+ max_theta_buf,
280
+ max_energy_buf
281
+ )
282
+
283
+ cl.enqueue_nd_range_kernel(queue, kernel, (global_size,), (local_size,))
284
+
285
+ # Read results
286
+ cl.enqueue_copy(queue, max_energy_host, max_energy_buf)
287
+ queue.finish()
288
+
289
+ # Queue read for results we might not need
290
+ cl.enqueue_copy(queue, max_theta_host, max_theta_buf)
291
+
292
+ # Find global minimum
293
+ best_x = np.argmax(max_energy_host)
294
+ energy = max_energy_host[best_x]
295
+
296
+ if energy <= best_energy:
297
+ # No improvement: we can exit early
298
+ return best_energy, theta
299
+
300
+ # We need the best index
301
+ queue.finish()
302
+
303
+ blocks = (n + 63) // 64
304
+ offset = best_x * blocks
305
+ for b in range(blocks):
306
+ s = max_theta_host[best_x]
307
+ b_offset = b << 6
308
+ for i in range(64):
309
+ j = b_offset + i
310
+ if j >= n:
311
+ break
312
+ theta[j] = (s >> i) & 1
313
+
314
+ return energy, theta
315
+
316
+
258
317
  def spin_glass_solver(
259
318
  G,
260
319
  quality=None,
@@ -343,9 +402,16 @@ def spin_glass_solver(
343
402
  if is_segmented:
344
403
  single_bit_flips_kernel = opencl_context.single_bit_flips_segmented_kernel
345
404
  double_bit_flips_kernel = opencl_context.double_bit_flips_segmented_kernel
405
+ gray_kernel = opencl_context.gray_segmented_kernel
346
406
  else:
347
407
  single_bit_flips_kernel = opencl_context.single_bit_flips_kernel
348
408
  double_bit_flips_kernel = opencl_context.double_bit_flips_kernel
409
+ gray_kernel = opencl_context.gray_kernel
410
+
411
+ if n_qubits <= gnl:
412
+ gray_work_group_size = opencl_context.MAX_GPU_PROC_ELEM
413
+ gray_args = setup_opencl(1, gray_work_group_size, np.array([n_qubits, is_spin_glass, (gray_iterations + gray_work_group_size - 1) // gray_work_group_size, segment_size]), True)
414
+ gray_kernel = opencl_context.gray_segmented_kernel if is_segmented else opencl_context.gray_kernel
349
415
 
350
416
  thread_count = os.cpu_count() ** 2
351
417
  improved = True
@@ -376,21 +442,25 @@ def spin_glass_solver(
376
442
  improved = True
377
443
  continue
378
444
 
379
- # Gray code with default O(n^3)
380
- iterators, energies = pick_gray_seeds(best_theta, thread_count, gray_seed_multiple, G_m, n_qubits, is_spin_glass)
381
- energy, state = energies[0], iterators[0]
382
- if energy > max_energy:
383
- max_energy = energy
384
- best_theta = state
385
- improved = True
386
- continue
387
-
388
- energy, state = run_gray_optimization(best_theta, iterators, energies, gray_iterations, thread_count, is_spin_glass, G_m)
389
- if energy > max_energy:
390
- max_energy = energy
391
- best_theta = state
392
- improved = True
393
- continue
445
+ if is_opencl and (n_qubits <= gnl):
446
+ theta_buf_64 = make_best_theta_buf_64(best_theta)
447
+ energy, state = run_gray_search_opencl(n_qubits, gray_kernel, max_energy, best_theta, theta_buf_64, G_m_buf, is_segmented, *gray_args)
448
+ else:
449
+ # Gray code with default O(n^3)
450
+ iterators, energies = pick_gray_seeds(best_theta, thread_count, gray_seed_multiple, G_m, n_qubits, is_spin_glass)
451
+ energy, state = energies[0], iterators[0]
452
+ if energy > max_energy:
453
+ max_energy = energy
454
+ best_theta = state
455
+ improved = True
456
+ continue
457
+
458
+ energy, state = run_gray_optimization(best_theta, iterators, energies, gray_iterations, thread_count, is_spin_glass, G_m)
459
+ if energy > max_energy:
460
+ max_energy = energy
461
+ best_theta = state
462
+ improved = True
463
+ continue
394
464
 
395
465
  # Post-reheat phase
396
466
  reheat_theta = state
@@ -1,5 +1,5 @@
1
1
  from .maxcut_tfim_sparse import maxcut_tfim_sparse
2
- from .maxcut_tfim_util import compute_cut_sparse, compute_energy_sparse, get_cut, gray_code_next, gray_mutation, heuristic_threshold_sparse, int_to_bitstring, make_G_m_csr_buf, make_best_theta_buf, opencl_context, setup_opencl, to_scipy_sparse_upper_triangular
2
+ from .maxcut_tfim_util import compute_cut_sparse, compute_energy_sparse, get_cut, gray_code_next, gray_mutation, heuristic_threshold_sparse, int_to_bitstring, make_G_m_csr_buf, make_best_theta_buf, make_best_theta_buf_64, opencl_context, setup_opencl, to_scipy_sparse_upper_triangular
3
3
  import networkx as nx
4
4
  import numpy as np
5
5
  from numba import njit, prange
@@ -15,6 +15,7 @@ except ImportError:
15
15
 
16
16
  dtype = opencl_context.dtype
17
17
  wgs = opencl_context.work_group_size
18
+ gnl = opencl_context.GRAY_NODE_LIMIT
18
19
 
19
20
 
20
21
  @njit(parallel=True)
@@ -105,7 +106,7 @@ def run_double_bit_flips(best_theta, is_spin_glass, G_data, G_rows, G_cols, thre
105
106
 
106
107
  @njit(parallel=True)
107
108
  def pick_gray_seeds(best_theta, thread_count, gray_seed_multiple, G_data, G_rows, G_cols, n, is_spin_glass):
108
- blocks = (n + 63) // 64
109
+ blocks = (n + 63) >> 6
109
110
  block_size = thread_count * gray_seed_multiple
110
111
  seed_count = block_size * blocks
111
112
 
@@ -115,14 +116,14 @@ def pick_gray_seeds(best_theta, thread_count, gray_seed_multiple, G_data, G_rows
115
116
  if is_spin_glass:
116
117
  for s in prange(seed_count):
117
118
  i = s % block_size
118
- offset = (s // block_size) * 64
119
+ offset = (s // block_size) << 6
119
120
  seed = gray_mutation(i, best_theta, offset)
120
121
  energies[s] = compute_energy_sparse(seed, G_data, G_rows, G_cols, n)
121
122
  seeds[s] = seed
122
123
  else:
123
124
  for s in prange(seed_count):
124
125
  i = s % block_size
125
- offset = (s // block_size) * 64
126
+ offset = (s // block_size) << 6
126
127
  seed = gray_mutation(i, best_theta, offset)
127
128
  energies[s] = compute_cut_sparse(seed, G_data, G_rows, G_cols, n)
128
129
  seeds[s] = seed
@@ -143,42 +144,42 @@ def pick_gray_seeds(best_theta, thread_count, gray_seed_multiple, G_data, G_rows
143
144
  def run_gray_optimization(best_theta, iterators, energies, gray_iterations, thread_count, is_spin_glass, G_data, G_rows, G_cols):
144
145
  n = len(best_theta)
145
146
  thread_iterations = (gray_iterations + thread_count - 1) // thread_count
146
- blocks = (n + 63) // 64
147
-
148
- states = np.empty((thread_count, n), dtype=np.bool_)
147
+ blocks = (n + 63) >> 6
149
148
 
150
149
  if is_spin_glass:
151
150
  for i in prange(thread_count):
152
- iterator = iterators[i].copy()
153
- best_energy, best_iterator = energies[i], iterator.copy()
151
+ iterator = iterators[i]
152
+ best_energy = energies[i]
154
153
  for curr_idx in range(thread_iterations):
155
154
  for block in range(blocks):
156
- gray_code_next(iterator, curr_idx, block * 64)
155
+ flip_bit = gray_code_next(iterator, curr_idx, block << 6)
157
156
  energy = compute_energy_sparse(iterator, G_data, G_rows, G_cols, n)
158
157
  if energy > best_energy:
159
- best_iterator, best_energy = iterator.copy(), energy
158
+ best_energy = energy
160
159
  else:
161
- iterator = best_iterator.copy()
160
+ # Revert iterator
161
+ iterator[flip_bit] = not iterator[flip_bit]
162
162
  if best_energy > energies[i]:
163
- states[i], energies[i] = best_iterator.copy(), best_energy
163
+ energies[i] = best_energy
164
164
  else:
165
165
  for i in prange(thread_count):
166
- iterator = iterators[i].copy()
167
- best_energy, best_iterator = energies[i], iterator.copy()
166
+ iterator = iterators[i]
167
+ best_energy = energies[i]
168
168
  for curr_idx in range(thread_iterations):
169
169
  for block in range(blocks):
170
- gray_code_next(iterator, curr_idx, block * 64)
170
+ flip_bit = gray_code_next(iterator, curr_idx, block << 6)
171
171
  energy = compute_cut_sparse(iterator, G_data, G_rows, G_cols, n)
172
172
  if energy > best_energy:
173
- best_iterator, best_energy = iterator.copy(), energy
173
+ best_energy = energy
174
174
  else:
175
- iterator = best_iterator.copy()
175
+ # Revert iterator
176
+ iterator[flip_bit] = not iterator[flip_bit]
176
177
  if best_energy > energies[i]:
177
- states[i], energies[i] = best_iterator.copy(), best_energy
178
+ energies[i] = best_energy
178
179
 
179
180
  best_index = np.argmax(energies)
180
181
  best_energy = energies[best_index]
181
- best_state = states[best_index]
182
+ best_state = iterators[best_index]
182
183
 
183
184
  return best_energy, best_state
184
185
 
@@ -259,6 +260,68 @@ def run_bit_flips_opencl(is_double, n, kernel, best_energy, theta, theta_buf, G_
259
260
  return energy, theta
260
261
 
261
262
 
263
+ def run_gray_search_opencl(n, kernel, best_energy, theta, theta_buf, G_data_buf, G_rows_buf, G_cols_buf, is_segmented, local_size, global_size, args_buf, max_energy_host, max_theta_host, max_energy_buf, max_theta_buf):
264
+ queue = opencl_context.queue
265
+
266
+ # Set kernel args
267
+ if is_segmented:
268
+ kernel.set_args(
269
+ G_data_buf[0],
270
+ G_data_buf[1],
271
+ G_data_buf[2],
272
+ G_data_buf[3],
273
+ G_rows_buf,
274
+ G_cols_buf,
275
+ theta_buf,
276
+ args_buf,
277
+ max_theta_buf,
278
+ max_energy_buf
279
+ )
280
+ else:
281
+ kernel.set_args(
282
+ G_data_buf,
283
+ G_rows_buf,
284
+ G_cols_buf,
285
+ theta_buf,
286
+ args_buf,
287
+ max_theta_buf,
288
+ max_energy_buf
289
+ )
290
+
291
+ cl.enqueue_nd_range_kernel(queue, kernel, (global_size,), (local_size,))
292
+
293
+ # Read results
294
+ cl.enqueue_copy(queue, max_energy_host, max_energy_buf)
295
+ queue.finish()
296
+
297
+ # Queue read for results we might not need
298
+ cl.enqueue_copy(queue, max_theta_host, max_theta_buf)
299
+
300
+ # Find global minimum
301
+ best_x = np.argmax(max_energy_host)
302
+ energy = max_energy_host[best_x]
303
+
304
+ if energy <= best_energy:
305
+ # No improvement: we can exit early
306
+ return best_energy, theta
307
+
308
+ # We need the best index
309
+ queue.finish()
310
+
311
+ blocks = (n + 63) // 64
312
+ offset = best_x * blocks
313
+ for b in range(blocks):
314
+ s = max_theta_host[best_x]
315
+ b_offset = b << 6
316
+ for i in range(64):
317
+ j = b_offset + i
318
+ if j >= n:
319
+ break
320
+ theta[j] = (s >> i) & 1
321
+
322
+ return energy, theta
323
+
324
+
262
325
  def spin_glass_solver_sparse(
263
326
  G,
264
327
  quality=None,
@@ -351,6 +414,11 @@ def spin_glass_solver_sparse(
351
414
  single_bit_flips_kernel = opencl_context.single_bit_flips_sparse_kernel
352
415
  double_bit_flips_kernel = opencl_context.double_bit_flips_sparse_kernel
353
416
 
417
+ if n_qubits <= gnl:
418
+ gray_work_group_size = opencl_context.MAX_GPU_PROC_ELEM
419
+ gray_args = setup_opencl(1, gray_work_group_size, np.array([n_qubits, is_spin_glass, (gray_iterations + gray_work_group_size - 1) // gray_work_group_size, segment_size]), True)
420
+ gray_kernel = opencl_context.gray_sparse_segmented_kernel if is_segmented else opencl_context.gray_sparse_kernel
421
+
354
422
  thread_count = os.cpu_count() ** 2
355
423
  improved = True
356
424
  while improved:
@@ -380,21 +448,25 @@ def spin_glass_solver_sparse(
380
448
  improved = True
381
449
  continue
382
450
 
383
- # Gray code with default O(n^3)
384
- iterators, energies = pick_gray_seeds(best_theta, thread_count, gray_seed_multiple, G_m.data, G_m.indptr, G_m.indices, n_qubits, is_spin_glass)
385
- energy, state = energies[0], iterators[0]
386
- if energy > max_energy:
387
- max_energy = energy
388
- best_theta = state
389
- improved = True
390
- continue
391
-
392
- energy, state = run_gray_optimization(best_theta, iterators, energies, gray_iterations, thread_count, is_spin_glass, G_m.data, G_m.indptr, G_m.indices)
393
- if energy > max_energy:
394
- max_energy = energy
395
- best_theta = state
396
- improved = True
397
- continue
451
+ if is_opencl and (n_qubits <= gnl):
452
+ theta_buf_64 = make_best_theta_buf_64(best_theta)
453
+ energy, state = run_gray_search_opencl(n_qubits, gray_kernel, max_energy, best_theta, theta_buf_64, G_data_buf, G_rows_buf, G_cols_buf, is_segmented, *gray_args)
454
+ else:
455
+ # Gray code with default O(n^3)
456
+ iterators, energies = pick_gray_seeds(best_theta, thread_count, gray_seed_multiple, G_m.data, G_m.indptr, G_m.indices, n_qubits, is_spin_glass)
457
+ energy, state = energies[0], iterators[0]
458
+ if energy > max_energy:
459
+ max_energy = energy
460
+ best_theta = state
461
+ improved = True
462
+ continue
463
+
464
+ energy, state = run_gray_optimization(best_theta, iterators, energies, gray_iterations, thread_count, is_spin_glass, G_m.data, G_m.indptr, G_m.indices)
465
+ if energy > max_energy:
466
+ max_energy = energy
467
+ best_theta = state
468
+ improved = True
469
+ continue
398
470
 
399
471
  # Post-reheat phase
400
472
  reheat_theta = state
@@ -97,7 +97,7 @@ def run_double_bit_flips(best_theta, is_spin_glass, G_func, nodes, thread_count)
97
97
 
98
98
  @njit(parallel=True)
99
99
  def pick_gray_seeds(best_theta, thread_count, gray_seed_multiple, G_func, nodes, n, is_spin_glass):
100
- blocks = (n + 63) // 64
100
+ blocks = (n + 63) >> 6
101
101
  block_size = thread_count * gray_seed_multiple
102
102
  seed_count = block_size * blocks
103
103
 
@@ -107,14 +107,14 @@ def pick_gray_seeds(best_theta, thread_count, gray_seed_multiple, G_func, nodes,
107
107
  if is_spin_glass:
108
108
  for s in prange(seed_count):
109
109
  i = s % block_size
110
- offset = (s // block_size) * 64
110
+ offset = (s // block_size) << 6
111
111
  seed = gray_mutation(i, best_theta, offset)
112
112
  energies[s] = compute_energy_streaming(seed, G_func, nodes, n)
113
113
  seeds[s] = seed
114
114
  else:
115
115
  for s in prange(seed_count):
116
116
  i = s % block_size
117
- offset = (s // block_size) * 64
117
+ offset = (s // block_size) << 6
118
118
  seed = gray_mutation(i, best_theta, offset)
119
119
  energies[s] = compute_cut_streaming(seed, G_func, nodes, n)
120
120
  seeds[s] = seed
@@ -135,42 +135,42 @@ def pick_gray_seeds(best_theta, thread_count, gray_seed_multiple, G_func, nodes,
135
135
  def run_gray_optimization(best_theta, iterators, energies, gray_iterations, thread_count, is_spin_glass, G_func, nodes):
136
136
  n = len(best_theta)
137
137
  thread_iterations = (gray_iterations + thread_count - 1) // thread_count
138
- blocks = (n + 63) // 64
139
-
140
- states = np.empty((thread_count, n), dtype=np.bool_)
138
+ blocks = (n + 63) >> 6
141
139
 
142
140
  if is_spin_glass:
143
141
  for i in prange(thread_count):
144
- iterator = iterators[i].copy()
145
- best_energy, best_iterator = energies[i], iterator.copy()
142
+ iterator = iterators[i]
143
+ best_energy = energies[i]
146
144
  for curr_idx in range(thread_iterations):
147
145
  for block in range(blocks):
148
- gray_code_next(iterator, curr_idx, block * 64)
146
+ flip_bit = gray_code_next(iterator, curr_idx, block << 6)
149
147
  energy = compute_energy_streaming(iterator, G_func, nodes, n)
150
148
  if energy > best_energy:
151
- best_iterator, best_energy = iterator.copy(), energy
149
+ best_energy = energy
152
150
  else:
153
- iterator = best_iterator.copy()
151
+ # Revert iterator
152
+ iterator[flip_bit] = not iterator[flip_bit]
154
153
  if best_energy > energies[i]:
155
- states[i], energies[i] = best_iterator.copy(), best_energy
154
+ energies[i] = best_energy
156
155
  else:
157
156
  for i in prange(thread_count):
158
- iterator = iterators[i].copy()
159
- best_energy, best_iterator = energies[i], iterator.copy()
157
+ iterator = iterators[i]
158
+ best_energy = energies[i]
160
159
  for curr_idx in range(thread_iterations):
161
160
  for block in range(blocks):
162
- gray_code_next(iterator, curr_idx, block * 64)
161
+ flip_bit = gray_code_next(iterator, curr_idx, block << 6)
163
162
  energy = compute_cut_streaming(iterator, G_func, nodes, n)
164
163
  if energy > best_energy:
165
- best_iterator, best_energy = iterator.copy(), energy
164
+ best_energy = energy
166
165
  else:
167
- iterator = best_iterator.copy()
166
+ # Revert iterator
167
+ iterator[flip_bit] = not iterator[flip_bit]
168
168
  if best_energy > energies[i]:
169
- states[i], energies[i] = best_iterator.copy(), best_energy
169
+ energies[i] = best_energy
170
170
 
171
171
  best_index = np.argmax(energies)
172
172
  best_energy = energies[best_index]
173
- best_state = states[best_index]
173
+ best_state = iterators[best_index]
174
174
 
175
175
  return best_energy, best_state
176
176
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrackising
3
- Version: 9.7.3
3
+ Version: 9.7.5
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
@@ -7,7 +7,7 @@ with open(README_PATH) as readme_file:
7
7
 
8
8
  setup(
9
9
  name='pyqrackising',
10
- version='9.7.3',
10
+ version='9.7.5',
11
11
  author='Dan Strano',
12
12
  author_email='stranoj@gmail.com',
13
13
  description='Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)',
File without changes
File without changes
File without changes