linkcell 0.4.0

Periodic linked-cell cutoff pairs and k-nearest neighbour search
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/* Device weights, curve keys, and the prefix split.
 * Host twins of those three kernels live in this file so a machine
 * without a GPU can compile the translation unit and check them. */

#include <cstdint>
#include <cstring>
#include <vector>
#include <algorithm>

#if defined(LINKCELL_HAS_GPULITE)
#include "gpulite_compat.hpp"
using gpulite::CUDART;
using gpulite::KernelFactory;
using gpulite::NVRTC;
#endif

namespace {

uint64_t spread21(uint32_t v) {
  uint64_t x = v & 0x1fffffu;
  x = (x | (x << 32)) & 0x001f00000000ffffull;
  x = (x | (x << 16)) & 0x001f0000ff0000ffull;
  x = (x | (x << 8)) & 0x100f00f00f00f00full;
  x = (x | (x << 4)) & 0x10c30c30c30c30c3ull;
  x = (x | (x << 2)) & 0x1249249249249249ull;
  return x;
}

uint64_t morton_key(uint32_t x, uint32_t y, uint32_t z) {
  return spread21(x) | (spread21(y) << 1) | (spread21(z) << 2);
}

uint64_t hilbert_key(uint32_t x, uint32_t y, uint32_t z, uint32_t bits) {
  if (bits == 0) {
    return 0;
  }
  uint32_t p[3] = {x, y, z};
  uint32_t q = 1u << (bits - 1);
  while (q > 1) {
    uint32_t mask = q - 1;
    for (int i = 0; i < 3; ++i) {
      if (p[i] & q) {
        p[0] ^= mask;
      } else {
        uint32_t t = (p[0] ^ p[i]) & mask;
        p[0] ^= t;
        p[i] ^= t;
      }
    }
    q >>= 1;
  }
  p[1] ^= p[0];
  p[2] ^= p[1];
  uint32_t t = 0;
  q = 1u << (bits - 1);
  while (q > 1) {
    if (p[2] & q) {
      t ^= q - 1;
    }
    q >>= 1;
  }
  for (int i = 0; i < 3; ++i) {
    p[i] ^= t;
  }
  uint64_t key = 0;
  for (int b = static_cast<int>(bits) - 1; b >= 0; --b) {
    for (int i = 0; i < 3; ++i) {
      key = (key << 1) | ((p[i] >> b) & 1u);
    }
  }
  return key;
}

uint32_t hilbert_bits(uint32_t nx, uint32_t ny, uint32_t nz) {
  uint32_t n = nx;
  if (ny > n) n = ny;
  if (nz > n) n = nz;
  if (n <= 1) return 0;
  uint32_t bits = 0;
  uint32_t v = n - 1;
  while (v > 0) {
    v >>= 1;
    bits += 1;
  }
  return bits;
}

uint32_t owner_of(uint64_t before, uint64_t weight, uint64_t total, uint32_t parts) {
  if (total == 0 || parts == 0) {
    return 0;
  }
#if defined(__SIZEOF_INT128__)
  unsigned __int128 num =
      (static_cast<unsigned __int128>(2) * before + weight) * parts;
  unsigned __int128 den = static_cast<unsigned __int128>(2) * total;
  uint32_t owner = static_cast<uint32_t>(num / den);
#else
  // No 128-bit integer (MSVC): the same quotient from a two-word
  // numerator and a 65-bit denominator, by restoring long division.
  uint64_t a_lo = before << 1;
  uint64_t a_hi = before >> 63;
  const uint64_t a_sum = a_lo + weight;
  a_hi += a_sum < a_lo ? 1 : 0;
  a_lo = a_sum;
  // (a_hi:a_lo) * parts, a_hi is at most 2, parts below 2^32.
  const uint64_t lo_lo = (a_lo & 0xffffffffu) * parts;
  const uint64_t lo_hi = (a_lo >> 32) * parts;
  uint64_t n_lo = lo_lo + (lo_hi << 32);
  uint64_t n_hi = a_hi * parts + (lo_hi >> 32) + (n_lo < lo_lo ? 1 : 0);
  const uint64_t d_lo = total << 1;
  const uint64_t d_hi = total >> 63;
  uint64_t r_hi = 0;
  uint64_t r_lo = 0;
  uint64_t q = 0;
  for (int bit = 127; bit >= 0; --bit) {
    const uint64_t in = bit >= 64 ? (n_hi >> (bit - 64)) & 1u : (n_lo >> bit) & 1u;
    r_hi = (r_hi << 1) | (r_lo >> 63);
    r_lo = (r_lo << 1) | in;
    if (r_hi > d_hi || (r_hi == d_hi && r_lo >= d_lo)) {
      const uint64_t borrow = r_lo < d_lo ? 1 : 0;
      r_lo -= d_lo;
      r_hi -= d_hi + borrow;
      if (bit < 64) {
        q |= uint64_t{1} << bit;
      }
    }
  }
  uint32_t owner = q >= parts ? parts : static_cast<uint32_t>(q);
#endif
  if (owner >= parts) {
    owner = parts - 1;
  }
  return owner;
}

const char *kCurve = R"CUDA(
__device__ unsigned long long spread21(unsigned int v) {
  unsigned long long x = v & 0x1fffffu;
  x = (x | (x << 32)) & 0x001f00000000ffffull;
  x = (x | (x << 16)) & 0x001f0000ff0000ffull;
  x = (x | (x << 8)) & 0x100f00f00f00f00full;
  x = (x | (x << 4)) & 0x10c30c30c30c30c3ull;
  x = (x | (x << 2)) & 0x1249249249249249ull;
  return x;
}

extern "C" __global__ void hist_cells(const unsigned int* bins,
    unsigned long long* weight, int n) {
  int i = blockIdx.x * blockDim.x + threadIdx.x;
  if (i < n) atomicAdd(weight + bins[i], 1ull);
}

extern "C" __global__ void morton_cells(const unsigned int* coords,
    unsigned long long* keys, int n) {
  int i = blockIdx.x * blockDim.x + threadIdx.x;
  if (i >= n) return;
  unsigned int x = coords[3 * i];
  unsigned int y = coords[3 * i + 1];
  unsigned int z = coords[3 * i + 2];
  keys[i] = spread21(x) | (spread21(y) << 1) | (spread21(z) << 2);
}

extern "C" __global__ void block_scan(const unsigned long long* in,
    unsigned long long* out, unsigned long long* block_sum, int n) {
  __shared__ unsigned long long s[256];
  int tid = threadIdx.x;
  int gid = blockIdx.x * 256 + tid;
  s[tid] = gid < n ? in[gid] : 0ull;
  __syncthreads();
  for (int offset = 1; offset < 256; offset <<= 1) {
    unsigned long long v = (tid >= offset) ? s[tid - offset] : 0ull;
    __syncthreads();
    if (tid >= offset) s[tid] += v;
    __syncthreads();
  }
  if (gid < n) out[gid] = (tid == 0) ? 0ull : s[tid - 1];
  if (tid == 255 && block_sum) block_sum[blockIdx.x] = s[255];
}

extern "C" __global__ void add_block(unsigned long long* out,
    const unsigned long long* block_prefix, int n) {
  int gid = blockIdx.x * blockDim.x + threadIdx.x;
  if (gid < n && blockIdx.x > 0) out[gid] += block_prefix[blockIdx.x];
}
)CUDA";

} // namespace

extern "C" {

void lc_part_host_histogram(const uint32_t *bins, size_t n, uint64_t *weight,
                            size_t ncell) {
  std::memset(weight, 0, ncell * sizeof(uint64_t));
  for (size_t i = 0; i < n; ++i) {
    weight[bins[i]] += 1;
  }
}

void lc_part_host_morton(const uint32_t *coords, size_t n, uint64_t *keys) {
  for (size_t i = 0; i < n; ++i) {
    keys[i] = morton_key(coords[3 * i], coords[3 * i + 1], coords[3 * i + 2]);
  }
}

void lc_part_host_prefix(const uint64_t *values, size_t n, uint64_t *out) {
  out[0] = 0;
  for (size_t i = 0; i < n; ++i) {
    out[i + 1] = out[i] + values[i];
  }
}

uint64_t lc_part_host_hilbert(uint32_t x, uint32_t y, uint32_t z, uint32_t bits) {
  return hilbert_key(x, y, z, bits);
}

int lc_gpu_curve_split(const uint32_t *atom_bin, size_t natom,
                       const uint32_t *coords, size_t ncell, uint32_t parts,
                       uint32_t *assign, uint64_t *out_weight, uint8_t method) {
#if !defined(LINKCELL_HAS_GPULITE)
  (void)atom_bin;
  (void)natom;
  (void)coords;
  (void)ncell;
  (void)parts;
  (void)assign;
  (void)out_weight;
  (void)method;
  return 2;
#else
  if (!CUDART::loaded() || !NVRTC::loaded()) {
    return 2;
  }
  if (parts == 0 || assign == nullptr || out_weight == nullptr || ncell == 0) {
    return 1;
  }
  if (natom > 0 && atom_bin == nullptr) {
    return 1;
  }
  if (coords == nullptr) {
    return 1;
  }
  auto &rt = CUDART::instance();
  auto fail = [](void *a, void *b, void *c, void *d) {
    auto &rt = CUDART::instance();
    if (a) rt.cudaFree(a);
    if (b) rt.cudaFree(b);
    if (c) rt.cudaFree(c);
    if (d) rt.cudaFree(d);
    return 1;
  };
  uint32_t *d_bins = nullptr;
  uint64_t *d_weight = nullptr;
  uint32_t *d_coords = nullptr;
  uint64_t *d_keys = nullptr;
  if (rt.cudaMalloc(reinterpret_cast<void **>(&d_weight), ncell * sizeof(uint64_t)) != 0) {
    return 1;
  }
  rt.cudaMemset(d_weight, 0, ncell * sizeof(uint64_t));
  if (natom > 0) {
    if (rt.cudaMalloc(reinterpret_cast<void **>(&d_bins), natom * sizeof(uint32_t)) != 0) {
      return fail(d_weight, nullptr, nullptr, nullptr);
    }
    if (rt.cudaMemcpy(d_bins, atom_bin, natom * sizeof(uint32_t), cudaMemcpyHostToDevice) != 0) {
      return fail(d_weight, d_bins, nullptr, nullptr);
    }
  }
  if (rt.cudaMalloc(reinterpret_cast<void **>(&d_coords), ncell * 3 * sizeof(uint32_t)) != 0) {
    return fail(d_weight, d_bins, nullptr, nullptr);
  }
  if (rt.cudaMemcpy(d_coords, coords, ncell * 3 * sizeof(uint32_t), cudaMemcpyHostToDevice) != 0) {
    return fail(d_weight, d_bins, d_coords, nullptr);
  }
  if (rt.cudaMalloc(reinterpret_cast<void **>(&d_keys), ncell * sizeof(uint64_t)) != 0) {
    return fail(d_weight, d_bins, d_coords, nullptr);
  }
  auto &factory = KernelFactory::instance(0);
  const std::vector<std::string> opt{"-std=c++17"};
  const int block = 256;
  const int grid_atoms = static_cast<int>((natom + block - 1) / block);
  const int grid_cells = static_cast<int>((ncell + block - 1) / block);
  int n_atom = static_cast<int>(natom);
  int n_cell = static_cast<int>(ncell);
  if (natom > 0) {
    void *raw[] = {&d_bins, &d_weight, &n_atom};
    auto *k = factory.create("hist_cells", kCurve, "partition.cu", opt);
    k->launch(dim3(grid_atoms == 0 ? 1 : grid_atoms), dim3(block), 0, nullptr,
              std::vector<void *>(raw, raw + 3), true);
  }
  if (rt.cudaMemcpy(out_weight, d_weight, ncell * sizeof(uint64_t), cudaMemcpyDeviceToHost) != 0) {
    return fail(d_weight, d_bins, d_coords, d_keys);
  }
  /* Hilbert keys are produced on the host twin of the same recurrence.
   * Morton keys are produced on the device. Both copies are inside this call. */
  std::vector<uint64_t> keys(ncell);
  if (method == 0) {
    void *raw[] = {&d_coords, &d_keys, &n_cell};
    auto *k = factory.create("morton_cells", kCurve, "partition.cu", opt);
    k->launch(dim3(grid_cells == 0 ? 1 : grid_cells), dim3(block), 0, nullptr,
              std::vector<void *>(raw, raw + 3), true);
    if (rt.cudaMemcpy(keys.data(), d_keys, ncell * sizeof(uint64_t), cudaMemcpyDeviceToHost) != 0) {
      return fail(d_weight, d_bins, d_coords, d_keys);
    }
  } else {
    uint32_t nx = 0, ny = 0, nz = 0;
    for (size_t i = 0; i < ncell; ++i) {
      nx = std::max(nx, coords[3 * i] + 1);
      ny = std::max(ny, coords[3 * i + 1] + 1);
      nz = std::max(nz, coords[3 * i + 2] + 1);
    }
    uint32_t bits = hilbert_bits(nx, ny, nz);
    for (size_t i = 0; i < ncell; ++i) {
      keys[i] = hilbert_key(coords[3 * i], coords[3 * i + 1], coords[3 * i + 2], bits);
    }
    if (rt.cudaMemcpy(d_keys, keys.data(), ncell * sizeof(uint64_t), cudaMemcpyHostToDevice) != 0) {
      return fail(d_weight, d_bins, d_coords, d_keys);
    }
    if (rt.cudaMemcpy(keys.data(), d_keys, ncell * sizeof(uint64_t), cudaMemcpyDeviceToHost) != 0) {
      return fail(d_weight, d_bins, d_coords, d_keys);
    }
  }
  std::vector<uint32_t> order(ncell);
  for (size_t i = 0; i < ncell; ++i) order[i] = static_cast<uint32_t>(i);
  std::sort(order.begin(), order.end(), [&](uint32_t a, uint32_t b) {
    if (keys[a] != keys[b]) return keys[a] < keys[b];
    return a < b;
  });
  std::vector<uint64_t> ordered(ncell);
  uint64_t total = 0;
  for (size_t i = 0; i < ncell; ++i) {
    ordered[i] = out_weight[order[i]];
    total += ordered[i];
  }
  uint64_t *d_ordered = nullptr;
  uint64_t *d_prefix = nullptr;
  uint64_t *d_blocks = nullptr;
  int n_blocks = grid_cells == 0 ? 1 : grid_cells;
  if (rt.cudaMalloc(reinterpret_cast<void **>(&d_ordered), ncell * sizeof(uint64_t)) != 0 ||
      rt.cudaMalloc(reinterpret_cast<void **>(&d_prefix), (ncell + 1) * sizeof(uint64_t)) != 0 ||
      rt.cudaMalloc(reinterpret_cast<void **>(&d_blocks), static_cast<size_t>(n_blocks) * sizeof(uint64_t)) != 0) {
    if (d_ordered) rt.cudaFree(d_ordered);
    if (d_prefix) rt.cudaFree(d_prefix);
    if (d_blocks) rt.cudaFree(d_blocks);
    return fail(d_weight, d_bins, d_coords, d_keys);
  }
  if (rt.cudaMemcpy(d_ordered, ordered.data(), ncell * sizeof(uint64_t), cudaMemcpyHostToDevice) != 0) {
    rt.cudaFree(d_ordered);
    rt.cudaFree(d_prefix);
    rt.cudaFree(d_blocks);
    return fail(d_weight, d_bins, d_coords, d_keys);
  }
  {
    void *raw[] = {&d_ordered, &d_prefix, &d_blocks, &n_cell};
    auto *k = factory.create("block_scan", kCurve, "partition.cu", opt);
    k->launch(dim3(n_blocks), dim3(block), 0, nullptr, std::vector<void *>(raw, raw + 4), true);
  }
  std::vector<uint64_t> block_sum(static_cast<size_t>(n_blocks));
  std::vector<uint64_t> block_prefix(static_cast<size_t>(n_blocks), 0);
  if (rt.cudaMemcpy(block_sum.data(), d_blocks, block_sum.size() * sizeof(uint64_t),
                    cudaMemcpyDeviceToHost) != 0) {
    rt.cudaFree(d_ordered);
    rt.cudaFree(d_prefix);
    rt.cudaFree(d_blocks);
    return fail(d_weight, d_bins, d_coords, d_keys);
  }
  for (int b = 1; b < n_blocks; ++b) {
    block_prefix[static_cast<size_t>(b)] =
        block_prefix[static_cast<size_t>(b - 1)] + block_sum[static_cast<size_t>(b - 1)];
  }
  if (rt.cudaMemcpy(d_blocks, block_prefix.data(), block_prefix.size() * sizeof(uint64_t),
                    cudaMemcpyHostToDevice) != 0) {
    rt.cudaFree(d_ordered);
    rt.cudaFree(d_prefix);
    rt.cudaFree(d_blocks);
    return fail(d_weight, d_bins, d_coords, d_keys);
  }
  {
    void *raw[] = {&d_prefix, &d_blocks, &n_cell};
    auto *k = factory.create("add_block", kCurve, "partition.cu", opt);
    k->launch(dim3(n_blocks), dim3(block), 0, nullptr, std::vector<void *>(raw, raw + 3), true);
  }
  std::vector<uint64_t> prefix(ncell);
  if (rt.cudaMemcpy(prefix.data(), d_prefix, ncell * sizeof(uint64_t), cudaMemcpyDeviceToHost) != 0) {
    rt.cudaFree(d_ordered);
    rt.cudaFree(d_prefix);
    rt.cudaFree(d_blocks);
    return fail(d_weight, d_bins, d_coords, d_keys);
  }
  uint64_t use_total = total == 0 ? ncell : total;
  for (size_t i = 0; i < ncell; ++i) {
    uint64_t w = total == 0 ? 1 : ordered[i];
    assign[order[i]] = owner_of(prefix[i], w, use_total, parts);
  }
  rt.cudaFree(d_ordered);
  rt.cudaFree(d_prefix);
  rt.cudaFree(d_blocks);
  rt.cudaFree(d_weight);
  if (d_bins) rt.cudaFree(d_bins);
  rt.cudaFree(d_coords);
  rt.cudaFree(d_keys);
  return 0;
#endif
}

}

extern "C" void lc_set_gpu_curve_split(int (*f)(const uint32_t *, size_t, const uint32_t *,
                                                 size_t, uint32_t, uint32_t *, uint64_t *,
                                                 uint8_t));

namespace {

// Register the device split with the Rust library when this library loads.
struct RegisterCurveSplit {
  RegisterCurveSplit() { lc_set_gpu_curve_split(&lc_gpu_curve_split); }
};
const RegisterCurveSplit register_curve_split;

}  // namespace