Prepared t_mdatoms for using vector
[gromacs.git] / src / gromacs / mdlib / nbnxn_search.cpp
blob736e7c0f1df6d649453292905197354e5826e1e0
1 /*
2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2012,2013,2014,2015,2016,2017, by the GROMACS development team, led by
5 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6 * and including many others, as listed in the AUTHORS file in the
7 * top-level source directory and at http://www.gromacs.org.
9 * GROMACS is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
14 * GROMACS is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with GROMACS; if not, see
21 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * If you want to redistribute modifications to GROMACS, please
25 * consider that scientific software is very special. Version
26 * control is crucial - bugs must be traceable. We will be happy to
27 * consider code for inclusion in the official distribution, but
28 * derived work must not be called official GROMACS. Details are found
29 * in the README & COPYING files - if they are missing, get the
30 * official version at http://www.gromacs.org.
32 * To help us fund GROMACS development, we humbly ask that you cite
33 * the research papers on the package. Check out http://www.gromacs.org.
36 #include "gmxpre.h"
38 #include "nbnxn_search.h"
40 #include "config.h"
42 #include <assert.h>
43 #include <string.h>
45 #include <cmath>
47 #include <algorithm>
49 #include "gromacs/domdec/domdec_struct.h"
50 #include "gromacs/gmxlib/nrnb.h"
51 #include "gromacs/math/functions.h"
52 #include "gromacs/math/utilities.h"
53 #include "gromacs/math/vec.h"
54 #include "gromacs/mdlib/gmx_omp_nthreads.h"
55 #include "gromacs/mdlib/nb_verlet.h"
56 #include "gromacs/mdlib/nbnxn_atomdata.h"
57 #include "gromacs/mdlib/nbnxn_consts.h"
58 #include "gromacs/mdlib/nbnxn_grid.h"
59 #include "gromacs/mdlib/nbnxn_internal.h"
60 #include "gromacs/mdlib/nbnxn_simd.h"
61 #include "gromacs/mdlib/nbnxn_util.h"
62 #include "gromacs/mdlib/ns.h"
63 #include "gromacs/mdtypes/group.h"
64 #include "gromacs/mdtypes/md_enums.h"
65 #include "gromacs/pbcutil/ishift.h"
66 #include "gromacs/pbcutil/pbc.h"
67 #include "gromacs/simd/simd.h"
68 #include "gromacs/simd/vector_operations.h"
69 #include "gromacs/utility/exceptions.h"
70 #include "gromacs/utility/fatalerror.h"
71 #include "gromacs/utility/gmxomp.h"
72 #include "gromacs/utility/smalloc.h"
74 using namespace gmx; // TODO: Remove when this file is moved into gmx namespace
77 /* We shift the i-particles backward for PBC.
78 * This leads to more conditionals than shifting forward.
79 * We do this to get more balanced pair lists.
81 constexpr bool c_pbcShiftBackward = true;
84 static void nbs_cycle_clear(nbnxn_cycle_t *cc)
86 for (int i = 0; i < enbsCCnr; i++)
88 cc[i].count = 0;
89 cc[i].c = 0;
93 static double Mcyc_av(const nbnxn_cycle_t *cc)
95 return (double)cc->c*1e-6/cc->count;
98 static void nbs_cycle_print(FILE *fp, const nbnxn_search_t nbs)
100 fprintf(fp, "\n");
101 fprintf(fp, "ns %4d grid %4.1f search %4.1f red.f %5.3f",
102 nbs->cc[enbsCCgrid].count,
103 Mcyc_av(&nbs->cc[enbsCCgrid]),
104 Mcyc_av(&nbs->cc[enbsCCsearch]),
105 Mcyc_av(&nbs->cc[enbsCCreducef]));
107 if (nbs->nthread_max > 1)
109 if (nbs->cc[enbsCCcombine].count > 0)
111 fprintf(fp, " comb %5.2f",
112 Mcyc_av(&nbs->cc[enbsCCcombine]));
114 fprintf(fp, " s. th");
115 for (int t = 0; t < nbs->nthread_max; t++)
117 fprintf(fp, " %4.1f",
118 Mcyc_av(&nbs->work[t].cc[enbsCCsearch]));
121 fprintf(fp, "\n");
124 gmx_unused static gmx_inline int ci_to_cj(int ci, int na_cj_2log)
126 switch (na_cj_2log)
128 case 2: return ci; break;
129 case 3: return (ci>>1); break;
130 case 1: return (ci<<1); break;
133 return 0;
136 /* Layout for the nonbonded NxN pair lists */
137 enum class NbnxnLayout
139 NoSimd4x4, // i-cluster size 4, j-cluster size 4
140 Simd4xN, // i-cluster size 4, j-cluster size SIMD width
141 Simd2xNN, // i-cluster size 4, j-cluster size half SIMD width
142 Gpu8x8x8 // i-cluster size 8, j-cluster size 8 + super-clustering
145 /* Returns the j-cluster size */
146 template <NbnxnLayout layout>
147 static constexpr int jClusterSize()
149 #if GMX_SIMD
150 static_assert(layout == NbnxnLayout::NoSimd4x4 || layout == NbnxnLayout::Simd4xN || layout == NbnxnLayout::Simd2xNN, "Currently jClusterSize only supports CPU layouts");
152 return layout == NbnxnLayout::Simd4xN ? GMX_SIMD_REAL_WIDTH : (layout == NbnxnLayout::Simd2xNN ? GMX_SIMD_REAL_WIDTH/2 : NBNXN_CPU_CLUSTER_I_SIZE);
153 #else
154 static_assert(layout == NbnxnLayout::NoSimd4x4, "Currently without SIMD, jClusterSize only supports NoSimd4x4");
156 return NBNXN_CPU_CLUSTER_I_SIZE;
157 #endif
160 /* Returns the j-cluster index given the i-cluster index */
161 template <int jClusterSize>
162 static inline int cjFromCi(int ci)
164 static_assert(jClusterSize == NBNXN_CPU_CLUSTER_I_SIZE/2 || jClusterSize == NBNXN_CPU_CLUSTER_I_SIZE || jClusterSize == NBNXN_CPU_CLUSTER_I_SIZE*2, "Only j-cluster sizes 2, 4 and 8 are currently implemented");
166 if (jClusterSize == NBNXN_CPU_CLUSTER_I_SIZE/2)
168 return ci << 1;
170 else if (jClusterSize == NBNXN_CPU_CLUSTER_I_SIZE)
172 return ci;
174 else
176 return ci >> 1;
180 /* Returns the j-cluster index given the i-cluster index */
181 template <NbnxnLayout layout>
182 static inline int cjFromCi(int ci)
184 constexpr int clusterSize = jClusterSize<layout>();
186 return cjFromCi<clusterSize>(ci);
189 /* Returns the nbnxn coordinate data index given the i-cluster index */
190 template <NbnxnLayout layout>
191 static inline int xIndexFromCi(int ci)
193 constexpr int clusterSize = jClusterSize<layout>();
195 static_assert(clusterSize == NBNXN_CPU_CLUSTER_I_SIZE/2 || clusterSize == NBNXN_CPU_CLUSTER_I_SIZE || clusterSize == NBNXN_CPU_CLUSTER_I_SIZE*2, "Only j-cluster sizes 2, 4 and 8 are currently implemented");
197 if (clusterSize <= NBNXN_CPU_CLUSTER_I_SIZE)
199 /* Coordinates are stored packed in groups of 4 */
200 return ci*STRIDE_P4;
202 else
204 /* Coordinates packed in 8, i-cluster size is half the packing width */
205 return (ci >> 1)*STRIDE_P8 + (ci & 1)*(c_packX8 >> 1);
209 /* Returns the nbnxn coordinate data index given the j-cluster index */
210 template <NbnxnLayout layout>
211 static inline int xIndexFromCj(int cj)
213 constexpr int clusterSize = jClusterSize<layout>();
215 static_assert(clusterSize == NBNXN_CPU_CLUSTER_I_SIZE/2 || clusterSize == NBNXN_CPU_CLUSTER_I_SIZE || clusterSize == NBNXN_CPU_CLUSTER_I_SIZE*2, "Only j-cluster sizes 2, 4 and 8 are currently implemented");
217 if (clusterSize == NBNXN_CPU_CLUSTER_I_SIZE/2)
219 /* Coordinates are stored packed in groups of 4 */
220 return (cj >> 1)*STRIDE_P4 + (cj & 1)*(c_packX4 >> 1);
222 else if (clusterSize == NBNXN_CPU_CLUSTER_I_SIZE)
224 /* Coordinates are stored packed in groups of 4 */
225 return cj*STRIDE_P4;
227 else
229 /* Coordinates are stored packed in groups of 8 */
230 return cj*STRIDE_P8;
234 gmx_bool nbnxn_kernel_pairlist_simple(int nb_kernel_type)
236 if (nb_kernel_type == nbnxnkNotSet)
238 gmx_fatal(FARGS, "Non-bonded kernel type not set for Verlet-style pair-list.");
241 switch (nb_kernel_type)
243 case nbnxnk8x8x8_GPU:
244 case nbnxnk8x8x8_PlainC:
245 return FALSE;
247 case nbnxnk4x4_PlainC:
248 case nbnxnk4xN_SIMD_4xN:
249 case nbnxnk4xN_SIMD_2xNN:
250 return TRUE;
252 default:
253 gmx_incons("Invalid nonbonded kernel type passed!");
254 return FALSE;
258 /* Initializes a single nbnxn_pairlist_t data structure */
259 static void nbnxn_init_pairlist_fep(t_nblist *nl)
261 nl->type = GMX_NBLIST_INTERACTION_FREE_ENERGY;
262 nl->igeometry = GMX_NBLIST_GEOMETRY_PARTICLE_PARTICLE;
263 /* The interaction functions are set in the free energy kernel fuction */
264 nl->ivdw = -1;
265 nl->ivdwmod = -1;
266 nl->ielec = -1;
267 nl->ielecmod = -1;
269 nl->maxnri = 0;
270 nl->maxnrj = 0;
271 nl->nri = 0;
272 nl->nrj = 0;
273 nl->iinr = nullptr;
274 nl->gid = nullptr;
275 nl->shift = nullptr;
276 nl->jindex = nullptr;
277 nl->jjnr = nullptr;
278 nl->excl_fep = nullptr;
282 void nbnxn_init_search(nbnxn_search_t * nbs_ptr,
283 ivec *n_dd_cells,
284 struct gmx_domdec_zones_t *zones,
285 gmx_bool bFEP,
286 int nthread_max)
288 nbnxn_search_t nbs;
289 int ngrid;
291 snew(nbs, 1);
292 *nbs_ptr = nbs;
294 nbs->bFEP = bFEP;
296 nbs->DomDec = (n_dd_cells != nullptr);
298 clear_ivec(nbs->dd_dim);
299 ngrid = 1;
300 if (nbs->DomDec)
302 nbs->zones = zones;
304 for (int d = 0; d < DIM; d++)
306 if ((*n_dd_cells)[d] > 1)
308 nbs->dd_dim[d] = 1;
309 /* Each grid matches a DD zone */
310 ngrid *= 2;
315 nbnxn_grids_init(nbs, ngrid);
317 nbs->cell = nullptr;
318 nbs->cell_nalloc = 0;
319 nbs->a = nullptr;
320 nbs->a_nalloc = 0;
322 nbs->nthread_max = nthread_max;
324 /* Initialize the work data structures for each thread */
325 snew(nbs->work, nbs->nthread_max);
326 for (int t = 0; t < nbs->nthread_max; t++)
328 nbs->work[t].cxy_na = nullptr;
329 nbs->work[t].cxy_na_nalloc = 0;
330 nbs->work[t].sort_work = nullptr;
331 nbs->work[t].sort_work_nalloc = 0;
333 snew(nbs->work[t].nbl_fep, 1);
334 nbnxn_init_pairlist_fep(nbs->work[t].nbl_fep);
337 /* Initialize detailed nbsearch cycle counting */
338 nbs->print_cycles = (getenv("GMX_NBNXN_CYCLE") != nullptr);
339 nbs->search_count = 0;
340 nbs_cycle_clear(nbs->cc);
341 for (int t = 0; t < nbs->nthread_max; t++)
343 nbs_cycle_clear(nbs->work[t].cc);
347 static void init_buffer_flags(nbnxn_buffer_flags_t *flags,
348 int natoms)
350 flags->nflag = (natoms + NBNXN_BUFFERFLAG_SIZE - 1)/NBNXN_BUFFERFLAG_SIZE;
351 if (flags->nflag > flags->flag_nalloc)
353 flags->flag_nalloc = over_alloc_large(flags->nflag);
354 srenew(flags->flag, flags->flag_nalloc);
356 for (int b = 0; b < flags->nflag; b++)
358 bitmask_clear(&(flags->flag[b]));
362 /* Determines the cell range along one dimension that
363 * the bounding box b0 - b1 sees.
365 static void get_cell_range(real b0, real b1,
366 int nc, real c0, real s, real invs,
367 real d2, real r2, int *cf, int *cl)
369 *cf = std::max(static_cast<int>((b0 - c0)*invs), 0);
371 while (*cf > 0 && d2 + gmx::square((b0 - c0) - (*cf-1+1)*s) < r2)
373 (*cf)--;
376 *cl = std::min(static_cast<int>((b1 - c0)*invs), nc-1);
377 while (*cl < nc-1 && d2 + gmx::square((*cl+1)*s - (b1 - c0)) < r2)
379 (*cl)++;
383 /* Reference code calculating the distance^2 between two bounding boxes */
385 static float box_dist2(float bx0, float bx1, float by0,
386 float by1, float bz0, float bz1,
387 const nbnxn_bb_t *bb)
389 float d2;
390 float dl, dh, dm, dm0;
392 d2 = 0;
394 dl = bx0 - bb->upper[BB_X];
395 dh = bb->lower[BB_X] - bx1;
396 dm = std::max(dl, dh);
397 dm0 = std::max(dm, 0.0f);
398 d2 += dm0*dm0;
400 dl = by0 - bb->upper[BB_Y];
401 dh = bb->lower[BB_Y] - by1;
402 dm = std::max(dl, dh);
403 dm0 = std::max(dm, 0.0f);
404 d2 += dm0*dm0;
406 dl = bz0 - bb->upper[BB_Z];
407 dh = bb->lower[BB_Z] - bz1;
408 dm = std::max(dl, dh);
409 dm0 = std::max(dm, 0.0f);
410 d2 += dm0*dm0;
412 return d2;
416 /* Plain C code calculating the distance^2 between two bounding boxes */
417 static float subc_bb_dist2(int si, const nbnxn_bb_t *bb_i_ci,
418 int csj, const nbnxn_bb_t *bb_j_all)
420 const nbnxn_bb_t *bb_i, *bb_j;
421 float d2;
422 float dl, dh, dm, dm0;
424 bb_i = bb_i_ci + si;
425 bb_j = bb_j_all + csj;
427 d2 = 0;
429 dl = bb_i->lower[BB_X] - bb_j->upper[BB_X];
430 dh = bb_j->lower[BB_X] - bb_i->upper[BB_X];
431 dm = std::max(dl, dh);
432 dm0 = std::max(dm, 0.0f);
433 d2 += dm0*dm0;
435 dl = bb_i->lower[BB_Y] - bb_j->upper[BB_Y];
436 dh = bb_j->lower[BB_Y] - bb_i->upper[BB_Y];
437 dm = std::max(dl, dh);
438 dm0 = std::max(dm, 0.0f);
439 d2 += dm0*dm0;
441 dl = bb_i->lower[BB_Z] - bb_j->upper[BB_Z];
442 dh = bb_j->lower[BB_Z] - bb_i->upper[BB_Z];
443 dm = std::max(dl, dh);
444 dm0 = std::max(dm, 0.0f);
445 d2 += dm0*dm0;
447 return d2;
450 #if NBNXN_SEARCH_BB_SIMD4
452 /* 4-wide SIMD code for bb distance for bb format xyz0 */
453 static float subc_bb_dist2_simd4(int si, const nbnxn_bb_t *bb_i_ci,
454 int csj, const nbnxn_bb_t *bb_j_all)
456 // TODO: During SIMDv2 transition only some archs use namespace (remove when done)
457 using namespace gmx;
459 Simd4Float bb_i_S0, bb_i_S1;
460 Simd4Float bb_j_S0, bb_j_S1;
461 Simd4Float dl_S;
462 Simd4Float dh_S;
463 Simd4Float dm_S;
464 Simd4Float dm0_S;
466 bb_i_S0 = load4(&bb_i_ci[si].lower[0]);
467 bb_i_S1 = load4(&bb_i_ci[si].upper[0]);
468 bb_j_S0 = load4(&bb_j_all[csj].lower[0]);
469 bb_j_S1 = load4(&bb_j_all[csj].upper[0]);
471 dl_S = bb_i_S0 - bb_j_S1;
472 dh_S = bb_j_S0 - bb_i_S1;
474 dm_S = max(dl_S, dh_S);
475 dm0_S = max(dm_S, simd4SetZeroF());
477 return dotProduct(dm0_S, dm0_S);
480 /* Calculate bb bounding distances of bb_i[si,...,si+3] and store them in d2 */
481 #define SUBC_BB_DIST2_SIMD4_XXXX_INNER(si, bb_i, d2) \
483 int shi; \
485 Simd4Float dx_0, dy_0, dz_0; \
486 Simd4Float dx_1, dy_1, dz_1; \
488 Simd4Float mx, my, mz; \
489 Simd4Float m0x, m0y, m0z; \
491 Simd4Float d2x, d2y, d2z; \
492 Simd4Float d2s, d2t; \
494 shi = si*NNBSBB_D*DIM; \
496 xi_l = load4(bb_i+shi+0*STRIDE_PBB); \
497 yi_l = load4(bb_i+shi+1*STRIDE_PBB); \
498 zi_l = load4(bb_i+shi+2*STRIDE_PBB); \
499 xi_h = load4(bb_i+shi+3*STRIDE_PBB); \
500 yi_h = load4(bb_i+shi+4*STRIDE_PBB); \
501 zi_h = load4(bb_i+shi+5*STRIDE_PBB); \
503 dx_0 = xi_l - xj_h; \
504 dy_0 = yi_l - yj_h; \
505 dz_0 = zi_l - zj_h; \
507 dx_1 = xj_l - xi_h; \
508 dy_1 = yj_l - yi_h; \
509 dz_1 = zj_l - zi_h; \
511 mx = max(dx_0, dx_1); \
512 my = max(dy_0, dy_1); \
513 mz = max(dz_0, dz_1); \
515 m0x = max(mx, zero); \
516 m0y = max(my, zero); \
517 m0z = max(mz, zero); \
519 d2x = m0x * m0x; \
520 d2y = m0y * m0y; \
521 d2z = m0z * m0z; \
523 d2s = d2x + d2y; \
524 d2t = d2s + d2z; \
526 store4(d2+si, d2t); \
529 /* 4-wide SIMD code for nsi bb distances for bb format xxxxyyyyzzzz */
530 static void subc_bb_dist2_simd4_xxxx(const float *bb_j,
531 int nsi, const float *bb_i,
532 float *d2)
534 // TODO: During SIMDv2 transition only some archs use namespace (remove when done)
535 using namespace gmx;
537 Simd4Float xj_l, yj_l, zj_l;
538 Simd4Float xj_h, yj_h, zj_h;
539 Simd4Float xi_l, yi_l, zi_l;
540 Simd4Float xi_h, yi_h, zi_h;
542 Simd4Float zero;
544 zero = setZero();
546 xj_l = Simd4Float(bb_j[0*STRIDE_PBB]);
547 yj_l = Simd4Float(bb_j[1*STRIDE_PBB]);
548 zj_l = Simd4Float(bb_j[2*STRIDE_PBB]);
549 xj_h = Simd4Float(bb_j[3*STRIDE_PBB]);
550 yj_h = Simd4Float(bb_j[4*STRIDE_PBB]);
551 zj_h = Simd4Float(bb_j[5*STRIDE_PBB]);
553 /* Here we "loop" over si (0,STRIDE_PBB) from 0 to nsi with step STRIDE_PBB.
554 * But as we know the number of iterations is 1 or 2, we unroll manually.
556 SUBC_BB_DIST2_SIMD4_XXXX_INNER(0, bb_i, d2);
557 if (STRIDE_PBB < nsi)
559 SUBC_BB_DIST2_SIMD4_XXXX_INNER(STRIDE_PBB, bb_i, d2);
563 #endif /* NBNXN_SEARCH_BB_SIMD4 */
566 /* Returns if any atom pair from two clusters is within distance sqrt(rlist2) */
567 static gmx_inline gmx_bool
568 clusterpair_in_range(const nbnxn_list_work_t *work,
569 int si,
570 int csj, int stride, const real *x_j,
571 real rlist2)
573 #if !GMX_SIMD4_HAVE_REAL
575 /* Plain C version.
576 * All coordinates are stored as xyzxyz...
579 const real *x_i = work->x_ci;
581 for (int i = 0; i < c_nbnxnGpuClusterSize; i++)
583 int i0 = (si*c_nbnxnGpuClusterSize + i)*DIM;
584 for (int j = 0; j < c_nbnxnGpuClusterSize; j++)
586 int j0 = (csj*c_nbnxnGpuClusterSize + j)*stride;
588 real d2 = gmx::square(x_i[i0 ] - x_j[j0 ]) + gmx::square(x_i[i0+1] - x_j[j0+1]) + gmx::square(x_i[i0+2] - x_j[j0+2]);
590 if (d2 < rlist2)
592 return TRUE;
597 return FALSE;
599 #else /* !GMX_SIMD4_HAVE_REAL */
601 /* 4-wide SIMD version.
602 * A cluster is hard-coded to 8 atoms.
603 * The coordinates x_i are stored as xxxxyyyy..., x_j is stored xyzxyz...
604 * Using 8-wide AVX(2) is not faster on Intel Sandy Bridge and Haswell.
606 assert(c_nbnxnGpuClusterSize == 8);
608 Simd4Real rc2_S = Simd4Real(rlist2);
610 const real *x_i = work->x_ci_simd;
612 int dim_stride = c_nbnxnGpuClusterSize*DIM;
613 Simd4Real ix_S0 = load4(x_i + si*dim_stride + 0*GMX_SIMD4_WIDTH);
614 Simd4Real iy_S0 = load4(x_i + si*dim_stride + 1*GMX_SIMD4_WIDTH);
615 Simd4Real iz_S0 = load4(x_i + si*dim_stride + 2*GMX_SIMD4_WIDTH);
616 Simd4Real ix_S1 = load4(x_i + si*dim_stride + 3*GMX_SIMD4_WIDTH);
617 Simd4Real iy_S1 = load4(x_i + si*dim_stride + 4*GMX_SIMD4_WIDTH);
618 Simd4Real iz_S1 = load4(x_i + si*dim_stride + 5*GMX_SIMD4_WIDTH);
620 /* We loop from the outer to the inner particles to maximize
621 * the chance that we find a pair in range quickly and return.
623 int j0 = csj*c_nbnxnGpuClusterSize;
624 int j1 = j0 + c_nbnxnGpuClusterSize - 1;
625 while (j0 < j1)
627 Simd4Real jx0_S, jy0_S, jz0_S;
628 Simd4Real jx1_S, jy1_S, jz1_S;
630 Simd4Real dx_S0, dy_S0, dz_S0;
631 Simd4Real dx_S1, dy_S1, dz_S1;
632 Simd4Real dx_S2, dy_S2, dz_S2;
633 Simd4Real dx_S3, dy_S3, dz_S3;
635 Simd4Real rsq_S0;
636 Simd4Real rsq_S1;
637 Simd4Real rsq_S2;
638 Simd4Real rsq_S3;
640 Simd4Bool wco_S0;
641 Simd4Bool wco_S1;
642 Simd4Bool wco_S2;
643 Simd4Bool wco_S3;
644 Simd4Bool wco_any_S01, wco_any_S23, wco_any_S;
646 jx0_S = Simd4Real(x_j[j0*stride+0]);
647 jy0_S = Simd4Real(x_j[j0*stride+1]);
648 jz0_S = Simd4Real(x_j[j0*stride+2]);
650 jx1_S = Simd4Real(x_j[j1*stride+0]);
651 jy1_S = Simd4Real(x_j[j1*stride+1]);
652 jz1_S = Simd4Real(x_j[j1*stride+2]);
654 /* Calculate distance */
655 dx_S0 = ix_S0 - jx0_S;
656 dy_S0 = iy_S0 - jy0_S;
657 dz_S0 = iz_S0 - jz0_S;
658 dx_S1 = ix_S1 - jx0_S;
659 dy_S1 = iy_S1 - jy0_S;
660 dz_S1 = iz_S1 - jz0_S;
661 dx_S2 = ix_S0 - jx1_S;
662 dy_S2 = iy_S0 - jy1_S;
663 dz_S2 = iz_S0 - jz1_S;
664 dx_S3 = ix_S1 - jx1_S;
665 dy_S3 = iy_S1 - jy1_S;
666 dz_S3 = iz_S1 - jz1_S;
668 /* rsq = dx*dx+dy*dy+dz*dz */
669 rsq_S0 = norm2(dx_S0, dy_S0, dz_S0);
670 rsq_S1 = norm2(dx_S1, dy_S1, dz_S1);
671 rsq_S2 = norm2(dx_S2, dy_S2, dz_S2);
672 rsq_S3 = norm2(dx_S3, dy_S3, dz_S3);
674 wco_S0 = (rsq_S0 < rc2_S);
675 wco_S1 = (rsq_S1 < rc2_S);
676 wco_S2 = (rsq_S2 < rc2_S);
677 wco_S3 = (rsq_S3 < rc2_S);
679 wco_any_S01 = wco_S0 || wco_S1;
680 wco_any_S23 = wco_S2 || wco_S3;
681 wco_any_S = wco_any_S01 || wco_any_S23;
683 if (anyTrue(wco_any_S))
685 return TRUE;
688 j0++;
689 j1--;
692 return FALSE;
694 #endif /* !GMX_SIMD4_HAVE_REAL */
697 /* Returns the j sub-cell for index cj_ind */
698 static int nbl_cj(const nbnxn_pairlist_t *nbl, int cj_ind)
700 return nbl->cj4[cj_ind/c_nbnxnGpuJgroupSize].cj[cj_ind & (c_nbnxnGpuJgroupSize - 1)];
703 /* Returns the i-interaction mask of the j sub-cell for index cj_ind */
704 static unsigned int nbl_imask0(const nbnxn_pairlist_t *nbl, int cj_ind)
706 return nbl->cj4[cj_ind/c_nbnxnGpuJgroupSize].imei[0].imask;
709 /* Ensures there is enough space for extra extra exclusion masks */
710 static void check_excl_space(nbnxn_pairlist_t *nbl, int extra)
712 if (nbl->nexcl+extra > nbl->excl_nalloc)
714 nbl->excl_nalloc = over_alloc_small(nbl->nexcl+extra);
715 nbnxn_realloc_void((void **)&nbl->excl,
716 nbl->nexcl*sizeof(*nbl->excl),
717 nbl->excl_nalloc*sizeof(*nbl->excl),
718 nbl->alloc, nbl->free);
722 /* Ensures there is enough space for maxNumExtraClusters extra j-clusters in the list */
723 static void check_cell_list_space_simple(nbnxn_pairlist_t *nbl,
724 int maxNumExtraClusters)
726 int cj_max;
728 cj_max = nbl->ncj + maxNumExtraClusters;
730 if (cj_max > nbl->cj_nalloc)
732 nbl->cj_nalloc = over_alloc_small(cj_max);
733 nbnxn_realloc_void((void **)&nbl->cj,
734 nbl->ncj*sizeof(*nbl->cj),
735 nbl->cj_nalloc*sizeof(*nbl->cj),
736 nbl->alloc, nbl->free);
738 nbnxn_realloc_void((void **)&nbl->cjOuter,
739 nbl->ncj*sizeof(*nbl->cjOuter),
740 nbl->cj_nalloc*sizeof(*nbl->cjOuter),
741 nbl->alloc, nbl->free);
745 /* Ensures there is enough space for ncell extra j-clusters in the list */
746 static void check_cell_list_space_supersub(nbnxn_pairlist_t *nbl,
747 int ncell)
749 int ncj4_max, w;
751 /* We can have maximally nsupercell*c_gpuNumClusterPerCell sj lists */
752 /* We can store 4 j-subcell - i-supercell pairs in one struct.
753 * since we round down, we need one extra entry.
755 ncj4_max = ((nbl->work->cj_ind + ncell*c_gpuNumClusterPerCell + c_nbnxnGpuJgroupSize - 1)/c_nbnxnGpuJgroupSize);
757 if (ncj4_max > nbl->cj4_nalloc)
759 nbl->cj4_nalloc = over_alloc_small(ncj4_max);
760 nbnxn_realloc_void((void **)&nbl->cj4,
761 nbl->work->cj4_init*sizeof(*nbl->cj4),
762 nbl->cj4_nalloc*sizeof(*nbl->cj4),
763 nbl->alloc, nbl->free);
766 if (ncj4_max > nbl->work->cj4_init)
768 for (int j4 = nbl->work->cj4_init; j4 < ncj4_max; j4++)
770 /* No i-subcells and no excl's in the list initially */
771 for (w = 0; w < c_nbnxnGpuClusterpairSplit; w++)
773 nbl->cj4[j4].imei[w].imask = 0U;
774 nbl->cj4[j4].imei[w].excl_ind = 0;
778 nbl->work->cj4_init = ncj4_max;
782 /* Set all excl masks for one GPU warp no exclusions */
783 static void set_no_excls(nbnxn_excl_t *excl)
785 for (int t = 0; t < c_nbnxnGpuExclSize; t++)
787 /* Turn all interaction bits on */
788 excl->pair[t] = NBNXN_INTERACTION_MASK_ALL;
792 /* Initializes a single nbnxn_pairlist_t data structure */
793 static void nbnxn_init_pairlist(nbnxn_pairlist_t *nbl,
794 gmx_bool bSimple,
795 nbnxn_alloc_t *alloc,
796 nbnxn_free_t *free)
798 if (alloc == nullptr)
800 nbl->alloc = nbnxn_alloc_aligned;
802 else
804 nbl->alloc = alloc;
806 if (free == nullptr)
808 nbl->free = nbnxn_free_aligned;
810 else
812 nbl->free = free;
815 nbl->bSimple = bSimple;
816 nbl->na_sc = 0;
817 nbl->na_ci = 0;
818 nbl->na_cj = 0;
819 nbl->nci = 0;
820 nbl->ci = nullptr;
821 nbl->ci_nalloc = 0;
822 nbl->nsci = 0;
823 nbl->sci = nullptr;
824 nbl->sci_nalloc = 0;
825 nbl->ncj = 0;
826 nbl->ncjInUse = 0;
827 nbl->cj = nullptr;
828 nbl->cj_nalloc = 0;
829 nbl->ncj4 = 0;
830 /* We need one element extra in sj, so alloc initially with 1 */
831 nbl->cj4_nalloc = 0;
832 nbl->cj4 = nullptr;
833 nbl->nci_tot = 0;
835 if (!nbl->bSimple)
837 GMX_ASSERT(c_nbnxnGpuNumClusterPerSupercluster == c_gpuNumClusterPerCell, "The search code assumes that the a super-cluster matches a search grid cell");
839 GMX_ASSERT(sizeof(nbl->cj4[0].imei[0].imask)*8 >= c_nbnxnGpuJgroupSize*c_gpuNumClusterPerCell, "The i super-cluster cluster interaction mask does not contain a sufficient number of bits");
840 GMX_ASSERT(sizeof(nbl->excl[0])*8 >= c_nbnxnGpuJgroupSize*c_gpuNumClusterPerCell, "The GPU exclusion mask does not contain a sufficient number of bits");
842 nbl->excl = nullptr;
843 nbl->excl_nalloc = 0;
844 nbl->nexcl = 0;
845 check_excl_space(nbl, 1);
846 nbl->nexcl = 1;
847 set_no_excls(&nbl->excl[0]);
850 snew(nbl->work, 1);
851 if (nbl->bSimple)
853 snew_aligned(nbl->work->bb_ci, 1, NBNXN_SEARCH_BB_MEM_ALIGN);
855 else
857 #if NBNXN_BBXXXX
858 snew_aligned(nbl->work->pbb_ci, c_gpuNumClusterPerCell/STRIDE_PBB*NNBSBB_XXXX, NBNXN_SEARCH_BB_MEM_ALIGN);
859 #else
860 snew_aligned(nbl->work->bb_ci, c_gpuNumClusterPerCell, NBNXN_SEARCH_BB_MEM_ALIGN);
861 #endif
863 int gpu_clusterpair_nc = c_gpuNumClusterPerCell*c_nbnxnGpuClusterSize*DIM;
864 snew(nbl->work->x_ci, gpu_clusterpair_nc);
865 #if GMX_SIMD
866 snew_aligned(nbl->work->x_ci_simd,
867 std::max(NBNXN_CPU_CLUSTER_I_SIZE*DIM*GMX_SIMD_REAL_WIDTH,
868 gpu_clusterpair_nc),
869 GMX_SIMD_REAL_WIDTH);
870 #endif
871 snew_aligned(nbl->work->d2, c_gpuNumClusterPerCell, NBNXN_SEARCH_BB_MEM_ALIGN);
873 nbl->work->sort = nullptr;
874 nbl->work->sort_nalloc = 0;
875 nbl->work->sci_sort = nullptr;
876 nbl->work->sci_sort_nalloc = 0;
879 void nbnxn_init_pairlist_set(nbnxn_pairlist_set_t *nbl_list,
880 gmx_bool bSimple, gmx_bool bCombined,
881 nbnxn_alloc_t *alloc,
882 nbnxn_free_t *free)
884 nbl_list->bSimple = bSimple;
885 nbl_list->bCombined = bCombined;
887 nbl_list->nnbl = gmx_omp_nthreads_get(emntNonbonded);
889 if (!nbl_list->bCombined &&
890 nbl_list->nnbl > NBNXN_BUFFERFLAG_MAX_THREADS)
892 gmx_fatal(FARGS, "%d OpenMP threads were requested. Since the non-bonded force buffer reduction is prohibitively slow with more than %d threads, we do not allow this. Use %d or less OpenMP threads.",
893 nbl_list->nnbl, NBNXN_BUFFERFLAG_MAX_THREADS, NBNXN_BUFFERFLAG_MAX_THREADS);
896 snew(nbl_list->nbl, nbl_list->nnbl);
897 if (bSimple && nbl_list->nnbl > 1)
899 snew(nbl_list->nbl_work, nbl_list->nnbl);
901 snew(nbl_list->nbl_fep, nbl_list->nnbl);
902 /* Execute in order to avoid memory interleaving between threads */
903 #pragma omp parallel for num_threads(nbl_list->nnbl) schedule(static)
904 for (int i = 0; i < nbl_list->nnbl; i++)
908 /* Allocate the nblist data structure locally on each thread
909 * to optimize memory access for NUMA architectures.
911 snew(nbl_list->nbl[i], 1);
913 /* Only list 0 is used on the GPU, use normal allocation for i>0 */
914 if (!bSimple && i == 0)
916 nbnxn_init_pairlist(nbl_list->nbl[i], nbl_list->bSimple, alloc, free);
918 else
920 nbnxn_init_pairlist(nbl_list->nbl[i], nbl_list->bSimple, nullptr, nullptr);
921 if (bSimple && nbl_list->nnbl > 1)
923 snew(nbl_list->nbl_work[i], 1);
924 nbnxn_init_pairlist(nbl_list->nbl_work[i], nbl_list->bSimple, nullptr, nullptr);
928 snew(nbl_list->nbl_fep[i], 1);
929 nbnxn_init_pairlist_fep(nbl_list->nbl_fep[i]);
931 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
935 /* Print statistics of a pair list, used for debug output */
936 static void print_nblist_statistics_simple(FILE *fp, const nbnxn_pairlist_t *nbl,
937 const nbnxn_search_t nbs, real rl)
939 const nbnxn_grid_t *grid;
940 int cs[SHIFTS];
941 int npexcl;
943 grid = &nbs->grid[0];
945 fprintf(fp, "nbl nci %d ncj %d\n",
946 nbl->nci, nbl->ncjInUse);
947 fprintf(fp, "nbl na_sc %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n",
948 nbl->na_sc, rl, nbl->ncjInUse, nbl->ncjInUse/(double)grid->nc,
949 nbl->ncjInUse/(double)grid->nc*grid->na_sc,
950 nbl->ncjInUse/(double)grid->nc*grid->na_sc/(0.5*4.0/3.0*M_PI*rl*rl*rl*grid->nc*grid->na_sc/(grid->size[XX]*grid->size[YY]*grid->size[ZZ])));
952 fprintf(fp, "nbl average j cell list length %.1f\n",
953 0.25*nbl->ncjInUse/(double)std::max(nbl->nci, 1));
955 for (int s = 0; s < SHIFTS; s++)
957 cs[s] = 0;
959 npexcl = 0;
960 for (int i = 0; i < nbl->nci; i++)
962 cs[nbl->ci[i].shift & NBNXN_CI_SHIFT] +=
963 nbl->ci[i].cj_ind_end - nbl->ci[i].cj_ind_start;
965 int j = nbl->ci[i].cj_ind_start;
966 while (j < nbl->ci[i].cj_ind_end &&
967 nbl->cj[j].excl != NBNXN_INTERACTION_MASK_ALL)
969 npexcl++;
970 j++;
973 fprintf(fp, "nbl cell pairs, total: %d excl: %d %.1f%%\n",
974 nbl->ncj, npexcl, 100*npexcl/(double)std::max(nbl->ncj, 1));
975 for (int s = 0; s < SHIFTS; s++)
977 if (cs[s] > 0)
979 fprintf(fp, "nbl shift %2d ncj %3d\n", s, cs[s]);
984 /* Print statistics of a pair lists, used for debug output */
985 static void print_nblist_statistics_supersub(FILE *fp, const nbnxn_pairlist_t *nbl,
986 const nbnxn_search_t nbs, real rl)
988 const nbnxn_grid_t *grid;
989 int b;
990 int c[c_gpuNumClusterPerCell + 1];
991 double sum_nsp, sum_nsp2;
992 int nsp_max;
994 /* This code only produces correct statistics with domain decomposition */
995 grid = &nbs->grid[0];
997 fprintf(fp, "nbl nsci %d ncj4 %d nsi %d excl4 %d\n",
998 nbl->nsci, nbl->ncj4, nbl->nci_tot, nbl->nexcl);
999 fprintf(fp, "nbl na_c %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n",
1000 nbl->na_ci, rl, nbl->nci_tot, nbl->nci_tot/(double)grid->nsubc_tot,
1001 nbl->nci_tot/(double)grid->nsubc_tot*grid->na_c,
1002 nbl->nci_tot/(double)grid->nsubc_tot*grid->na_c/(0.5*4.0/3.0*M_PI*rl*rl*rl*grid->nsubc_tot*grid->na_c/(grid->size[XX]*grid->size[YY]*grid->size[ZZ])));
1004 sum_nsp = 0;
1005 sum_nsp2 = 0;
1006 nsp_max = 0;
1007 for (int si = 0; si <= c_gpuNumClusterPerCell; si++)
1009 c[si] = 0;
1011 for (int i = 0; i < nbl->nsci; i++)
1013 int nsp;
1015 nsp = 0;
1016 for (int j4 = nbl->sci[i].cj4_ind_start; j4 < nbl->sci[i].cj4_ind_end; j4++)
1018 for (int j = 0; j < c_nbnxnGpuJgroupSize; j++)
1020 b = 0;
1021 for (int si = 0; si < c_gpuNumClusterPerCell; si++)
1023 if (nbl->cj4[j4].imei[0].imask & (1U << (j*c_gpuNumClusterPerCell + si)))
1025 b++;
1028 nsp += b;
1029 c[b]++;
1032 sum_nsp += nsp;
1033 sum_nsp2 += nsp*nsp;
1034 nsp_max = std::max(nsp_max, nsp);
1036 if (nbl->nsci > 0)
1038 sum_nsp /= nbl->nsci;
1039 sum_nsp2 /= nbl->nsci;
1041 fprintf(fp, "nbl #cluster-pairs: av %.1f stddev %.1f max %d\n",
1042 sum_nsp, std::sqrt(sum_nsp2 - sum_nsp*sum_nsp), nsp_max);
1044 if (nbl->ncj4 > 0)
1046 for (b = 0; b <= c_gpuNumClusterPerCell; b++)
1048 fprintf(fp, "nbl j-list #i-subcell %d %7d %4.1f\n",
1049 b, c[b],
1050 100.0*c[b]/(double)(nbl->ncj4*c_nbnxnGpuJgroupSize));
1055 /* Returns a pointer to the exclusion mask for cj4-unit cj4, warp warp */
1056 static void low_get_nbl_exclusions(nbnxn_pairlist_t *nbl, int cj4,
1057 int warp, nbnxn_excl_t **excl)
1059 if (nbl->cj4[cj4].imei[warp].excl_ind == 0)
1061 /* No exclusions set, make a new list entry */
1062 nbl->cj4[cj4].imei[warp].excl_ind = nbl->nexcl;
1063 nbl->nexcl++;
1064 *excl = &nbl->excl[nbl->cj4[cj4].imei[warp].excl_ind];
1065 set_no_excls(*excl);
1067 else
1069 /* We already have some exclusions, new ones can be added to the list */
1070 *excl = &nbl->excl[nbl->cj4[cj4].imei[warp].excl_ind];
1074 /* Returns a pointer to the exclusion mask for cj4-unit cj4, warp warp,
1075 * generates a new element and allocates extra memory, if necessary.
1077 static void get_nbl_exclusions_1(nbnxn_pairlist_t *nbl, int cj4,
1078 int warp, nbnxn_excl_t **excl)
1080 if (nbl->cj4[cj4].imei[warp].excl_ind == 0)
1082 /* We need to make a new list entry, check if we have space */
1083 check_excl_space(nbl, 1);
1085 low_get_nbl_exclusions(nbl, cj4, warp, excl);
1088 /* Returns pointers to the exclusion masks for cj4-unit cj4 for both warps,
1089 * generates a new element and allocates extra memory, if necessary.
1091 static void get_nbl_exclusions_2(nbnxn_pairlist_t *nbl, int cj4,
1092 nbnxn_excl_t **excl_w0,
1093 nbnxn_excl_t **excl_w1)
1095 /* Check for space we might need */
1096 check_excl_space(nbl, 2);
1098 low_get_nbl_exclusions(nbl, cj4, 0, excl_w0);
1099 low_get_nbl_exclusions(nbl, cj4, 1, excl_w1);
1102 /* Sets the self exclusions i=j and pair exclusions i>j */
1103 static void set_self_and_newton_excls_supersub(nbnxn_pairlist_t *nbl,
1104 int cj4_ind, int sj_offset,
1105 int i_cluster_in_cell)
1107 nbnxn_excl_t *excl[c_nbnxnGpuClusterpairSplit];
1109 /* Here we only set the set self and double pair exclusions */
1111 assert(c_nbnxnGpuClusterpairSplit == 2);
1113 get_nbl_exclusions_2(nbl, cj4_ind, &excl[0], &excl[1]);
1115 /* Only minor < major bits set */
1116 for (int ej = 0; ej < nbl->na_ci; ej++)
1118 int w = (ej>>2);
1119 for (int ei = ej; ei < nbl->na_ci; ei++)
1121 excl[w]->pair[(ej & (c_nbnxnGpuJgroupSize-1))*nbl->na_ci + ei] &=
1122 ~(1U << (sj_offset*c_gpuNumClusterPerCell + i_cluster_in_cell));
1127 /* Returns a diagonal or off-diagonal interaction mask for plain C lists */
1128 static unsigned int get_imask(gmx_bool rdiag, int ci, int cj)
1130 return (rdiag && ci == cj ? NBNXN_INTERACTION_MASK_DIAG : NBNXN_INTERACTION_MASK_ALL);
1133 /* Returns a diagonal or off-diagonal interaction mask for cj-size=2 */
1134 gmx_unused static unsigned int get_imask_simd_j2(gmx_bool rdiag, int ci, int cj)
1136 return (rdiag && ci*2 == cj ? NBNXN_INTERACTION_MASK_DIAG_J2_0 :
1137 (rdiag && ci*2+1 == cj ? NBNXN_INTERACTION_MASK_DIAG_J2_1 :
1138 NBNXN_INTERACTION_MASK_ALL));
1141 /* Returns a diagonal or off-diagonal interaction mask for cj-size=4 */
1142 gmx_unused static unsigned int get_imask_simd_j4(gmx_bool rdiag, int ci, int cj)
1144 return (rdiag && ci == cj ? NBNXN_INTERACTION_MASK_DIAG : NBNXN_INTERACTION_MASK_ALL);
1147 /* Returns a diagonal or off-diagonal interaction mask for cj-size=8 */
1148 gmx_unused static unsigned int get_imask_simd_j8(gmx_bool rdiag, int ci, int cj)
1150 return (rdiag && ci == cj*2 ? NBNXN_INTERACTION_MASK_DIAG_J8_0 :
1151 (rdiag && ci == cj*2+1 ? NBNXN_INTERACTION_MASK_DIAG_J8_1 :
1152 NBNXN_INTERACTION_MASK_ALL));
1155 #if GMX_SIMD
1156 #if GMX_SIMD_REAL_WIDTH == 2
1157 #define get_imask_simd_4xn get_imask_simd_j2
1158 #endif
1159 #if GMX_SIMD_REAL_WIDTH == 4
1160 #define get_imask_simd_4xn get_imask_simd_j4
1161 #endif
1162 #if GMX_SIMD_REAL_WIDTH == 8
1163 #define get_imask_simd_4xn get_imask_simd_j8
1164 #define get_imask_simd_2xnn get_imask_simd_j4
1165 #endif
1166 #if GMX_SIMD_REAL_WIDTH == 16
1167 #define get_imask_simd_2xnn get_imask_simd_j8
1168 #endif
1169 #endif
1171 /* Plain C code for checking and adding cluster-pairs to the list.
1173 * \param[in] gridj The j-grid
1174 * \param[in,out] nbl The pair-list to store the cluster pairs in
1175 * \param[in] icluster The index of the i-cluster
1176 * \param[in] jclusterFirst The first cluster in the j-range
1177 * \param[in] jclusterLast The last cluster in the j-range
1178 * \param[in] excludeSubDiagonal Exclude atom pairs with i-index > j-index
1179 * \param[in] x_j Coordinates for the j-atom, in xyz format
1180 * \param[in] rlist2 The squared list cut-off
1181 * \param[in] rbb2 The squared cut-off for putting cluster-pairs in the list based on bounding box distance only
1182 * \param[in,out] numDistanceChecks The number of distance checks performed
1184 static void
1185 makeClusterListSimple(const nbnxn_grid_t * gridj,
1186 nbnxn_pairlist_t * nbl,
1187 int icluster,
1188 int jclusterFirst,
1189 int jclusterLast,
1190 bool excludeSubDiagonal,
1191 const real * gmx_restrict x_j,
1192 real rlist2,
1193 float rbb2,
1194 int * gmx_restrict numDistanceChecks)
1196 const nbnxn_bb_t * gmx_restrict bb_ci = nbl->work->bb_ci;
1197 const real * gmx_restrict x_ci = nbl->work->x_ci;
1199 gmx_bool InRange;
1201 InRange = FALSE;
1202 while (!InRange && jclusterFirst <= jclusterLast)
1204 real d2 = subc_bb_dist2(0, bb_ci, jclusterFirst, gridj->bb);
1205 *numDistanceChecks += 2;
1207 /* Check if the distance is within the distance where
1208 * we use only the bounding box distance rbb,
1209 * or within the cut-off and there is at least one atom pair
1210 * within the cut-off.
1212 if (d2 < rbb2)
1214 InRange = TRUE;
1216 else if (d2 < rlist2)
1218 int cjf_gl = gridj->cell0 + jclusterFirst;
1219 for (int i = 0; i < NBNXN_CPU_CLUSTER_I_SIZE && !InRange; i++)
1221 for (int j = 0; j < NBNXN_CPU_CLUSTER_I_SIZE; j++)
1223 InRange = InRange ||
1224 (gmx::square(x_ci[i*STRIDE_XYZ+XX] - x_j[(cjf_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+XX]) +
1225 gmx::square(x_ci[i*STRIDE_XYZ+YY] - x_j[(cjf_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+YY]) +
1226 gmx::square(x_ci[i*STRIDE_XYZ+ZZ] - x_j[(cjf_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+ZZ]) < rlist2);
1229 *numDistanceChecks += NBNXN_CPU_CLUSTER_I_SIZE*NBNXN_CPU_CLUSTER_I_SIZE;
1231 if (!InRange)
1233 jclusterFirst++;
1236 if (!InRange)
1238 return;
1241 InRange = FALSE;
1242 while (!InRange && jclusterLast > jclusterFirst)
1244 real d2 = subc_bb_dist2(0, bb_ci, jclusterLast, gridj->bb);
1245 *numDistanceChecks += 2;
1247 /* Check if the distance is within the distance where
1248 * we use only the bounding box distance rbb,
1249 * or within the cut-off and there is at least one atom pair
1250 * within the cut-off.
1252 if (d2 < rbb2)
1254 InRange = TRUE;
1256 else if (d2 < rlist2)
1258 int cjl_gl = gridj->cell0 + jclusterLast;
1259 for (int i = 0; i < NBNXN_CPU_CLUSTER_I_SIZE && !InRange; i++)
1261 for (int j = 0; j < NBNXN_CPU_CLUSTER_I_SIZE; j++)
1263 InRange = InRange ||
1264 (gmx::square(x_ci[i*STRIDE_XYZ+XX] - x_j[(cjl_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+XX]) +
1265 gmx::square(x_ci[i*STRIDE_XYZ+YY] - x_j[(cjl_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+YY]) +
1266 gmx::square(x_ci[i*STRIDE_XYZ+ZZ] - x_j[(cjl_gl*NBNXN_CPU_CLUSTER_I_SIZE+j)*STRIDE_XYZ+ZZ]) < rlist2);
1269 *numDistanceChecks += NBNXN_CPU_CLUSTER_I_SIZE*NBNXN_CPU_CLUSTER_I_SIZE;
1271 if (!InRange)
1273 jclusterLast--;
1277 if (jclusterFirst <= jclusterLast)
1279 for (int jcluster = jclusterFirst; jcluster <= jclusterLast; jcluster++)
1281 /* Store cj and the interaction mask */
1282 nbl->cj[nbl->ncj].cj = gridj->cell0 + jcluster;
1283 nbl->cj[nbl->ncj].excl = get_imask(excludeSubDiagonal, icluster, jcluster);
1284 nbl->ncj++;
1286 /* Increase the closing index in i super-cell list */
1287 nbl->ci[nbl->nci].cj_ind_end = nbl->ncj;
1291 #ifdef GMX_NBNXN_SIMD_4XN
1292 #include "gromacs/mdlib/nbnxn_search_simd_4xn.h"
1293 #endif
1294 #ifdef GMX_NBNXN_SIMD_2XNN
1295 #include "gromacs/mdlib/nbnxn_search_simd_2xnn.h"
1296 #endif
1298 /* Plain C or SIMD4 code for making a pair list of super-cell sci vs scj.
1299 * Checks bounding box distances and possibly atom pair distances.
1301 static void make_cluster_list_supersub(const nbnxn_grid_t *gridi,
1302 const nbnxn_grid_t *gridj,
1303 nbnxn_pairlist_t *nbl,
1304 int sci, int scj,
1305 gmx_bool sci_equals_scj,
1306 int stride, const real *x,
1307 real rlist2, float rbb2,
1308 int *numDistanceChecks)
1310 nbnxn_list_work_t *work = nbl->work;
1312 #if NBNXN_BBXXXX
1313 const float *pbb_ci = work->pbb_ci;
1314 #else
1315 const nbnxn_bb_t *bb_ci = work->bb_ci;
1316 #endif
1318 assert(c_nbnxnGpuClusterSize == gridi->na_c);
1319 assert(c_nbnxnGpuClusterSize == gridj->na_c);
1321 /* We generate the pairlist mainly based on bounding-box distances
1322 * and do atom pair distance based pruning on the GPU.
1323 * Only if a j-group contains a single cluster-pair, we try to prune
1324 * that pair based on atom distances on the CPU to avoid empty j-groups.
1326 #define PRUNE_LIST_CPU_ONE 1
1327 #define PRUNE_LIST_CPU_ALL 0
1329 #if PRUNE_LIST_CPU_ONE
1330 int ci_last = -1;
1331 #endif
1333 float *d2l = work->d2;
1335 for (int subc = 0; subc < gridj->nsubc[scj]; subc++)
1337 int cj4_ind = nbl->work->cj_ind/c_nbnxnGpuJgroupSize;
1338 int cj_offset = nbl->work->cj_ind - cj4_ind*c_nbnxnGpuJgroupSize;
1339 nbnxn_cj4_t *cj4 = &nbl->cj4[cj4_ind];
1341 int cj = scj*c_gpuNumClusterPerCell + subc;
1343 int cj_gl = gridj->cell0*c_gpuNumClusterPerCell + cj;
1345 /* Initialize this j-subcell i-subcell list */
1346 cj4->cj[cj_offset] = cj_gl;
1348 int ci1;
1349 if (sci_equals_scj)
1351 ci1 = subc + 1;
1353 else
1355 ci1 = gridi->nsubc[sci];
1358 #if NBNXN_BBXXXX
1359 /* Determine all ci1 bb distances in one call with SIMD4 */
1360 subc_bb_dist2_simd4_xxxx(gridj->pbb+(cj>>STRIDE_PBB_2LOG)*NNBSBB_XXXX+(cj & (STRIDE_PBB-1)),
1361 ci1, pbb_ci, d2l);
1362 *numDistanceChecks += c_nbnxnGpuClusterSize*2;
1363 #endif
1365 int npair = 0;
1366 unsigned int imask = 0;
1367 /* We use a fixed upper-bound instead of ci1 to help optimization */
1368 for (int ci = 0; ci < c_gpuNumClusterPerCell; ci++)
1370 if (ci == ci1)
1372 break;
1375 #if !NBNXN_BBXXXX
1376 /* Determine the bb distance between ci and cj */
1377 d2l[ci] = subc_bb_dist2(ci, bb_ci, cj, gridj->bb);
1378 *numDistanceChecks += 2;
1379 #endif
1380 float d2 = d2l[ci];
1382 #if PRUNE_LIST_CPU_ALL
1383 /* Check if the distance is within the distance where
1384 * we use only the bounding box distance rbb,
1385 * or within the cut-off and there is at least one atom pair
1386 * within the cut-off. This check is very costly.
1388 *numDistanceChecks += c_nbnxnGpuClusterSize*c_nbnxnGpuClusterSize;
1389 if (d2 < rbb2 ||
1390 (d2 < rlist2 &&
1391 clusterpair_in_range(work, ci, cj_gl, stride, x, rlist2)))
1392 #else
1393 /* Check if the distance between the two bounding boxes
1394 * in within the pair-list cut-off.
1396 if (d2 < rlist2)
1397 #endif
1399 /* Flag this i-subcell to be taken into account */
1400 imask |= (1U << (cj_offset*c_gpuNumClusterPerCell + ci));
1402 #if PRUNE_LIST_CPU_ONE
1403 ci_last = ci;
1404 #endif
1406 npair++;
1410 #if PRUNE_LIST_CPU_ONE
1411 /* If we only found 1 pair, check if any atoms are actually
1412 * within the cut-off, so we could get rid of it.
1414 if (npair == 1 && d2l[ci_last] >= rbb2 &&
1415 !clusterpair_in_range(work, ci_last, cj_gl, stride, x, rlist2))
1417 imask &= ~(1U << (cj_offset*c_gpuNumClusterPerCell + ci_last));
1418 npair--;
1420 #endif
1422 if (npair > 0)
1424 /* We have a useful sj entry, close it now */
1426 /* Set the exclusions for the ci==sj entry.
1427 * Here we don't bother to check if this entry is actually flagged,
1428 * as it will nearly always be in the list.
1430 if (sci_equals_scj)
1432 set_self_and_newton_excls_supersub(nbl, cj4_ind, cj_offset, subc);
1435 /* Copy the cluster interaction mask to the list */
1436 for (int w = 0; w < c_nbnxnGpuClusterpairSplit; w++)
1438 cj4->imei[w].imask |= imask;
1441 nbl->work->cj_ind++;
1443 /* Keep the count */
1444 nbl->nci_tot += npair;
1446 /* Increase the closing index in i super-cell list */
1447 nbl->sci[nbl->nsci].cj4_ind_end =
1448 (nbl->work->cj_ind + c_nbnxnGpuJgroupSize - 1)/c_nbnxnGpuJgroupSize;
1453 /* Set all atom-pair exclusions from the topology stored in excl
1454 * as masks in the pair-list for simple list i-entry nbl_ci
1456 static void set_ci_top_excls(const nbnxn_search_t nbs,
1457 nbnxn_pairlist_t *nbl,
1458 gmx_bool diagRemoved,
1459 int na_ci_2log,
1460 int na_cj_2log,
1461 const nbnxn_ci_t *nbl_ci,
1462 const t_blocka *excl)
1464 const int *cell;
1465 int ci;
1466 int cj_ind_first, cj_ind_last;
1467 int cj_first, cj_last;
1468 int ndirect;
1469 int ai, aj, si, ge, se;
1470 int found, cj_ind_0, cj_ind_1, cj_ind_m;
1471 int cj_m;
1472 int inner_i, inner_e;
1474 cell = nbs->cell;
1476 if (nbl_ci->cj_ind_end == nbl_ci->cj_ind_start)
1478 /* Empty list */
1479 return;
1482 ci = nbl_ci->ci;
1484 cj_ind_first = nbl_ci->cj_ind_start;
1485 cj_ind_last = nbl->ncj - 1;
1487 cj_first = nbl->cj[cj_ind_first].cj;
1488 cj_last = nbl->cj[cj_ind_last].cj;
1490 /* Determine how many contiguous j-cells we have starting
1491 * from the first i-cell. This number can be used to directly
1492 * calculate j-cell indices for excluded atoms.
1494 ndirect = 0;
1495 if (na_ci_2log == na_cj_2log)
1497 while (cj_ind_first + ndirect <= cj_ind_last &&
1498 nbl->cj[cj_ind_first+ndirect].cj == ci + ndirect)
1500 ndirect++;
1503 #if NBNXN_SEARCH_BB_SIMD4
1504 else
1506 while (cj_ind_first + ndirect <= cj_ind_last &&
1507 nbl->cj[cj_ind_first+ndirect].cj == ci_to_cj(ci, na_cj_2log) + ndirect)
1509 ndirect++;
1512 #endif
1514 /* Loop over the atoms in the i super-cell */
1515 for (int i = 0; i < nbl->na_sc; i++)
1517 ai = nbs->a[ci*nbl->na_sc+i];
1518 if (ai >= 0)
1520 si = (i>>na_ci_2log);
1522 /* Loop over the topology-based exclusions for this i-atom */
1523 for (int eind = excl->index[ai]; eind < excl->index[ai+1]; eind++)
1525 aj = excl->a[eind];
1527 if (aj == ai)
1529 /* The self exclusion are already set, save some time */
1530 continue;
1533 ge = cell[aj];
1535 /* Without shifts we only calculate interactions j>i
1536 * for one-way pair-lists.
1538 if (diagRemoved && ge <= ci*nbl->na_sc + i)
1540 continue;
1543 se = (ge >> na_cj_2log);
1545 /* Could the cluster se be in our list? */
1546 if (se >= cj_first && se <= cj_last)
1548 if (se < cj_first + ndirect)
1550 /* We can calculate cj_ind directly from se */
1551 found = cj_ind_first + se - cj_first;
1553 else
1555 /* Search for se using bisection */
1556 found = -1;
1557 cj_ind_0 = cj_ind_first + ndirect;
1558 cj_ind_1 = cj_ind_last + 1;
1559 while (found == -1 && cj_ind_0 < cj_ind_1)
1561 cj_ind_m = (cj_ind_0 + cj_ind_1)>>1;
1563 cj_m = nbl->cj[cj_ind_m].cj;
1565 if (se == cj_m)
1567 found = cj_ind_m;
1569 else if (se < cj_m)
1571 cj_ind_1 = cj_ind_m;
1573 else
1575 cj_ind_0 = cj_ind_m + 1;
1580 if (found >= 0)
1582 inner_i = i - (si << na_ci_2log);
1583 inner_e = ge - (se << na_cj_2log);
1585 nbl->cj[found].excl &= ~(1U<<((inner_i<<na_cj_2log) + inner_e));
1593 /* Add a new i-entry to the FEP list and copy the i-properties */
1594 static gmx_inline void fep_list_new_nri_copy(t_nblist *nlist)
1596 /* Add a new i-entry */
1597 nlist->nri++;
1599 assert(nlist->nri < nlist->maxnri);
1601 /* Duplicate the last i-entry, except for jindex, which continues */
1602 nlist->iinr[nlist->nri] = nlist->iinr[nlist->nri-1];
1603 nlist->shift[nlist->nri] = nlist->shift[nlist->nri-1];
1604 nlist->gid[nlist->nri] = nlist->gid[nlist->nri-1];
1605 nlist->jindex[nlist->nri] = nlist->nrj;
1608 /* For load balancing of the free-energy lists over threads, we set
1609 * the maximum nrj size of an i-entry to 40. This leads to good
1610 * load balancing in the worst case scenario of a single perturbed
1611 * particle on 16 threads, while not introducing significant overhead.
1612 * Note that half of the perturbed pairs will anyhow end up in very small lists,
1613 * since non perturbed i-particles will see few perturbed j-particles).
1615 const int max_nrj_fep = 40;
1617 /* Exclude the perturbed pairs from the Verlet list. This is only done to avoid
1618 * singularities for overlapping particles (0/0), since the charges and
1619 * LJ parameters have been zeroed in the nbnxn data structure.
1620 * Simultaneously make a group pair list for the perturbed pairs.
1622 static void make_fep_list(const nbnxn_search_t nbs,
1623 const nbnxn_atomdata_t *nbat,
1624 nbnxn_pairlist_t *nbl,
1625 gmx_bool bDiagRemoved,
1626 nbnxn_ci_t *nbl_ci,
1627 const nbnxn_grid_t *gridi,
1628 const nbnxn_grid_t *gridj,
1629 t_nblist *nlist)
1631 int ci, cj_ind_start, cj_ind_end, cja, cjr;
1632 int nri_max;
1633 int ngid, gid_i = 0, gid_j, gid;
1634 int egp_shift, egp_mask;
1635 int gid_cj = 0;
1636 int ind_i, ind_j, ai, aj;
1637 int nri;
1638 gmx_bool bFEP_i, bFEP_i_all;
1640 if (nbl_ci->cj_ind_end == nbl_ci->cj_ind_start)
1642 /* Empty list */
1643 return;
1646 ci = nbl_ci->ci;
1648 cj_ind_start = nbl_ci->cj_ind_start;
1649 cj_ind_end = nbl_ci->cj_ind_end;
1651 /* In worst case we have alternating energy groups
1652 * and create #atom-pair lists, which means we need the size
1653 * of a cluster pair (na_ci*na_cj) times the number of cj's.
1655 nri_max = nbl->na_ci*nbl->na_cj*(cj_ind_end - cj_ind_start);
1656 if (nlist->nri + nri_max > nlist->maxnri)
1658 nlist->maxnri = over_alloc_large(nlist->nri + nri_max);
1659 reallocate_nblist(nlist);
1662 ngid = nbat->nenergrp;
1664 if (static_cast<std::size_t>(ngid*gridj->na_cj) > sizeof(gid_cj)*8)
1666 gmx_fatal(FARGS, "The Verlet scheme with %dx%d kernels and free-energy only supports up to %d energy groups",
1667 gridi->na_c, gridj->na_cj, (sizeof(gid_cj)*8)/gridj->na_cj);
1670 egp_shift = nbat->neg_2log;
1671 egp_mask = (1<<nbat->neg_2log) - 1;
1673 /* Loop over the atoms in the i sub-cell */
1674 bFEP_i_all = TRUE;
1675 for (int i = 0; i < nbl->na_ci; i++)
1677 ind_i = ci*nbl->na_ci + i;
1678 ai = nbs->a[ind_i];
1679 if (ai >= 0)
1681 nri = nlist->nri;
1682 nlist->jindex[nri+1] = nlist->jindex[nri];
1683 nlist->iinr[nri] = ai;
1684 /* The actual energy group pair index is set later */
1685 nlist->gid[nri] = 0;
1686 nlist->shift[nri] = nbl_ci->shift & NBNXN_CI_SHIFT;
1688 bFEP_i = gridi->fep[ci - gridi->cell0] & (1 << i);
1690 bFEP_i_all = bFEP_i_all && bFEP_i;
1692 if (nlist->nrj + (cj_ind_end - cj_ind_start)*nbl->na_cj > nlist->maxnrj)
1694 nlist->maxnrj = over_alloc_small(nlist->nrj + (cj_ind_end - cj_ind_start)*nbl->na_cj);
1695 srenew(nlist->jjnr, nlist->maxnrj);
1696 srenew(nlist->excl_fep, nlist->maxnrj);
1699 if (ngid > 1)
1701 gid_i = (nbat->energrp[ci] >> (egp_shift*i)) & egp_mask;
1704 for (int cj_ind = cj_ind_start; cj_ind < cj_ind_end; cj_ind++)
1706 unsigned int fep_cj;
1708 cja = nbl->cj[cj_ind].cj;
1710 if (gridj->na_cj == gridj->na_c)
1712 cjr = cja - gridj->cell0;
1713 fep_cj = gridj->fep[cjr];
1714 if (ngid > 1)
1716 gid_cj = nbat->energrp[cja];
1719 else if (2*gridj->na_cj == gridj->na_c)
1721 cjr = cja - gridj->cell0*2;
1722 /* Extract half of the ci fep/energrp mask */
1723 fep_cj = (gridj->fep[cjr>>1] >> ((cjr&1)*gridj->na_cj)) & ((1<<gridj->na_cj) - 1);
1724 if (ngid > 1)
1726 gid_cj = nbat->energrp[cja>>1] >> ((cja&1)*gridj->na_cj*egp_shift) & ((1<<(gridj->na_cj*egp_shift)) - 1);
1729 else
1731 cjr = cja - (gridj->cell0>>1);
1732 /* Combine two ci fep masks/energrp */
1733 fep_cj = gridj->fep[cjr*2] + (gridj->fep[cjr*2+1] << gridj->na_c);
1734 if (ngid > 1)
1736 gid_cj = nbat->energrp[cja*2] + (nbat->energrp[cja*2+1] << (gridj->na_c*egp_shift));
1740 if (bFEP_i || fep_cj != 0)
1742 for (int j = 0; j < nbl->na_cj; j++)
1744 /* Is this interaction perturbed and not excluded? */
1745 ind_j = cja*nbl->na_cj + j;
1746 aj = nbs->a[ind_j];
1747 if (aj >= 0 &&
1748 (bFEP_i || (fep_cj & (1 << j))) &&
1749 (!bDiagRemoved || ind_j >= ind_i))
1751 if (ngid > 1)
1753 gid_j = (gid_cj >> (j*egp_shift)) & egp_mask;
1754 gid = GID(gid_i, gid_j, ngid);
1756 if (nlist->nrj > nlist->jindex[nri] &&
1757 nlist->gid[nri] != gid)
1759 /* Energy group pair changed: new list */
1760 fep_list_new_nri_copy(nlist);
1761 nri = nlist->nri;
1763 nlist->gid[nri] = gid;
1766 if (nlist->nrj - nlist->jindex[nri] >= max_nrj_fep)
1768 fep_list_new_nri_copy(nlist);
1769 nri = nlist->nri;
1772 /* Add it to the FEP list */
1773 nlist->jjnr[nlist->nrj] = aj;
1774 nlist->excl_fep[nlist->nrj] = (nbl->cj[cj_ind].excl >> (i*nbl->na_cj + j)) & 1;
1775 nlist->nrj++;
1777 /* Exclude it from the normal list.
1778 * Note that the charge has been set to zero,
1779 * but we need to avoid 0/0, as perturbed atoms
1780 * can be on top of each other.
1782 nbl->cj[cj_ind].excl &= ~(1U << (i*nbl->na_cj + j));
1788 if (nlist->nrj > nlist->jindex[nri])
1790 /* Actually add this new, non-empty, list */
1791 nlist->nri++;
1792 nlist->jindex[nlist->nri] = nlist->nrj;
1797 if (bFEP_i_all)
1799 /* All interactions are perturbed, we can skip this entry */
1800 nbl_ci->cj_ind_end = cj_ind_start;
1801 nbl->ncjInUse -= cj_ind_end - cj_ind_start;
1805 /* Return the index of atom a within a cluster */
1806 static gmx_inline int cj_mod_cj4(int cj)
1808 return cj & (c_nbnxnGpuJgroupSize - 1);
1811 /* Convert a j-cluster to a cj4 group */
1812 static gmx_inline int cj_to_cj4(int cj)
1814 return cj/c_nbnxnGpuJgroupSize;
1817 /* Return the index of an j-atom within a warp */
1818 static gmx_inline int a_mod_wj(int a)
1820 return a & (c_nbnxnGpuClusterSize/c_nbnxnGpuClusterpairSplit - 1);
1823 /* As make_fep_list above, but for super/sub lists. */
1824 static void make_fep_list_supersub(const nbnxn_search_t nbs,
1825 const nbnxn_atomdata_t *nbat,
1826 nbnxn_pairlist_t *nbl,
1827 gmx_bool bDiagRemoved,
1828 const nbnxn_sci_t *nbl_sci,
1829 real shx,
1830 real shy,
1831 real shz,
1832 real rlist_fep2,
1833 const nbnxn_grid_t *gridi,
1834 const nbnxn_grid_t *gridj,
1835 t_nblist *nlist)
1837 int sci, cj4_ind_start, cj4_ind_end, cjr;
1838 int nri_max;
1839 int c_abs;
1840 int ind_i, ind_j, ai, aj;
1841 int nri;
1842 gmx_bool bFEP_i;
1843 real xi, yi, zi;
1844 const nbnxn_cj4_t *cj4;
1846 if (nbl_sci->cj4_ind_end == nbl_sci->cj4_ind_start)
1848 /* Empty list */
1849 return;
1852 sci = nbl_sci->sci;
1854 cj4_ind_start = nbl_sci->cj4_ind_start;
1855 cj4_ind_end = nbl_sci->cj4_ind_end;
1857 /* Here we process one super-cell, max #atoms na_sc, versus a list
1858 * cj4 entries, each with max c_nbnxnGpuJgroupSize cj's, each
1859 * of size na_cj atoms.
1860 * On the GPU we don't support energy groups (yet).
1861 * So for each of the na_sc i-atoms, we need max one FEP list
1862 * for each max_nrj_fep j-atoms.
1864 nri_max = nbl->na_sc*nbl->na_cj*(1 + ((cj4_ind_end - cj4_ind_start)*c_nbnxnGpuJgroupSize)/max_nrj_fep);
1865 if (nlist->nri + nri_max > nlist->maxnri)
1867 nlist->maxnri = over_alloc_large(nlist->nri + nri_max);
1868 reallocate_nblist(nlist);
1871 /* Loop over the atoms in the i super-cluster */
1872 for (int c = 0; c < c_gpuNumClusterPerCell; c++)
1874 c_abs = sci*c_gpuNumClusterPerCell + c;
1876 for (int i = 0; i < nbl->na_ci; i++)
1878 ind_i = c_abs*nbl->na_ci + i;
1879 ai = nbs->a[ind_i];
1880 if (ai >= 0)
1882 nri = nlist->nri;
1883 nlist->jindex[nri+1] = nlist->jindex[nri];
1884 nlist->iinr[nri] = ai;
1885 /* With GPUs, energy groups are not supported */
1886 nlist->gid[nri] = 0;
1887 nlist->shift[nri] = nbl_sci->shift & NBNXN_CI_SHIFT;
1889 bFEP_i = (gridi->fep[c_abs - gridi->cell0*c_gpuNumClusterPerCell] & (1 << i));
1891 xi = nbat->x[ind_i*nbat->xstride+XX] + shx;
1892 yi = nbat->x[ind_i*nbat->xstride+YY] + shy;
1893 zi = nbat->x[ind_i*nbat->xstride+ZZ] + shz;
1895 if ((nlist->nrj + cj4_ind_end - cj4_ind_start)*c_nbnxnGpuJgroupSize*nbl->na_cj > nlist->maxnrj)
1897 nlist->maxnrj = over_alloc_small((nlist->nrj + cj4_ind_end - cj4_ind_start)*c_nbnxnGpuJgroupSize*nbl->na_cj);
1898 srenew(nlist->jjnr, nlist->maxnrj);
1899 srenew(nlist->excl_fep, nlist->maxnrj);
1902 for (int cj4_ind = cj4_ind_start; cj4_ind < cj4_ind_end; cj4_ind++)
1904 cj4 = &nbl->cj4[cj4_ind];
1906 for (int gcj = 0; gcj < c_nbnxnGpuJgroupSize; gcj++)
1908 unsigned int fep_cj;
1910 if ((cj4->imei[0].imask & (1U << (gcj*c_gpuNumClusterPerCell + c))) == 0)
1912 /* Skip this ci for this cj */
1913 continue;
1916 cjr = cj4->cj[gcj] - gridj->cell0*c_gpuNumClusterPerCell;
1918 fep_cj = gridj->fep[cjr];
1920 if (bFEP_i || fep_cj != 0)
1922 for (int j = 0; j < nbl->na_cj; j++)
1924 /* Is this interaction perturbed and not excluded? */
1925 ind_j = (gridj->cell0*c_gpuNumClusterPerCell + cjr)*nbl->na_cj + j;
1926 aj = nbs->a[ind_j];
1927 if (aj >= 0 &&
1928 (bFEP_i || (fep_cj & (1 << j))) &&
1929 (!bDiagRemoved || ind_j >= ind_i))
1931 nbnxn_excl_t *excl;
1932 int excl_pair;
1933 unsigned int excl_bit;
1934 real dx, dy, dz;
1936 get_nbl_exclusions_1(nbl, cj4_ind, j>>2, &excl);
1938 excl_pair = a_mod_wj(j)*nbl->na_ci + i;
1939 excl_bit = (1U << (gcj*c_gpuNumClusterPerCell + c));
1941 dx = nbat->x[ind_j*nbat->xstride+XX] - xi;
1942 dy = nbat->x[ind_j*nbat->xstride+YY] - yi;
1943 dz = nbat->x[ind_j*nbat->xstride+ZZ] - zi;
1945 /* The unpruned GPU list has more than 2/3
1946 * of the atom pairs beyond rlist. Using
1947 * this list will cause a lot of overhead
1948 * in the CPU FEP kernels, especially
1949 * relative to the fast GPU kernels.
1950 * So we prune the FEP list here.
1952 if (dx*dx + dy*dy + dz*dz < rlist_fep2)
1954 if (nlist->nrj - nlist->jindex[nri] >= max_nrj_fep)
1956 fep_list_new_nri_copy(nlist);
1957 nri = nlist->nri;
1960 /* Add it to the FEP list */
1961 nlist->jjnr[nlist->nrj] = aj;
1962 nlist->excl_fep[nlist->nrj] = (excl->pair[excl_pair] & excl_bit) ? 1 : 0;
1963 nlist->nrj++;
1966 /* Exclude it from the normal list.
1967 * Note that the charge and LJ parameters have
1968 * been set to zero, but we need to avoid 0/0,
1969 * as perturbed atoms can be on top of each other.
1971 excl->pair[excl_pair] &= ~excl_bit;
1975 /* Note that we could mask out this pair in imask
1976 * if all i- and/or all j-particles are perturbed.
1977 * But since the perturbed pairs on the CPU will
1978 * take an order of magnitude more time, the GPU
1979 * will finish before the CPU and there is no gain.
1985 if (nlist->nrj > nlist->jindex[nri])
1987 /* Actually add this new, non-empty, list */
1988 nlist->nri++;
1989 nlist->jindex[nlist->nri] = nlist->nrj;
1996 /* Set all atom-pair exclusions from the topology stored in excl
1997 * as masks in the pair-list for i-super-cell entry nbl_sci
1999 static void set_sci_top_excls(const nbnxn_search_t nbs,
2000 nbnxn_pairlist_t *nbl,
2001 gmx_bool diagRemoved,
2002 int na_c_2log,
2003 const nbnxn_sci_t *nbl_sci,
2004 const t_blocka *excl)
2006 const int *cell;
2007 int na_c;
2008 int sci;
2009 int cj_ind_first, cj_ind_last;
2010 int cj_first, cj_last;
2011 int ndirect;
2012 int ai, aj, si, ge, se;
2013 int found, cj_ind_0, cj_ind_1, cj_ind_m;
2014 int cj_m;
2015 nbnxn_excl_t *nbl_excl;
2016 int inner_i, inner_e, w;
2018 cell = nbs->cell;
2020 na_c = nbl->na_ci;
2022 if (nbl_sci->cj4_ind_end == nbl_sci->cj4_ind_start)
2024 /* Empty list */
2025 return;
2028 sci = nbl_sci->sci;
2030 cj_ind_first = nbl_sci->cj4_ind_start*c_nbnxnGpuJgroupSize;
2031 cj_ind_last = nbl->work->cj_ind - 1;
2033 cj_first = nbl->cj4[nbl_sci->cj4_ind_start].cj[0];
2034 cj_last = nbl_cj(nbl, cj_ind_last);
2036 /* Determine how many contiguous j-clusters we have starting
2037 * from the first i-cluster. This number can be used to directly
2038 * calculate j-cluster indices for excluded atoms.
2040 ndirect = 0;
2041 while (cj_ind_first + ndirect <= cj_ind_last &&
2042 nbl_cj(nbl, cj_ind_first+ndirect) == sci*c_gpuNumClusterPerCell + ndirect)
2044 ndirect++;
2047 /* Loop over the atoms in the i super-cell */
2048 for (int i = 0; i < nbl->na_sc; i++)
2050 ai = nbs->a[sci*nbl->na_sc+i];
2051 if (ai >= 0)
2053 si = (i>>na_c_2log);
2055 /* Loop over the topology-based exclusions for this i-atom */
2056 for (int eind = excl->index[ai]; eind < excl->index[ai+1]; eind++)
2058 aj = excl->a[eind];
2060 if (aj == ai)
2062 /* The self exclusion are already set, save some time */
2063 continue;
2066 ge = cell[aj];
2068 /* Without shifts we only calculate interactions j>i
2069 * for one-way pair-lists.
2071 if (diagRemoved && ge <= sci*nbl->na_sc + i)
2073 continue;
2076 se = ge>>na_c_2log;
2077 /* Could the cluster se be in our list? */
2078 if (se >= cj_first && se <= cj_last)
2080 if (se < cj_first + ndirect)
2082 /* We can calculate cj_ind directly from se */
2083 found = cj_ind_first + se - cj_first;
2085 else
2087 /* Search for se using bisection */
2088 found = -1;
2089 cj_ind_0 = cj_ind_first + ndirect;
2090 cj_ind_1 = cj_ind_last + 1;
2091 while (found == -1 && cj_ind_0 < cj_ind_1)
2093 cj_ind_m = (cj_ind_0 + cj_ind_1)>>1;
2095 cj_m = nbl_cj(nbl, cj_ind_m);
2097 if (se == cj_m)
2099 found = cj_ind_m;
2101 else if (se < cj_m)
2103 cj_ind_1 = cj_ind_m;
2105 else
2107 cj_ind_0 = cj_ind_m + 1;
2112 if (found >= 0)
2114 inner_i = i - si*na_c;
2115 inner_e = ge - se*na_c;
2117 if (nbl_imask0(nbl, found) & (1U << (cj_mod_cj4(found)*c_gpuNumClusterPerCell + si)))
2119 w = (inner_e >> 2);
2121 get_nbl_exclusions_1(nbl, cj_to_cj4(found), w, &nbl_excl);
2123 nbl_excl->pair[a_mod_wj(inner_e)*nbl->na_ci+inner_i] &=
2124 ~(1U << (cj_mod_cj4(found)*c_gpuNumClusterPerCell + si));
2133 /* Reallocate the simple ci list for at least n entries */
2134 static void nb_realloc_ci(nbnxn_pairlist_t *nbl, int n)
2136 nbl->ci_nalloc = over_alloc_small(n);
2137 nbnxn_realloc_void((void **)&nbl->ci,
2138 nbl->nci*sizeof(*nbl->ci),
2139 nbl->ci_nalloc*sizeof(*nbl->ci),
2140 nbl->alloc, nbl->free);
2142 nbnxn_realloc_void((void **)&nbl->ciOuter,
2143 nbl->nci*sizeof(*nbl->ciOuter),
2144 nbl->ci_nalloc*sizeof(*nbl->ciOuter),
2145 nbl->alloc, nbl->free);
2148 /* Reallocate the super-cell sci list for at least n entries */
2149 static void nb_realloc_sci(nbnxn_pairlist_t *nbl, int n)
2151 nbl->sci_nalloc = over_alloc_small(n);
2152 nbnxn_realloc_void((void **)&nbl->sci,
2153 nbl->nsci*sizeof(*nbl->sci),
2154 nbl->sci_nalloc*sizeof(*nbl->sci),
2155 nbl->alloc, nbl->free);
2158 /* Make a new ci entry at index nbl->nci */
2159 static void new_ci_entry(nbnxn_pairlist_t *nbl, int ci, int shift, int flags)
2161 if (nbl->nci + 1 > nbl->ci_nalloc)
2163 nb_realloc_ci(nbl, nbl->nci+1);
2165 nbl->ci[nbl->nci].ci = ci;
2166 nbl->ci[nbl->nci].shift = shift;
2167 /* Store the interaction flags along with the shift */
2168 nbl->ci[nbl->nci].shift |= flags;
2169 nbl->ci[nbl->nci].cj_ind_start = nbl->ncj;
2170 nbl->ci[nbl->nci].cj_ind_end = nbl->ncj;
2173 /* Make a new sci entry at index nbl->nsci */
2174 static void new_sci_entry(nbnxn_pairlist_t *nbl, int sci, int shift)
2176 if (nbl->nsci + 1 > nbl->sci_nalloc)
2178 nb_realloc_sci(nbl, nbl->nsci+1);
2180 nbl->sci[nbl->nsci].sci = sci;
2181 nbl->sci[nbl->nsci].shift = shift;
2182 nbl->sci[nbl->nsci].cj4_ind_start = nbl->ncj4;
2183 nbl->sci[nbl->nsci].cj4_ind_end = nbl->ncj4;
2186 /* Sort the simple j-list cj on exclusions.
2187 * Entries with exclusions will all be sorted to the beginning of the list.
2189 static void sort_cj_excl(nbnxn_cj_t *cj, int ncj,
2190 nbnxn_list_work_t *work)
2192 int jnew;
2194 if (ncj > work->cj_nalloc)
2196 work->cj_nalloc = over_alloc_large(ncj);
2197 srenew(work->cj, work->cj_nalloc);
2200 /* Make a list of the j-cells involving exclusions */
2201 jnew = 0;
2202 for (int j = 0; j < ncj; j++)
2204 if (cj[j].excl != NBNXN_INTERACTION_MASK_ALL)
2206 work->cj[jnew++] = cj[j];
2209 /* Check if there are exclusions at all or not just the first entry */
2210 if (!((jnew == 0) ||
2211 (jnew == 1 && cj[0].excl != NBNXN_INTERACTION_MASK_ALL)))
2213 for (int j = 0; j < ncj; j++)
2215 if (cj[j].excl == NBNXN_INTERACTION_MASK_ALL)
2217 work->cj[jnew++] = cj[j];
2220 for (int j = 0; j < ncj; j++)
2222 cj[j] = work->cj[j];
2227 /* Close this simple list i entry */
2228 static void close_ci_entry_simple(nbnxn_pairlist_t *nbl)
2230 int jlen;
2232 /* All content of the new ci entry have already been filled correctly,
2233 * we only need to increase the count here (for non empty lists).
2235 jlen = nbl->ci[nbl->nci].cj_ind_end - nbl->ci[nbl->nci].cj_ind_start;
2236 if (jlen > 0)
2238 sort_cj_excl(nbl->cj+nbl->ci[nbl->nci].cj_ind_start, jlen, nbl->work);
2240 /* The counts below are used for non-bonded pair/flop counts
2241 * and should therefore match the available kernel setups.
2243 if (!(nbl->ci[nbl->nci].shift & NBNXN_CI_DO_COUL(0)))
2245 nbl->work->ncj_noq += jlen;
2247 else if ((nbl->ci[nbl->nci].shift & NBNXN_CI_HALF_LJ(0)) ||
2248 !(nbl->ci[nbl->nci].shift & NBNXN_CI_DO_LJ(0)))
2250 nbl->work->ncj_hlj += jlen;
2253 nbl->nci++;
2257 /* Split sci entry for load balancing on the GPU.
2258 * Splitting ensures we have enough lists to fully utilize the whole GPU.
2259 * With progBal we generate progressively smaller lists, which improves
2260 * load balancing. As we only know the current count on our own thread,
2261 * we will need to estimate the current total amount of i-entries.
2262 * As the lists get concatenated later, this estimate depends
2263 * both on nthread and our own thread index.
2265 static void split_sci_entry(nbnxn_pairlist_t *nbl,
2266 int nsp_target_av,
2267 gmx_bool progBal, float nsp_tot_est,
2268 int thread, int nthread)
2270 int nsp_max;
2271 int cj4_start, cj4_end, j4len;
2272 int sci;
2273 int nsp, nsp_sci, nsp_cj4, nsp_cj4_e, nsp_cj4_p;
2275 if (progBal)
2277 float nsp_est;
2279 /* Estimate the total numbers of ci's of the nblist combined
2280 * over all threads using the target number of ci's.
2282 nsp_est = (nsp_tot_est*thread)/nthread + nbl->nci_tot;
2284 /* The first ci blocks should be larger, to avoid overhead.
2285 * The last ci blocks should be smaller, to improve load balancing.
2286 * The factor 3/2 makes the first block 3/2 times the target average
2287 * and ensures that the total number of blocks end up equal to
2288 * that of equally sized blocks of size nsp_target_av.
2290 nsp_max = static_cast<int>(nsp_target_av*(nsp_tot_est*1.5/(nsp_est + nsp_tot_est)));
2292 else
2294 nsp_max = nsp_target_av;
2297 cj4_start = nbl->sci[nbl->nsci-1].cj4_ind_start;
2298 cj4_end = nbl->sci[nbl->nsci-1].cj4_ind_end;
2299 j4len = cj4_end - cj4_start;
2301 if (j4len > 1 && j4len*c_gpuNumClusterPerCell*c_nbnxnGpuJgroupSize > nsp_max)
2303 /* Remove the last ci entry and process the cj4's again */
2304 nbl->nsci -= 1;
2306 sci = nbl->nsci;
2307 nsp = 0;
2308 nsp_sci = 0;
2309 nsp_cj4_e = 0;
2310 nsp_cj4 = 0;
2311 for (int cj4 = cj4_start; cj4 < cj4_end; cj4++)
2313 nsp_cj4_p = nsp_cj4;
2314 /* Count the number of cluster pairs in this cj4 group */
2315 nsp_cj4 = 0;
2316 for (int p = 0; p < c_gpuNumClusterPerCell*c_nbnxnGpuJgroupSize; p++)
2318 nsp_cj4 += (nbl->cj4[cj4].imei[0].imask >> p) & 1;
2321 /* If adding the current cj4 with nsp_cj4 pairs get us further
2322 * away from our target nsp_max, split the list before this cj4.
2324 if (nsp > 0 && nsp_max - nsp < nsp + nsp_cj4 - nsp_max)
2326 /* Split the list at cj4 */
2327 nbl->sci[sci].cj4_ind_end = cj4;
2328 /* Create a new sci entry */
2329 sci++;
2330 nbl->nsci++;
2331 if (nbl->nsci+1 > nbl->sci_nalloc)
2333 nb_realloc_sci(nbl, nbl->nsci+1);
2335 nbl->sci[sci].sci = nbl->sci[nbl->nsci-1].sci;
2336 nbl->sci[sci].shift = nbl->sci[nbl->nsci-1].shift;
2337 nbl->sci[sci].cj4_ind_start = cj4;
2338 nsp_sci = nsp;
2339 nsp_cj4_e = nsp_cj4_p;
2340 nsp = 0;
2342 nsp += nsp_cj4;
2345 /* Put the remaining cj4's in the last sci entry */
2346 nbl->sci[sci].cj4_ind_end = cj4_end;
2348 /* Possibly balance out the last two sci's
2349 * by moving the last cj4 of the second last sci.
2351 if (nsp_sci - nsp_cj4_e >= nsp + nsp_cj4_e)
2353 nbl->sci[sci-1].cj4_ind_end--;
2354 nbl->sci[sci].cj4_ind_start--;
2357 nbl->nsci++;
2361 /* Clost this super/sub list i entry */
2362 static void close_ci_entry_supersub(nbnxn_pairlist_t *nbl,
2363 int nsp_max_av,
2364 gmx_bool progBal, float nsp_tot_est,
2365 int thread, int nthread)
2367 /* All content of the new ci entry have already been filled correctly,
2368 * we only need to increase the count here (for non empty lists).
2370 int j4len = nbl->sci[nbl->nsci].cj4_ind_end - nbl->sci[nbl->nsci].cj4_ind_start;
2371 if (j4len > 0)
2373 /* We can only have complete blocks of 4 j-entries in a list,
2374 * so round the count up before closing.
2376 nbl->ncj4 = (nbl->work->cj_ind + c_nbnxnGpuJgroupSize - 1)/c_nbnxnGpuJgroupSize;
2377 nbl->work->cj_ind = nbl->ncj4*c_nbnxnGpuJgroupSize;
2379 nbl->nsci++;
2381 if (nsp_max_av > 0)
2383 /* Measure the size of the new entry and potentially split it */
2384 split_sci_entry(nbl, nsp_max_av, progBal, nsp_tot_est,
2385 thread, nthread);
2390 /* Syncs the working array before adding another grid pair to the list */
2391 static void sync_work(nbnxn_pairlist_t *nbl)
2393 if (!nbl->bSimple)
2395 nbl->work->cj_ind = nbl->ncj4*c_nbnxnGpuJgroupSize;
2396 nbl->work->cj4_init = nbl->ncj4;
2400 /* Clears an nbnxn_pairlist_t data structure */
2401 static void clear_pairlist(nbnxn_pairlist_t *nbl)
2403 nbl->nci = 0;
2404 nbl->nsci = 0;
2405 nbl->ncj = 0;
2406 nbl->ncjInUse = 0;
2407 nbl->ncj4 = 0;
2408 nbl->nci_tot = 0;
2409 nbl->nciOuter = -1;
2410 nbl->nexcl = 1;
2412 nbl->work->ncj_noq = 0;
2413 nbl->work->ncj_hlj = 0;
2416 /* Clears a group scheme pair list */
2417 static void clear_pairlist_fep(t_nblist *nl)
2419 nl->nri = 0;
2420 nl->nrj = 0;
2421 if (nl->jindex == nullptr)
2423 snew(nl->jindex, 1);
2425 nl->jindex[0] = 0;
2428 /* Sets a simple list i-cell bounding box, including PBC shift */
2429 static gmx_inline void set_icell_bb_simple(const nbnxn_bb_t *bb, int ci,
2430 real shx, real shy, real shz,
2431 nbnxn_bb_t *bb_ci)
2433 bb_ci->lower[BB_X] = bb[ci].lower[BB_X] + shx;
2434 bb_ci->lower[BB_Y] = bb[ci].lower[BB_Y] + shy;
2435 bb_ci->lower[BB_Z] = bb[ci].lower[BB_Z] + shz;
2436 bb_ci->upper[BB_X] = bb[ci].upper[BB_X] + shx;
2437 bb_ci->upper[BB_Y] = bb[ci].upper[BB_Y] + shy;
2438 bb_ci->upper[BB_Z] = bb[ci].upper[BB_Z] + shz;
2441 #if NBNXN_BBXXXX
2442 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
2443 static void set_icell_bbxxxx_supersub(const float *bb, int ci,
2444 real shx, real shy, real shz,
2445 float *bb_ci)
2447 int ia = ci*(c_gpuNumClusterPerCell >> STRIDE_PBB_2LOG)*NNBSBB_XXXX;
2448 for (int m = 0; m < (c_gpuNumClusterPerCell >> STRIDE_PBB_2LOG)*NNBSBB_XXXX; m += NNBSBB_XXXX)
2450 for (int i = 0; i < STRIDE_PBB; i++)
2452 bb_ci[m+0*STRIDE_PBB+i] = bb[ia+m+0*STRIDE_PBB+i] + shx;
2453 bb_ci[m+1*STRIDE_PBB+i] = bb[ia+m+1*STRIDE_PBB+i] + shy;
2454 bb_ci[m+2*STRIDE_PBB+i] = bb[ia+m+2*STRIDE_PBB+i] + shz;
2455 bb_ci[m+3*STRIDE_PBB+i] = bb[ia+m+3*STRIDE_PBB+i] + shx;
2456 bb_ci[m+4*STRIDE_PBB+i] = bb[ia+m+4*STRIDE_PBB+i] + shy;
2457 bb_ci[m+5*STRIDE_PBB+i] = bb[ia+m+5*STRIDE_PBB+i] + shz;
2461 #endif
2463 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
2464 gmx_unused static void set_icell_bb_supersub(const nbnxn_bb_t *bb, int ci,
2465 real shx, real shy, real shz,
2466 nbnxn_bb_t *bb_ci)
2468 for (int i = 0; i < c_gpuNumClusterPerCell; i++)
2470 set_icell_bb_simple(bb, ci*c_gpuNumClusterPerCell+i,
2471 shx, shy, shz,
2472 &bb_ci[i]);
2476 /* Copies PBC shifted i-cell atom coordinates x,y,z to working array */
2477 static void icell_set_x_simple(int ci,
2478 real shx, real shy, real shz,
2479 int stride, const real *x,
2480 nbnxn_list_work_t *work)
2482 int ia = ci*NBNXN_CPU_CLUSTER_I_SIZE;
2484 for (int i = 0; i < NBNXN_CPU_CLUSTER_I_SIZE; i++)
2486 work->x_ci[i*STRIDE_XYZ+XX] = x[(ia+i)*stride+XX] + shx;
2487 work->x_ci[i*STRIDE_XYZ+YY] = x[(ia+i)*stride+YY] + shy;
2488 work->x_ci[i*STRIDE_XYZ+ZZ] = x[(ia+i)*stride+ZZ] + shz;
2492 /* Copies PBC shifted super-cell atom coordinates x,y,z to working array */
2493 static void icell_set_x_supersub(int ci,
2494 real shx, real shy, real shz,
2495 int stride, const real *x,
2496 nbnxn_list_work_t *work)
2498 #if !GMX_SIMD4_HAVE_REAL
2500 real * x_ci = work->x_ci;
2502 int ia = ci*c_gpuNumClusterPerCell*c_nbnxnGpuClusterSize;
2503 for (int i = 0; i < c_gpuNumClusterPerCell*c_nbnxnGpuClusterSize; i++)
2505 x_ci[i*DIM + XX] = x[(ia+i)*stride + XX] + shx;
2506 x_ci[i*DIM + YY] = x[(ia+i)*stride + YY] + shy;
2507 x_ci[i*DIM + ZZ] = x[(ia+i)*stride + ZZ] + shz;
2510 #else /* !GMX_SIMD4_HAVE_REAL */
2512 real * x_ci = work->x_ci_simd;
2514 for (int si = 0; si < c_gpuNumClusterPerCell; si++)
2516 for (int i = 0; i < c_nbnxnGpuClusterSize; i += GMX_SIMD4_WIDTH)
2518 int io = si*c_nbnxnGpuClusterSize + i;
2519 int ia = ci*c_gpuNumClusterPerCell*c_nbnxnGpuClusterSize + io;
2520 for (int j = 0; j < GMX_SIMD4_WIDTH; j++)
2522 x_ci[io*DIM + j + XX*GMX_SIMD4_WIDTH] = x[(ia + j)*stride + XX] + shx;
2523 x_ci[io*DIM + j + YY*GMX_SIMD4_WIDTH] = x[(ia + j)*stride + YY] + shy;
2524 x_ci[io*DIM + j + ZZ*GMX_SIMD4_WIDTH] = x[(ia + j)*stride + ZZ] + shz;
2529 #endif /* !GMX_SIMD4_HAVE_REAL */
2532 static real minimum_subgrid_size_xy(const nbnxn_grid_t *grid)
2534 if (grid->bSimple)
2536 return std::min(grid->sx, grid->sy);
2538 else
2540 return std::min(grid->sx/c_gpuNumClusterPerCellX,
2541 grid->sy/c_gpuNumClusterPerCellY);
2545 static real effective_buffer_1x1_vs_MxN(const nbnxn_grid_t *gridi,
2546 const nbnxn_grid_t *gridj)
2548 const real eff_1x1_buffer_fac_overest = 0.1;
2550 /* Determine an atom-pair list cut-off buffer size for atom pairs,
2551 * to be added to rlist (including buffer) used for MxN.
2552 * This is for converting an MxN list to a 1x1 list. This means we can't
2553 * use the normal buffer estimate, as we have an MxN list in which
2554 * some atom pairs beyond rlist are missing. We want to capture
2555 * the beneficial effect of buffering by extra pairs just outside rlist,
2556 * while removing the useless pairs that are further away from rlist.
2557 * (Also the buffer could have been set manually not using the estimate.)
2558 * This buffer size is an overestimate.
2559 * We add 10% of the smallest grid sub-cell dimensions.
2560 * Note that the z-size differs per cell and we don't use this,
2561 * so we overestimate.
2562 * With PME, the 10% value gives a buffer that is somewhat larger
2563 * than the effective buffer with a tolerance of 0.005 kJ/mol/ps.
2564 * Smaller tolerances or using RF lead to a smaller effective buffer,
2565 * so 10% gives a safe overestimate.
2567 return eff_1x1_buffer_fac_overest*(minimum_subgrid_size_xy(gridi) +
2568 minimum_subgrid_size_xy(gridj));
2571 /* Clusters at the cut-off only increase rlist by 60% of their size */
2572 static real nbnxn_rlist_inc_outside_fac = 0.6;
2574 /* Due to the cluster size the effective pair-list is longer than
2575 * that of a simple atom pair-list. This function gives the extra distance.
2577 real nbnxn_get_rlist_effective_inc(int cluster_size_j, real atom_density)
2579 int cluster_size_i;
2580 real vol_inc_i, vol_inc_j;
2582 /* We should get this from the setup, but currently it's the same for
2583 * all setups, including GPUs.
2585 cluster_size_i = NBNXN_CPU_CLUSTER_I_SIZE;
2587 vol_inc_i = (cluster_size_i - 1)/atom_density;
2588 vol_inc_j = (cluster_size_j - 1)/atom_density;
2590 return nbnxn_rlist_inc_outside_fac*std::cbrt(vol_inc_i + vol_inc_j);
2593 /* Estimates the interaction volume^2 for non-local interactions */
2594 static real nonlocal_vol2(const struct gmx_domdec_zones_t *zones, rvec ls, real r)
2596 real cl, ca, za;
2597 real vold_est;
2598 real vol2_est_tot;
2600 vol2_est_tot = 0;
2602 /* Here we simply add up the volumes of 1, 2 or 3 1D decomposition
2603 * not home interaction volume^2. As these volumes are not additive,
2604 * this is an overestimate, but it would only be significant in the limit
2605 * of small cells, where we anyhow need to split the lists into
2606 * as small parts as possible.
2609 for (int z = 0; z < zones->n; z++)
2611 if (zones->shift[z][XX] + zones->shift[z][YY] + zones->shift[z][ZZ] == 1)
2613 cl = 0;
2614 ca = 1;
2615 za = 1;
2616 for (int d = 0; d < DIM; d++)
2618 if (zones->shift[z][d] == 0)
2620 cl += 0.5*ls[d];
2621 ca *= ls[d];
2622 za *= zones->size[z].x1[d] - zones->size[z].x0[d];
2626 /* 4 octants of a sphere */
2627 vold_est = 0.25*M_PI*r*r*r*r;
2628 /* 4 quarter pie slices on the edges */
2629 vold_est += 4*cl*M_PI/6.0*r*r*r;
2630 /* One rectangular volume on a face */
2631 vold_est += ca*0.5*r*r;
2633 vol2_est_tot += vold_est*za;
2637 return vol2_est_tot;
2640 /* Estimates the average size of a full j-list for super/sub setup */
2641 static void get_nsubpair_target(const nbnxn_search_t nbs,
2642 int iloc,
2643 real rlist,
2644 int min_ci_balanced,
2645 int *nsubpair_target,
2646 float *nsubpair_tot_est)
2648 /* The target value of 36 seems to be the optimum for Kepler.
2649 * Maxwell is less sensitive to the exact value.
2651 const int nsubpair_target_min = 36;
2652 const nbnxn_grid_t *grid;
2653 rvec ls;
2654 real r_eff_sup, vol_est, nsp_est, nsp_est_nl;
2656 grid = &nbs->grid[0];
2658 /* We don't need to balance list sizes if:
2659 * - We didn't request balancing.
2660 * - The number of grid cells >= the number of lists requested,
2661 * since we will always generate at least #cells lists.
2662 * - We don't have any cells, since then there won't be any lists.
2664 if (min_ci_balanced <= 0 || grid->nc >= min_ci_balanced || grid->nc == 0)
2666 /* nsubpair_target==0 signals no balancing */
2667 *nsubpair_target = 0;
2668 *nsubpair_tot_est = 0;
2670 return;
2673 ls[XX] = (grid->c1[XX] - grid->c0[XX])/(grid->ncx*c_gpuNumClusterPerCellX);
2674 ls[YY] = (grid->c1[YY] - grid->c0[YY])/(grid->ncy*c_gpuNumClusterPerCellY);
2675 ls[ZZ] = grid->na_c/(grid->atom_density*ls[XX]*ls[YY]);
2677 /* The average length of the diagonal of a sub cell */
2678 real diagonal = std::sqrt(ls[XX]*ls[XX] + ls[YY]*ls[YY] + ls[ZZ]*ls[ZZ]);
2680 /* The formulas below are a heuristic estimate of the average nsj per si*/
2681 r_eff_sup = rlist + nbnxn_rlist_inc_outside_fac*gmx::square((grid->na_c - 1.0)/grid->na_c)*0.5*diagonal;
2683 if (!nbs->DomDec || nbs->zones->n == 1)
2685 nsp_est_nl = 0;
2687 else
2689 nsp_est_nl =
2690 gmx::square(grid->atom_density/grid->na_c)*
2691 nonlocal_vol2(nbs->zones, ls, r_eff_sup);
2694 if (LOCAL_I(iloc))
2696 /* Sub-cell interacts with itself */
2697 vol_est = ls[XX]*ls[YY]*ls[ZZ];
2698 /* 6/2 rectangular volume on the faces */
2699 vol_est += (ls[XX]*ls[YY] + ls[XX]*ls[ZZ] + ls[YY]*ls[ZZ])*r_eff_sup;
2700 /* 12/2 quarter pie slices on the edges */
2701 vol_est += 2*(ls[XX] + ls[YY] + ls[ZZ])*0.25*M_PI*gmx::square(r_eff_sup);
2702 /* 4 octants of a sphere */
2703 vol_est += 0.5*4.0/3.0*M_PI*gmx::power3(r_eff_sup);
2705 /* Estimate the number of cluster pairs as the local number of
2706 * clusters times the volume they interact with times the density.
2708 nsp_est = grid->nsubc_tot*vol_est*grid->atom_density/grid->na_c;
2710 /* Subtract the non-local pair count */
2711 nsp_est -= nsp_est_nl;
2713 /* For small cut-offs nsp_est will be an underesimate.
2714 * With DD nsp_est_nl is an overestimate so nsp_est can get negative.
2715 * So to avoid too small or negative nsp_est we set a minimum of
2716 * all cells interacting with all 3^3 direct neighbors (3^3-1)/2+1=14.
2717 * This might be a slight overestimate for small non-periodic groups of
2718 * atoms as will occur for a local domain with DD, but for small
2719 * groups of atoms we'll anyhow be limited by nsubpair_target_min,
2720 * so this overestimation will not matter.
2722 nsp_est = std::max(nsp_est, grid->nsubc_tot*static_cast<real>(14));
2724 if (debug)
2726 fprintf(debug, "nsp_est local %5.1f non-local %5.1f\n",
2727 nsp_est, nsp_est_nl);
2730 else
2732 nsp_est = nsp_est_nl;
2735 /* Thus the (average) maximum j-list size should be as follows.
2736 * Since there is overhead, we shouldn't make the lists too small
2737 * (and we can't chop up j-groups) so we use a minimum target size of 36.
2739 *nsubpair_target = std::max(nsubpair_target_min,
2740 static_cast<int>(nsp_est/min_ci_balanced + 0.5));
2741 *nsubpair_tot_est = static_cast<int>(nsp_est);
2743 if (debug)
2745 fprintf(debug, "nbl nsp estimate %.1f, nsubpair_target %d\n",
2746 nsp_est, *nsubpair_target);
2750 /* Debug list print function */
2751 static void print_nblist_ci_cj(FILE *fp, const nbnxn_pairlist_t *nbl)
2753 for (int i = 0; i < nbl->nci; i++)
2755 fprintf(fp, "ci %4d shift %2d ncj %3d\n",
2756 nbl->ci[i].ci, nbl->ci[i].shift,
2757 nbl->ci[i].cj_ind_end - nbl->ci[i].cj_ind_start);
2759 for (int j = nbl->ci[i].cj_ind_start; j < nbl->ci[i].cj_ind_end; j++)
2761 fprintf(fp, " cj %5d imask %x\n",
2762 nbl->cj[j].cj,
2763 nbl->cj[j].excl);
2768 /* Debug list print function */
2769 static void print_nblist_sci_cj(FILE *fp, const nbnxn_pairlist_t *nbl)
2771 for (int i = 0; i < nbl->nsci; i++)
2773 fprintf(fp, "ci %4d shift %2d ncj4 %2d\n",
2774 nbl->sci[i].sci, nbl->sci[i].shift,
2775 nbl->sci[i].cj4_ind_end - nbl->sci[i].cj4_ind_start);
2777 int ncp = 0;
2778 for (int j4 = nbl->sci[i].cj4_ind_start; j4 < nbl->sci[i].cj4_ind_end; j4++)
2780 for (int j = 0; j < c_nbnxnGpuJgroupSize; j++)
2782 fprintf(fp, " sj %5d imask %x\n",
2783 nbl->cj4[j4].cj[j],
2784 nbl->cj4[j4].imei[0].imask);
2785 for (int si = 0; si < c_gpuNumClusterPerCell; si++)
2787 if (nbl->cj4[j4].imei[0].imask & (1U << (j*c_gpuNumClusterPerCell + si)))
2789 ncp++;
2794 fprintf(fp, "ci %4d shift %2d ncj4 %2d ncp %3d\n",
2795 nbl->sci[i].sci, nbl->sci[i].shift,
2796 nbl->sci[i].cj4_ind_end - nbl->sci[i].cj4_ind_start,
2797 ncp);
2801 /* Combine pair lists *nbl generated on multiple threads nblc */
2802 static void combine_nblists(int nnbl, nbnxn_pairlist_t **nbl,
2803 nbnxn_pairlist_t *nblc)
2805 int nsci, ncj4, nexcl;
2807 if (nblc->bSimple)
2809 gmx_incons("combine_nblists does not support simple lists");
2812 nsci = nblc->nsci;
2813 ncj4 = nblc->ncj4;
2814 nexcl = nblc->nexcl;
2815 for (int i = 0; i < nnbl; i++)
2817 nsci += nbl[i]->nsci;
2818 ncj4 += nbl[i]->ncj4;
2819 nexcl += nbl[i]->nexcl;
2822 if (nsci > nblc->sci_nalloc)
2824 nb_realloc_sci(nblc, nsci);
2826 if (ncj4 > nblc->cj4_nalloc)
2828 nblc->cj4_nalloc = over_alloc_small(ncj4);
2829 nbnxn_realloc_void((void **)&nblc->cj4,
2830 nblc->ncj4*sizeof(*nblc->cj4),
2831 nblc->cj4_nalloc*sizeof(*nblc->cj4),
2832 nblc->alloc, nblc->free);
2834 if (nexcl > nblc->excl_nalloc)
2836 nblc->excl_nalloc = over_alloc_small(nexcl);
2837 nbnxn_realloc_void((void **)&nblc->excl,
2838 nblc->nexcl*sizeof(*nblc->excl),
2839 nblc->excl_nalloc*sizeof(*nblc->excl),
2840 nblc->alloc, nblc->free);
2843 /* Each thread should copy its own data to the combined arrays,
2844 * as otherwise data will go back and forth between different caches.
2846 #if GMX_OPENMP && !(defined __clang_analyzer__)
2847 // cppcheck-suppress unreadVariable
2848 int nthreads = gmx_omp_nthreads_get(emntPairsearch);
2849 #endif
2851 #pragma omp parallel for num_threads(nthreads) schedule(static)
2852 for (int n = 0; n < nnbl; n++)
2856 int sci_offset;
2857 int cj4_offset;
2858 int excl_offset;
2859 const nbnxn_pairlist_t *nbli;
2861 /* Determine the offset in the combined data for our thread */
2862 sci_offset = nblc->nsci;
2863 cj4_offset = nblc->ncj4;
2864 excl_offset = nblc->nexcl;
2866 for (int i = 0; i < n; i++)
2868 sci_offset += nbl[i]->nsci;
2869 cj4_offset += nbl[i]->ncj4;
2870 excl_offset += nbl[i]->nexcl;
2873 nbli = nbl[n];
2875 for (int i = 0; i < nbli->nsci; i++)
2877 nblc->sci[sci_offset+i] = nbli->sci[i];
2878 nblc->sci[sci_offset+i].cj4_ind_start += cj4_offset;
2879 nblc->sci[sci_offset+i].cj4_ind_end += cj4_offset;
2882 for (int j4 = 0; j4 < nbli->ncj4; j4++)
2884 nblc->cj4[cj4_offset+j4] = nbli->cj4[j4];
2885 nblc->cj4[cj4_offset+j4].imei[0].excl_ind += excl_offset;
2886 nblc->cj4[cj4_offset+j4].imei[1].excl_ind += excl_offset;
2889 for (int j4 = 0; j4 < nbli->nexcl; j4++)
2891 nblc->excl[excl_offset+j4] = nbli->excl[j4];
2894 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
2897 for (int n = 0; n < nnbl; n++)
2899 nblc->nsci += nbl[n]->nsci;
2900 nblc->ncj4 += nbl[n]->ncj4;
2901 nblc->nci_tot += nbl[n]->nci_tot;
2902 nblc->nexcl += nbl[n]->nexcl;
2906 static void balance_fep_lists(const nbnxn_search_t nbs,
2907 nbnxn_pairlist_set_t *nbl_lists)
2909 int nnbl;
2910 int nri_tot, nrj_tot, nrj_target;
2911 int th_dest;
2912 t_nblist *nbld;
2914 nnbl = nbl_lists->nnbl;
2916 if (nnbl == 1)
2918 /* Nothing to balance */
2919 return;
2922 /* Count the total i-lists and pairs */
2923 nri_tot = 0;
2924 nrj_tot = 0;
2925 for (int th = 0; th < nnbl; th++)
2927 nri_tot += nbl_lists->nbl_fep[th]->nri;
2928 nrj_tot += nbl_lists->nbl_fep[th]->nrj;
2931 nrj_target = (nrj_tot + nnbl - 1)/nnbl;
2933 assert(gmx_omp_nthreads_get(emntNonbonded) == nnbl);
2935 #pragma omp parallel for schedule(static) num_threads(nnbl)
2936 for (int th = 0; th < nnbl; th++)
2940 t_nblist *nbl;
2942 nbl = nbs->work[th].nbl_fep;
2944 /* Note that here we allocate for the total size, instead of
2945 * a per-thread esimate (which is hard to obtain).
2947 if (nri_tot > nbl->maxnri)
2949 nbl->maxnri = over_alloc_large(nri_tot);
2950 reallocate_nblist(nbl);
2952 if (nri_tot > nbl->maxnri || nrj_tot > nbl->maxnrj)
2954 nbl->maxnrj = over_alloc_small(nrj_tot);
2955 srenew(nbl->jjnr, nbl->maxnrj);
2956 srenew(nbl->excl_fep, nbl->maxnrj);
2959 clear_pairlist_fep(nbl);
2961 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
2964 /* Loop over the source lists and assign and copy i-entries */
2965 th_dest = 0;
2966 nbld = nbs->work[th_dest].nbl_fep;
2967 for (int th = 0; th < nnbl; th++)
2969 t_nblist *nbls;
2971 nbls = nbl_lists->nbl_fep[th];
2973 for (int i = 0; i < nbls->nri; i++)
2975 int nrj;
2977 /* The number of pairs in this i-entry */
2978 nrj = nbls->jindex[i+1] - nbls->jindex[i];
2980 /* Decide if list th_dest is too large and we should procede
2981 * to the next destination list.
2983 if (th_dest+1 < nnbl && nbld->nrj > 0 &&
2984 nbld->nrj + nrj - nrj_target > nrj_target - nbld->nrj)
2986 th_dest++;
2987 nbld = nbs->work[th_dest].nbl_fep;
2990 nbld->iinr[nbld->nri] = nbls->iinr[i];
2991 nbld->gid[nbld->nri] = nbls->gid[i];
2992 nbld->shift[nbld->nri] = nbls->shift[i];
2994 for (int j = nbls->jindex[i]; j < nbls->jindex[i+1]; j++)
2996 nbld->jjnr[nbld->nrj] = nbls->jjnr[j];
2997 nbld->excl_fep[nbld->nrj] = nbls->excl_fep[j];
2998 nbld->nrj++;
3000 nbld->nri++;
3001 nbld->jindex[nbld->nri] = nbld->nrj;
3005 /* Swap the list pointers */
3006 for (int th = 0; th < nnbl; th++)
3008 t_nblist *nbl_tmp;
3010 nbl_tmp = nbl_lists->nbl_fep[th];
3011 nbl_lists->nbl_fep[th] = nbs->work[th].nbl_fep;
3012 nbs->work[th].nbl_fep = nbl_tmp;
3014 if (debug)
3016 fprintf(debug, "nbl_fep[%d] nri %4d nrj %4d\n",
3018 nbl_lists->nbl_fep[th]->nri,
3019 nbl_lists->nbl_fep[th]->nrj);
3024 /* Returns the next ci to be processes by our thread */
3025 static gmx_bool next_ci(const nbnxn_grid_t *grid,
3026 int nth, int ci_block,
3027 int *ci_x, int *ci_y,
3028 int *ci_b, int *ci)
3030 (*ci_b)++;
3031 (*ci)++;
3033 if (*ci_b == ci_block)
3035 /* Jump to the next block assigned to this task */
3036 *ci += (nth - 1)*ci_block;
3037 *ci_b = 0;
3040 if (*ci >= grid->nc)
3042 return FALSE;
3045 while (*ci >= grid->cxy_ind[*ci_x*grid->ncy + *ci_y + 1])
3047 *ci_y += 1;
3048 if (*ci_y == grid->ncy)
3050 *ci_x += 1;
3051 *ci_y = 0;
3055 return TRUE;
3058 /* Returns the distance^2 for which we put cell pairs in the list
3059 * without checking atom pair distances. This is usually < rlist^2.
3061 static float boundingbox_only_distance2(const nbnxn_grid_t *gridi,
3062 const nbnxn_grid_t *gridj,
3063 real rlist,
3064 gmx_bool simple)
3066 /* If the distance between two sub-cell bounding boxes is less
3067 * than this distance, do not check the distance between
3068 * all particle pairs in the sub-cell, since then it is likely
3069 * that the box pair has atom pairs within the cut-off.
3070 * We use the nblist cut-off minus 0.5 times the average x/y diagonal
3071 * spacing of the sub-cells. Around 40% of the checked pairs are pruned.
3072 * Using more than 0.5 gains at most 0.5%.
3073 * If forces are calculated more than twice, the performance gain
3074 * in the force calculation outweighs the cost of checking.
3075 * Note that with subcell lists, the atom-pair distance check
3076 * is only performed when only 1 out of 8 sub-cells in within range,
3077 * this is because the GPU is much faster than the cpu.
3079 real bbx, bby;
3080 real rbb2;
3082 bbx = 0.5*(gridi->sx + gridj->sx);
3083 bby = 0.5*(gridi->sy + gridj->sy);
3084 if (!simple)
3086 bbx /= c_gpuNumClusterPerCellX;
3087 bby /= c_gpuNumClusterPerCellY;
3090 rbb2 = std::max(0.0, rlist - 0.5*std::sqrt(bbx*bbx + bby*bby));
3091 rbb2 = rbb2 * rbb2;
3093 #if !GMX_DOUBLE
3094 return rbb2;
3095 #else
3096 return (float)((1+GMX_FLOAT_EPS)*rbb2);
3097 #endif
3100 static int get_ci_block_size(const nbnxn_grid_t *gridi,
3101 gmx_bool bDomDec, int nth)
3103 const int ci_block_enum = 5;
3104 const int ci_block_denom = 11;
3105 const int ci_block_min_atoms = 16;
3106 int ci_block;
3108 /* Here we decide how to distribute the blocks over the threads.
3109 * We use prime numbers to try to avoid that the grid size becomes
3110 * a multiple of the number of threads, which would lead to some
3111 * threads getting "inner" pairs and others getting boundary pairs,
3112 * which in turns will lead to load imbalance between threads.
3113 * Set the block size as 5/11/ntask times the average number of cells
3114 * in a y,z slab. This should ensure a quite uniform distribution
3115 * of the grid parts of the different thread along all three grid
3116 * zone boundaries with 3D domain decomposition. At the same time
3117 * the blocks will not become too small.
3119 ci_block = (gridi->nc*ci_block_enum)/(ci_block_denom*gridi->ncx*nth);
3121 /* Ensure the blocks are not too small: avoids cache invalidation */
3122 if (ci_block*gridi->na_sc < ci_block_min_atoms)
3124 ci_block = (ci_block_min_atoms + gridi->na_sc - 1)/gridi->na_sc;
3127 /* Without domain decomposition
3128 * or with less than 3 blocks per task, divide in nth blocks.
3130 if (!bDomDec || nth*3*ci_block > gridi->nc)
3132 ci_block = (gridi->nc + nth - 1)/nth;
3135 if (ci_block > 1 && (nth - 1)*ci_block >= gridi->nc)
3137 /* Some threads have no work. Although reducing the block size
3138 * does not decrease the block count on the first few threads,
3139 * with GPUs better mixing of "upper" cells that have more empty
3140 * clusters results in a somewhat lower max load over all threads.
3141 * Without GPUs the regime of so few atoms per thread is less
3142 * performance relevant, but with 8-wide SIMD the same reasoning
3143 * applies, since the pair list uses 4 i-atom "sub-clusters".
3145 ci_block--;
3148 return ci_block;
3151 /* Returns the number of bits to right-shift a cluster index to obtain
3152 * the corresponding force buffer flag index.
3154 static int getBufferFlagShift(int numAtomsPerCluster)
3156 int bufferFlagShift = 0;
3157 while ((numAtomsPerCluster << bufferFlagShift) < NBNXN_BUFFERFLAG_SIZE)
3159 bufferFlagShift++;
3162 return bufferFlagShift;
3165 /* Generates the part of pair-list nbl assigned to our thread */
3166 static void nbnxn_make_pairlist_part(const nbnxn_search_t nbs,
3167 const nbnxn_grid_t *gridi,
3168 const nbnxn_grid_t *gridj,
3169 nbnxn_search_work_t *work,
3170 const nbnxn_atomdata_t *nbat,
3171 const t_blocka *excl,
3172 real rlist,
3173 int nb_kernel_type,
3174 int ci_block,
3175 gmx_bool bFBufferFlag,
3176 int nsubpair_max,
3177 gmx_bool progBal,
3178 float nsubpair_tot_est,
3179 int th, int nth,
3180 nbnxn_pairlist_t *nbl,
3181 t_nblist *nbl_fep)
3183 int na_cj_2log;
3184 matrix box;
3185 real rlist2, rl_fep2 = 0;
3186 float rbb2;
3187 int ci_b, ci, ci_x, ci_y, ci_xy, cj;
3188 ivec shp;
3189 int shift;
3190 real shx, shy, shz;
3191 int cell0_i;
3192 const nbnxn_bb_t *bb_i = nullptr;
3193 #if NBNXN_BBXXXX
3194 const float *pbb_i = nullptr;
3195 #endif
3196 const float *bbcz_i, *bbcz_j;
3197 const int *flags_i;
3198 real bx0, bx1, by0, by1, bz0, bz1;
3199 real bz1_frac;
3200 real d2cx, d2z, d2z_cx, d2z_cy, d2zx, d2zxy, d2xy;
3201 int cxf, cxl, cyf, cyf_x, cyl;
3202 int numDistanceChecks;
3203 int gridi_flag_shift = 0, gridj_flag_shift = 0;
3204 gmx_bitmask_t *gridj_flag = nullptr;
3205 int ncj_old_i, ncj_old_j;
3207 nbs_cycle_start(&work->cc[enbsCCsearch]);
3209 if (gridj->bSimple != nbl->bSimple)
3211 gmx_incons("Grid incompatible with pair-list");
3214 sync_work(nbl);
3215 nbl->na_sc = gridj->na_sc;
3216 nbl->na_ci = gridj->na_c;
3217 nbl->na_cj = nbnxn_kernel_to_cluster_j_size(nb_kernel_type);
3218 na_cj_2log = get_2log(nbl->na_cj);
3220 nbl->rlist = rlist;
3222 if (bFBufferFlag)
3224 /* Determine conversion of clusters to flag blocks */
3225 gridi_flag_shift = getBufferFlagShift(nbl->na_ci);
3226 gridj_flag_shift = getBufferFlagShift(nbl->na_cj);
3228 gridj_flag = work->buffer_flags.flag;
3231 copy_mat(nbs->box, box);
3233 rlist2 = nbl->rlist*nbl->rlist;
3235 if (nbs->bFEP && !nbl->bSimple)
3237 /* Determine an atom-pair list cut-off distance for FEP atom pairs.
3238 * We should not simply use rlist, since then we would not have
3239 * the small, effective buffering of the NxN lists.
3240 * The buffer is on overestimate, but the resulting cost for pairs
3241 * beyond rlist is neglible compared to the FEP pairs within rlist.
3243 rl_fep2 = nbl->rlist + effective_buffer_1x1_vs_MxN(gridi, gridj);
3245 if (debug)
3247 fprintf(debug, "nbl_fep atom-pair rlist %f\n", rl_fep2);
3249 rl_fep2 = rl_fep2*rl_fep2;
3252 rbb2 = boundingbox_only_distance2(gridi, gridj, nbl->rlist, nbl->bSimple);
3254 if (debug)
3256 fprintf(debug, "nbl bounding box only distance %f\n", std::sqrt(rbb2));
3259 /* Set the shift range */
3260 for (int d = 0; d < DIM; d++)
3262 /* Check if we need periodicity shifts.
3263 * Without PBC or with domain decomposition we don't need them.
3265 if (d >= ePBC2npbcdim(nbs->ePBC) || nbs->dd_dim[d])
3267 shp[d] = 0;
3269 else
3271 if (d == XX &&
3272 box[XX][XX] - fabs(box[YY][XX]) - fabs(box[ZZ][XX]) < std::sqrt(rlist2))
3274 shp[d] = 2;
3276 else
3278 shp[d] = 1;
3283 #if NBNXN_BBXXXX
3284 if (gridi->bSimple)
3286 bb_i = gridi->bb;
3288 else
3290 pbb_i = gridi->pbb;
3292 #else
3293 /* We use the normal bounding box format for both grid types */
3294 bb_i = gridi->bb;
3295 #endif
3296 bbcz_i = gridi->bbcz;
3297 flags_i = gridi->flags;
3298 cell0_i = gridi->cell0;
3300 bbcz_j = gridj->bbcz;
3302 if (debug)
3304 fprintf(debug, "nbl nc_i %d col.av. %.1f ci_block %d\n",
3305 gridi->nc, gridi->nc/(double)(gridi->ncx*gridi->ncy), ci_block);
3308 numDistanceChecks = 0;
3310 /* Initially ci_b and ci to 1 before where we want them to start,
3311 * as they will both be incremented in next_ci.
3313 ci_b = -1;
3314 ci = th*ci_block - 1;
3315 ci_x = 0;
3316 ci_y = 0;
3317 while (next_ci(gridi, nth, ci_block, &ci_x, &ci_y, &ci_b, &ci))
3319 if (nbl->bSimple && flags_i[ci] == 0)
3321 continue;
3324 ncj_old_i = nbl->ncj;
3326 d2cx = 0;
3327 if (gridj != gridi && shp[XX] == 0)
3329 if (nbl->bSimple)
3331 bx1 = bb_i[ci].upper[BB_X];
3333 else
3335 bx1 = gridi->c0[XX] + (ci_x+1)*gridi->sx;
3337 if (bx1 < gridj->c0[XX])
3339 d2cx = gmx::square(gridj->c0[XX] - bx1);
3341 if (d2cx >= rlist2)
3343 continue;
3348 ci_xy = ci_x*gridi->ncy + ci_y;
3350 /* Loop over shift vectors in three dimensions */
3351 for (int tz = -shp[ZZ]; tz <= shp[ZZ]; tz++)
3353 shz = tz*box[ZZ][ZZ];
3355 bz0 = bbcz_i[ci*NNBSBB_D ] + shz;
3356 bz1 = bbcz_i[ci*NNBSBB_D+1] + shz;
3358 if (tz == 0)
3360 d2z = 0;
3362 else if (tz < 0)
3364 d2z = gmx::square(bz1);
3366 else
3368 d2z = gmx::square(bz0 - box[ZZ][ZZ]);
3371 d2z_cx = d2z + d2cx;
3373 if (d2z_cx >= rlist2)
3375 continue;
3378 bz1_frac = bz1/(gridi->cxy_ind[ci_xy+1] - gridi->cxy_ind[ci_xy]);
3379 if (bz1_frac < 0)
3381 bz1_frac = 0;
3383 /* The check with bz1_frac close to or larger than 1 comes later */
3385 for (int ty = -shp[YY]; ty <= shp[YY]; ty++)
3387 shy = ty*box[YY][YY] + tz*box[ZZ][YY];
3389 if (nbl->bSimple)
3391 by0 = bb_i[ci].lower[BB_Y] + shy;
3392 by1 = bb_i[ci].upper[BB_Y] + shy;
3394 else
3396 by0 = gridi->c0[YY] + (ci_y )*gridi->sy + shy;
3397 by1 = gridi->c0[YY] + (ci_y+1)*gridi->sy + shy;
3400 get_cell_range(by0, by1,
3401 gridj->ncy, gridj->c0[YY], gridj->sy, gridj->inv_sy,
3402 d2z_cx, rlist2,
3403 &cyf, &cyl);
3405 if (cyf > cyl)
3407 continue;
3410 d2z_cy = d2z;
3411 if (by1 < gridj->c0[YY])
3413 d2z_cy += gmx::square(gridj->c0[YY] - by1);
3415 else if (by0 > gridj->c1[YY])
3417 d2z_cy += gmx::square(by0 - gridj->c1[YY]);
3420 for (int tx = -shp[XX]; tx <= shp[XX]; tx++)
3422 shift = XYZ2IS(tx, ty, tz);
3424 if (c_pbcShiftBackward && gridi == gridj && shift > CENTRAL)
3426 continue;
3429 shx = tx*box[XX][XX] + ty*box[YY][XX] + tz*box[ZZ][XX];
3431 if (nbl->bSimple)
3433 bx0 = bb_i[ci].lower[BB_X] + shx;
3434 bx1 = bb_i[ci].upper[BB_X] + shx;
3436 else
3438 bx0 = gridi->c0[XX] + (ci_x )*gridi->sx + shx;
3439 bx1 = gridi->c0[XX] + (ci_x+1)*gridi->sx + shx;
3442 get_cell_range(bx0, bx1,
3443 gridj->ncx, gridj->c0[XX], gridj->sx, gridj->inv_sx,
3444 d2z_cy, rlist2,
3445 &cxf, &cxl);
3447 if (cxf > cxl)
3449 continue;
3452 if (nbl->bSimple)
3454 new_ci_entry(nbl, cell0_i+ci, shift, flags_i[ci]);
3456 else
3458 new_sci_entry(nbl, cell0_i+ci, shift);
3461 if ((!c_pbcShiftBackward || (shift == CENTRAL &&
3462 gridi == gridj)) &&
3463 cxf < ci_x)
3465 /* Leave the pairs with i > j.
3466 * x is the major index, so skip half of it.
3468 cxf = ci_x;
3471 if (nbl->bSimple)
3473 set_icell_bb_simple(bb_i, ci, shx, shy, shz,
3474 nbl->work->bb_ci);
3476 else
3478 #if NBNXN_BBXXXX
3479 set_icell_bbxxxx_supersub(pbb_i, ci, shx, shy, shz,
3480 nbl->work->pbb_ci);
3481 #else
3482 set_icell_bb_supersub(bb_i, ci, shx, shy, shz,
3483 nbl->work->bb_ci);
3484 #endif
3487 nbs->icell_set_x(cell0_i+ci, shx, shy, shz,
3488 nbat->xstride, nbat->x,
3489 nbl->work);
3491 for (int cx = cxf; cx <= cxl; cx++)
3493 d2zx = d2z;
3494 if (gridj->c0[XX] + cx*gridj->sx > bx1)
3496 d2zx += gmx::square(gridj->c0[XX] + cx*gridj->sx - bx1);
3498 else if (gridj->c0[XX] + (cx+1)*gridj->sx < bx0)
3500 d2zx += gmx::square(gridj->c0[XX] + (cx+1)*gridj->sx - bx0);
3503 if (gridi == gridj &&
3504 cx == 0 &&
3505 (!c_pbcShiftBackward || shift == CENTRAL) &&
3506 cyf < ci_y)
3508 /* Leave the pairs with i > j.
3509 * Skip half of y when i and j have the same x.
3511 cyf_x = ci_y;
3513 else
3515 cyf_x = cyf;
3518 for (int cy = cyf_x; cy <= cyl; cy++)
3520 const int columnStart = gridj->cxy_ind[cx*gridj->ncy + cy];
3521 const int columnEnd = gridj->cxy_ind[cx*gridj->ncy + cy + 1];
3523 d2zxy = d2zx;
3524 if (gridj->c0[YY] + cy*gridj->sy > by1)
3526 d2zxy += gmx::square(gridj->c0[YY] + cy*gridj->sy - by1);
3528 else if (gridj->c0[YY] + (cy+1)*gridj->sy < by0)
3530 d2zxy += gmx::square(gridj->c0[YY] + (cy+1)*gridj->sy - by0);
3532 if (columnStart < columnEnd && d2zxy < rlist2)
3534 /* To improve efficiency in the common case
3535 * of a homogeneous particle distribution,
3536 * we estimate the index of the middle cell
3537 * in range (midCell). We search down and up
3538 * starting from this index.
3540 * Note that the bbcz_j array contains bounds
3541 * for i-clusters, thus for clusters of 4 atoms.
3542 * For the common case where the j-cluster size
3543 * is 8, we could step with a stride of 2,
3544 * but we do not do this because it would
3545 * complicate this code even more.
3547 int midCell = columnStart + static_cast<int>(bz1_frac*(columnEnd - columnStart));
3548 if (midCell >= columnEnd)
3550 midCell = columnEnd - 1;
3553 d2xy = d2zxy - d2z;
3555 /* Find the lowest cell that can possibly
3556 * be within range.
3557 * Check if we hit the bottom of the grid,
3558 * if the j-cell is below the i-cell and if so,
3559 * if it is within range.
3561 int downTestCell = midCell;
3562 while (downTestCell >= columnStart &&
3563 (bbcz_j[downTestCell*NNBSBB_D + 1] >= bz0 ||
3564 d2xy + gmx::square(bbcz_j[downTestCell*NNBSBB_D + 1] - bz0) < rlist2))
3566 downTestCell--;
3568 int firstCell = downTestCell + 1;
3570 /* Find the highest cell that can possibly
3571 * be within range.
3572 * Check if we hit the top of the grid,
3573 * if the j-cell is above the i-cell and if so,
3574 * if it is within range.
3576 int upTestCell = midCell + 1;
3577 while (upTestCell < columnEnd &&
3578 (bbcz_j[upTestCell*NNBSBB_D] <= bz1 ||
3579 d2xy + gmx::square(bbcz_j[upTestCell*NNBSBB_D] - bz1) < rlist2))
3581 upTestCell++;
3583 int lastCell = upTestCell - 1;
3585 #define NBNXN_REFCODE 0
3586 #if NBNXN_REFCODE
3588 /* Simple reference code, for debugging,
3589 * overrides the more complex code above.
3591 firstCell = columnEnd;
3592 lastCell = -1;
3593 for (int k = columnStart; k < columnEnd; k++)
3595 if (d2xy + gmx::square(bbcz_j[k*NNBSBB_D + 1] - bz0) < rlist2 &&
3596 k < firstCell)
3598 firstCell = k;
3600 if (d2xy + gmx::square(bbcz_j[k*NNBSBB_D] - bz1) < rlist2 &&
3601 k > lastCell)
3603 lastCell = k;
3607 #endif
3609 if (gridi == gridj)
3611 /* We want each atom/cell pair only once,
3612 * only use cj >= ci.
3614 if (!c_pbcShiftBackward || shift == CENTRAL)
3616 firstCell = std::max(firstCell, ci);
3620 if (firstCell <= lastCell)
3622 GMX_ASSERT(firstCell >= columnStart && lastCell < columnEnd, "The range should reside within the current grid column");
3624 /* For f buffer flags with simple lists */
3625 ncj_old_j = nbl->ncj;
3627 if (nbl->bSimple)
3629 /* We have a maximum of 2 j-clusters
3630 * per i-cluster sized cell.
3632 check_cell_list_space_simple(nbl, 2*(lastCell - firstCell + 1));
3634 else
3636 check_cell_list_space_supersub(nbl, lastCell - firstCell + 1);
3639 switch (nb_kernel_type)
3641 case nbnxnk4x4_PlainC:
3642 makeClusterListSimple(gridj,
3643 nbl, ci, firstCell, lastCell,
3644 (gridi == gridj && shift == CENTRAL),
3645 nbat->x,
3646 rlist2, rbb2,
3647 &numDistanceChecks);
3648 break;
3649 #ifdef GMX_NBNXN_SIMD_4XN
3650 case nbnxnk4xN_SIMD_4xN:
3651 makeClusterListSimd4xn(gridj,
3652 nbl, ci, firstCell, lastCell,
3653 (gridi == gridj && shift == CENTRAL),
3654 nbat->x,
3655 rlist2, rbb2,
3656 &numDistanceChecks);
3657 break;
3658 #endif
3659 #ifdef GMX_NBNXN_SIMD_2XNN
3660 case nbnxnk4xN_SIMD_2xNN:
3661 makeClusterListSimd2xnn(gridj,
3662 nbl, ci, firstCell, lastCell,
3663 (gridi == gridj && shift == CENTRAL),
3664 nbat->x,
3665 rlist2, rbb2,
3666 &numDistanceChecks);
3667 break;
3668 #endif
3669 case nbnxnk8x8x8_PlainC:
3670 case nbnxnk8x8x8_GPU:
3671 for (cj = firstCell; cj <= lastCell; cj++)
3673 make_cluster_list_supersub(gridi, gridj,
3674 nbl, ci, cj,
3675 (gridi == gridj && shift == CENTRAL && ci == cj),
3676 nbat->xstride, nbat->x,
3677 rlist2, rbb2,
3678 &numDistanceChecks);
3680 break;
3683 if (bFBufferFlag && nbl->ncj > ncj_old_j)
3685 int cbf = nbl->cj[ncj_old_j].cj >> gridj_flag_shift;
3686 int cbl = nbl->cj[nbl->ncj-1].cj >> gridj_flag_shift;
3687 for (int cb = cbf; cb <= cbl; cb++)
3689 bitmask_init_bit(&gridj_flag[cb], th);
3693 nbl->ncjInUse += nbl->ncj - ncj_old_j;
3699 /* Set the exclusions for this ci list */
3700 if (nbl->bSimple)
3702 set_ci_top_excls(nbs,
3703 nbl,
3704 shift == CENTRAL && gridi == gridj,
3705 gridj->na_c_2log,
3706 na_cj_2log,
3707 &(nbl->ci[nbl->nci]),
3708 excl);
3710 if (nbs->bFEP)
3712 make_fep_list(nbs, nbat, nbl,
3713 shift == CENTRAL && gridi == gridj,
3714 &(nbl->ci[nbl->nci]),
3715 gridi, gridj, nbl_fep);
3718 else
3720 set_sci_top_excls(nbs,
3721 nbl,
3722 shift == CENTRAL && gridi == gridj,
3723 gridj->na_c_2log,
3724 &(nbl->sci[nbl->nsci]),
3725 excl);
3727 if (nbs->bFEP)
3729 make_fep_list_supersub(nbs, nbat, nbl,
3730 shift == CENTRAL && gridi == gridj,
3731 &(nbl->sci[nbl->nsci]),
3732 shx, shy, shz,
3733 rl_fep2,
3734 gridi, gridj, nbl_fep);
3738 /* Close this ci list */
3739 if (nbl->bSimple)
3741 close_ci_entry_simple(nbl);
3743 else
3745 close_ci_entry_supersub(nbl,
3746 nsubpair_max,
3747 progBal, nsubpair_tot_est,
3748 th, nth);
3754 if (bFBufferFlag && nbl->ncj > ncj_old_i)
3756 bitmask_init_bit(&(work->buffer_flags.flag[(gridi->cell0+ci)>>gridi_flag_shift]), th);
3760 work->ndistc = numDistanceChecks;
3762 nbs_cycle_stop(&work->cc[enbsCCsearch]);
3764 GMX_ASSERT(nbl->ncjInUse == nbl->ncj || nbs->bFEP, "Without free-energy all cj pair-list entries should be in use. Note that subsequent code does not make use of the equality, this check is only here to catch bugs");
3766 if (debug)
3768 fprintf(debug, "number of distance checks %d\n", numDistanceChecks);
3770 if (nbl->bSimple)
3772 print_nblist_statistics_simple(debug, nbl, nbs, rlist);
3774 else
3776 print_nblist_statistics_supersub(debug, nbl, nbs, rlist);
3779 if (nbs->bFEP)
3781 fprintf(debug, "nbl FEP list pairs: %d\n", nbl_fep->nrj);
3786 static void reduce_buffer_flags(const nbnxn_search_t nbs,
3787 int nsrc,
3788 const nbnxn_buffer_flags_t *dest)
3790 for (int s = 0; s < nsrc; s++)
3792 gmx_bitmask_t * flag = nbs->work[s].buffer_flags.flag;
3794 for (int b = 0; b < dest->nflag; b++)
3796 bitmask_union(&(dest->flag[b]), flag[b]);
3801 static void print_reduction_cost(const nbnxn_buffer_flags_t *flags, int nout)
3803 int nelem, nkeep, ncopy, nred, out;
3804 gmx_bitmask_t mask_0;
3806 nelem = 0;
3807 nkeep = 0;
3808 ncopy = 0;
3809 nred = 0;
3810 bitmask_init_bit(&mask_0, 0);
3811 for (int b = 0; b < flags->nflag; b++)
3813 if (bitmask_is_equal(flags->flag[b], mask_0))
3815 /* Only flag 0 is set, no copy of reduction required */
3816 nelem++;
3817 nkeep++;
3819 else if (!bitmask_is_zero(flags->flag[b]))
3821 int c = 0;
3822 for (out = 0; out < nout; out++)
3824 if (bitmask_is_set(flags->flag[b], out))
3826 c++;
3829 nelem += c;
3830 if (c == 1)
3832 ncopy++;
3834 else
3836 nred += c;
3841 fprintf(debug, "nbnxn reduction: #flag %d #list %d elem %4.2f, keep %4.2f copy %4.2f red %4.2f\n",
3842 flags->nflag, nout,
3843 nelem/(double)(flags->nflag),
3844 nkeep/(double)(flags->nflag),
3845 ncopy/(double)(flags->nflag),
3846 nred/(double)(flags->nflag));
3849 /* Copies the list entries from src to dest when cjStart <= *cjGlobal < cjEnd.
3850 * *cjGlobal is updated with the cj count in src.
3851 * When setFlags==true, flag bit t is set in flag for all i and j clusters.
3853 template<bool setFlags>
3854 static void copySelectedListRange(const nbnxn_ci_t * gmx_restrict srcCi,
3855 const nbnxn_pairlist_t * gmx_restrict src,
3856 nbnxn_pairlist_t * gmx_restrict dest,
3857 gmx_bitmask_t *flag,
3858 int iFlagShift, int jFlagShift, int t)
3860 int ncj = srcCi->cj_ind_end - srcCi->cj_ind_start;
3862 if (dest->nci + 1 >= dest->ci_nalloc)
3864 nb_realloc_ci(dest, dest->nci + 1);
3866 check_cell_list_space_simple(dest, ncj);
3868 dest->ci[dest->nci] = *srcCi;
3869 dest->ci[dest->nci].cj_ind_start = dest->ncj;
3870 dest->ci[dest->nci].cj_ind_end = dest->ncj + ncj;
3872 if (setFlags)
3874 bitmask_init_bit(&flag[srcCi->ci >> iFlagShift], t);
3877 for (int j = srcCi->cj_ind_start; j < srcCi->cj_ind_end; j++)
3879 dest->cj[dest->ncj++] = src->cj[j];
3881 if (setFlags)
3883 /* NOTE: This is relatively expensive, since this
3884 * operation is done for all elements in the list,
3885 * whereas at list generation this is done only
3886 * once for each flag entry.
3888 bitmask_init_bit(&flag[src->cj[j].cj >> jFlagShift], t);
3892 dest->nci++;
3895 /* This routine re-balances the pairlists such that all are nearly equally
3896 * sized. Only whole i-entries are moved between lists. These are moved
3897 * between the ends of the lists, such that the buffer reduction cost should
3898 * not change significantly.
3899 * Note that all original reduction flags are currently kept. This can lead
3900 * to reduction of parts of the force buffer that could be avoided. But since
3901 * the original lists are quite balanced, this will only give minor overhead.
3903 static void rebalanceSimpleLists(int numLists,
3904 nbnxn_pairlist_t * const * const srcSet,
3905 nbnxn_pairlist_t **destSet,
3906 nbnxn_search_work_t *searchWork)
3908 int ncjTotal = 0;
3909 for (int s = 0; s < numLists; s++)
3911 ncjTotal += srcSet[s]->ncjInUse;
3913 int ncjTarget = (ncjTotal + numLists - 1)/numLists;
3915 #pragma omp parallel num_threads(numLists)
3917 int t = gmx_omp_get_thread_num();
3919 int cjStart = ncjTarget* t;
3920 int cjEnd = ncjTarget*(t + 1);
3922 /* The destination pair-list for task/thread t */
3923 nbnxn_pairlist_t *dest = destSet[t];
3925 clear_pairlist(dest);
3926 dest->bSimple = srcSet[0]->bSimple;
3927 dest->na_ci = srcSet[0]->na_ci;
3928 dest->na_cj = srcSet[0]->na_cj;
3930 /* Note that the flags in the work struct (still) contain flags
3931 * for all entries that are present in srcSet->nbl[t].
3933 gmx_bitmask_t *flag = searchWork[t].buffer_flags.flag;
3935 int iFlagShift = getBufferFlagShift(dest->na_ci);
3936 int jFlagShift = getBufferFlagShift(dest->na_cj);
3938 int cjGlobal = 0;
3939 for (int s = 0; s < numLists && cjGlobal < cjEnd; s++)
3941 const nbnxn_pairlist_t *src = srcSet[s];
3943 if (cjGlobal + src->ncjInUse > cjStart)
3945 for (int i = 0; i < src->nci && cjGlobal < cjEnd; i++)
3947 const nbnxn_ci_t *srcCi = &src->ci[i];
3948 int ncj = srcCi->cj_ind_end - srcCi->cj_ind_start;
3949 if (cjGlobal >= cjStart)
3951 /* If the source list is not our own, we need to set
3952 * extra flags (the template bool parameter).
3954 if (s != t)
3956 copySelectedListRange
3957 <true>
3958 (srcCi, src, dest,
3959 flag, iFlagShift, jFlagShift, t);
3961 else
3963 copySelectedListRange
3964 <false>
3965 (srcCi, src,
3966 dest, flag, iFlagShift, jFlagShift, t);
3969 cjGlobal += ncj;
3972 else
3974 cjGlobal += src->ncjInUse;
3978 dest->ncjInUse = dest->ncj;
3981 #ifndef NDEBUG
3982 int ncjTotalNew = 0;
3983 for (int s = 0; s < numLists; s++)
3985 ncjTotalNew += destSet[s]->ncjInUse;
3987 GMX_RELEASE_ASSERT(ncjTotalNew == ncjTotal, "The total size of the lists before and after rebalancing should match");
3988 #endif
3991 /* Returns if the pairlists are so imbalanced that it is worth rebalancing. */
3992 static bool checkRebalanceSimpleLists(const nbnxn_pairlist_set_t *listSet)
3994 int numLists = listSet->nnbl;
3995 int ncjMax = 0;
3996 int ncjTotal = 0;
3997 for (int s = 0; s < numLists; s++)
3999 ncjMax = std::max(ncjMax, listSet->nbl[s]->ncjInUse);
4000 ncjTotal += listSet->nbl[s]->ncjInUse;
4002 if (debug)
4004 fprintf(debug, "Pair-list ncjMax %d ncjTotal %d\n", ncjMax, ncjTotal);
4006 /* The rebalancing adds 3% extra time to the search. Heuristically we
4007 * determined that under common conditions the non-bonded kernel balance
4008 * improvement will outweigh this when the imbalance is more than 3%.
4009 * But this will, obviously, depend on search vs kernel time and nstlist.
4011 const real rebalanceTolerance = 1.03;
4013 return numLists*ncjMax > ncjTotal*rebalanceTolerance;
4016 /* Perform a count (linear) sort to sort the smaller lists to the end.
4017 * This avoids load imbalance on the GPU, as large lists will be
4018 * scheduled and executed first and the smaller lists later.
4019 * Load balancing between multi-processors only happens at the end
4020 * and there smaller lists lead to more effective load balancing.
4021 * The sorting is done on the cj4 count, not on the actual pair counts.
4022 * Not only does this make the sort faster, but it also results in
4023 * better load balancing than using a list sorted on exact load.
4024 * This function swaps the pointer in the pair list to avoid a copy operation.
4026 static void sort_sci(nbnxn_pairlist_t *nbl)
4028 nbnxn_list_work_t *work;
4029 int m, s0, s1;
4030 nbnxn_sci_t *sci_sort;
4032 if (nbl->ncj4 <= nbl->nsci)
4034 /* nsci = 0 or all sci have size 1, sorting won't change the order */
4035 return;
4038 work = nbl->work;
4040 /* We will distinguish differences up to double the average */
4041 m = (2*nbl->ncj4)/nbl->nsci;
4043 if (m + 1 > work->sort_nalloc)
4045 work->sort_nalloc = over_alloc_large(m + 1);
4046 srenew(work->sort, work->sort_nalloc);
4049 if (work->sci_sort_nalloc != nbl->sci_nalloc)
4051 work->sci_sort_nalloc = nbl->sci_nalloc;
4052 nbnxn_realloc_void((void **)&work->sci_sort,
4054 work->sci_sort_nalloc*sizeof(*work->sci_sort),
4055 nbl->alloc, nbl->free);
4058 /* Count the entries of each size */
4059 for (int i = 0; i <= m; i++)
4061 work->sort[i] = 0;
4063 for (int s = 0; s < nbl->nsci; s++)
4065 int i = std::min(m, nbl->sci[s].cj4_ind_end - nbl->sci[s].cj4_ind_start);
4066 work->sort[i]++;
4068 /* Calculate the offset for each count */
4069 s0 = work->sort[m];
4070 work->sort[m] = 0;
4071 for (int i = m - 1; i >= 0; i--)
4073 s1 = work->sort[i];
4074 work->sort[i] = work->sort[i + 1] + s0;
4075 s0 = s1;
4078 /* Sort entries directly into place */
4079 sci_sort = work->sci_sort;
4080 for (int s = 0; s < nbl->nsci; s++)
4082 int i = std::min(m, nbl->sci[s].cj4_ind_end - nbl->sci[s].cj4_ind_start);
4083 sci_sort[work->sort[i]++] = nbl->sci[s];
4086 /* Swap the sci pointers so we use the new, sorted list */
4087 work->sci_sort = nbl->sci;
4088 nbl->sci = sci_sort;
4091 /* Make a local or non-local pair-list, depending on iloc */
4092 void nbnxn_make_pairlist(const nbnxn_search_t nbs,
4093 nbnxn_atomdata_t *nbat,
4094 const t_blocka *excl,
4095 real rlist,
4096 int min_ci_balanced,
4097 nbnxn_pairlist_set_t *nbl_list,
4098 int iloc,
4099 int nb_kernel_type,
4100 t_nrnb *nrnb)
4102 nbnxn_grid_t *gridi, *gridj;
4103 int nzi, zj0, zj1;
4104 int nsubpair_target;
4105 float nsubpair_tot_est;
4106 int nnbl;
4107 nbnxn_pairlist_t **nbl;
4108 int ci_block;
4109 gmx_bool CombineNBLists;
4110 gmx_bool progBal;
4111 int np_tot, np_noq, np_hlj, nap;
4113 nnbl = nbl_list->nnbl;
4114 nbl = nbl_list->nbl;
4115 CombineNBLists = nbl_list->bCombined;
4117 if (debug)
4119 fprintf(debug, "ns making %d nblists\n", nnbl);
4122 nbat->bUseBufferFlags = (nbat->nout > 1);
4123 /* We should re-init the flags before making the first list */
4124 if (nbat->bUseBufferFlags && LOCAL_I(iloc))
4126 init_buffer_flags(&nbat->buffer_flags, nbat->natoms);
4129 if (nbl_list->bSimple)
4131 #if GMX_SIMD
4132 switch (nb_kernel_type)
4134 #ifdef GMX_NBNXN_SIMD_4XN
4135 case nbnxnk4xN_SIMD_4xN:
4136 nbs->icell_set_x = icell_set_x_simd_4xn;
4137 break;
4138 #endif
4139 #ifdef GMX_NBNXN_SIMD_2XNN
4140 case nbnxnk4xN_SIMD_2xNN:
4141 nbs->icell_set_x = icell_set_x_simd_2xnn;
4142 break;
4143 #endif
4144 default:
4145 nbs->icell_set_x = icell_set_x_simple;
4146 break;
4148 #else // GMX_SIMD
4149 /* MSVC 2013 complains about switch statements without case */
4150 nbs->icell_set_x = icell_set_x_simple;
4151 #endif // GMX_SIMD
4153 else
4155 nbs->icell_set_x = icell_set_x_supersub;
4158 if (LOCAL_I(iloc))
4160 /* Only zone (grid) 0 vs 0 */
4161 nzi = 1;
4162 zj0 = 0;
4163 zj1 = 1;
4165 else
4167 nzi = nbs->zones->nizone;
4170 if (!nbl_list->bSimple && min_ci_balanced > 0)
4172 get_nsubpair_target(nbs, iloc, rlist, min_ci_balanced,
4173 &nsubpair_target, &nsubpair_tot_est);
4175 else
4177 nsubpair_target = 0;
4178 nsubpair_tot_est = 0;
4181 /* Clear all pair-lists */
4182 for (int th = 0; th < nnbl; th++)
4184 clear_pairlist(nbl[th]);
4186 if (nbs->bFEP)
4188 clear_pairlist_fep(nbl_list->nbl_fep[th]);
4192 for (int zi = 0; zi < nzi; zi++)
4194 gridi = &nbs->grid[zi];
4196 if (NONLOCAL_I(iloc))
4198 zj0 = nbs->zones->izone[zi].j0;
4199 zj1 = nbs->zones->izone[zi].j1;
4200 if (zi == 0)
4202 zj0++;
4205 for (int zj = zj0; zj < zj1; zj++)
4207 gridj = &nbs->grid[zj];
4209 if (debug)
4211 fprintf(debug, "ns search grid %d vs %d\n", zi, zj);
4214 nbs_cycle_start(&nbs->cc[enbsCCsearch]);
4216 ci_block = get_ci_block_size(gridi, nbs->DomDec, nnbl);
4218 /* With GPU: generate progressively smaller lists for
4219 * load balancing for local only or non-local with 2 zones.
4221 progBal = (LOCAL_I(iloc) || nbs->zones->n <= 2);
4223 #pragma omp parallel for num_threads(nnbl) schedule(static)
4224 for (int th = 0; th < nnbl; th++)
4228 /* Re-init the thread-local work flag data before making
4229 * the first list (not an elegant conditional).
4231 if (nbat->bUseBufferFlags && ((zi == 0 && zj == 0)))
4233 init_buffer_flags(&nbs->work[th].buffer_flags, nbat->natoms);
4236 if (CombineNBLists && th > 0)
4238 clear_pairlist(nbl[th]);
4241 /* Divide the i super cell equally over the nblists */
4242 nbnxn_make_pairlist_part(nbs, gridi, gridj,
4243 &nbs->work[th], nbat, excl,
4244 rlist,
4245 nb_kernel_type,
4246 ci_block,
4247 nbat->bUseBufferFlags,
4248 nsubpair_target,
4249 progBal, nsubpair_tot_est,
4250 th, nnbl,
4251 nbl[th],
4252 nbl_list->nbl_fep[th]);
4254 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
4256 nbs_cycle_stop(&nbs->cc[enbsCCsearch]);
4258 np_tot = 0;
4259 np_noq = 0;
4260 np_hlj = 0;
4261 for (int th = 0; th < nnbl; th++)
4263 inc_nrnb(nrnb, eNR_NBNXN_DIST2, nbs->work[th].ndistc);
4265 if (nbl_list->bSimple)
4267 np_tot += nbl[th]->ncj;
4268 np_noq += nbl[th]->work->ncj_noq;
4269 np_hlj += nbl[th]->work->ncj_hlj;
4271 else
4273 /* This count ignores potential subsequent pair pruning */
4274 np_tot += nbl[th]->nci_tot;
4277 nap = nbl[0]->na_ci*nbl[0]->na_cj;
4278 nbl_list->natpair_ljq = (np_tot - np_noq)*nap - np_hlj*nap/2;
4279 nbl_list->natpair_lj = np_noq*nap;
4280 nbl_list->natpair_q = np_hlj*nap/2;
4282 if (CombineNBLists && nnbl > 1)
4284 nbs_cycle_start(&nbs->cc[enbsCCcombine]);
4286 combine_nblists(nnbl-1, nbl+1, nbl[0]);
4288 nbs_cycle_stop(&nbs->cc[enbsCCcombine]);
4293 if (nbl_list->bSimple)
4295 if (nnbl > 1 && checkRebalanceSimpleLists(nbl_list))
4297 rebalanceSimpleLists(nbl_list->nnbl, nbl_list->nbl, nbl_list->nbl_work, nbs->work);
4299 /* Swap the pointer of the sets of pair lists */
4300 nbnxn_pairlist_t **tmp = nbl_list->nbl;
4301 nbl_list->nbl = nbl_list->nbl_work;
4302 nbl_list->nbl_work = tmp;
4305 else
4307 /* Sort the entries on size, large ones first */
4308 if (CombineNBLists || nnbl == 1)
4310 sort_sci(nbl[0]);
4312 else
4314 #pragma omp parallel for num_threads(nnbl) schedule(static)
4315 for (int th = 0; th < nnbl; th++)
4319 sort_sci(nbl[th]);
4321 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
4326 if (nbat->bUseBufferFlags)
4328 reduce_buffer_flags(nbs, nbl_list->nnbl, &nbat->buffer_flags);
4331 if (nbs->bFEP)
4333 /* Balance the free-energy lists over all the threads */
4334 balance_fep_lists(nbs, nbl_list);
4337 /* This is a fresh list, so not pruned, stored using ci and nci.
4338 * ciOuter and nciOuter are invalid at this point.
4340 GMX_ASSERT(nbl_list->nbl[0]->nciOuter == -1, "nciOuter should have been set to -1 to signal that it is invalid");
4342 /* Special performance logging stuff (env.var. GMX_NBNXN_CYCLE) */
4343 if (LOCAL_I(iloc))
4345 nbs->search_count++;
4347 if (nbs->print_cycles &&
4348 (!nbs->DomDec || !LOCAL_I(iloc)) &&
4349 nbs->search_count % 100 == 0)
4351 nbs_cycle_print(stderr, nbs);
4354 /* If we have more than one list, they either got rebalancing (CPU)
4355 * or combined (GPU), so we should dump the final result to debug.
4357 if (debug && nbl_list->nnbl > 1)
4359 if (nbl_list->bSimple)
4361 for (int t = 0; t < nbl_list->nnbl; t++)
4363 print_nblist_statistics_simple(debug, nbl_list->nbl[t], nbs, rlist);
4366 else
4368 print_nblist_statistics_supersub(debug, nbl_list->nbl[0], nbs, rlist);
4372 if (debug)
4374 if (gmx_debug_at)
4376 if (nbl_list->bSimple)
4378 for (int t = 0; t < nbl_list->nnbl; t++)
4380 print_nblist_ci_cj(debug, nbl_list->nbl[t]);
4383 else
4385 print_nblist_sci_cj(debug, nbl_list->nbl[0]);
4389 if (nbat->bUseBufferFlags)
4391 print_reduction_cost(&nbat->buffer_flags, nbl_list->nnbl);
4396 void nbnxnPrepareListForDynamicPruning(nbnxn_pairlist_set_t *listSet)
4398 /* TODO: Restructure the lists so we have actual outer and inner
4399 * list objects so we can set a single pointer instead of
4400 * swapping several pointers.
4403 for (int i = 0; i < listSet->nnbl; i++)
4405 /* The search produced a list in ci/cj.
4406 * Swap the list pointers so we get the outer list is ciOuter,cjOuter
4407 * and we can prune that to get an inner list in ci/cj.
4409 nbnxn_pairlist_t *list = listSet->nbl[i];
4410 list->nciOuter = list->nci;
4412 nbnxn_ci_t *ciTmp = list->ciOuter;
4413 list->ciOuter = list->ci;
4414 list->ci = ciTmp;
4416 nbnxn_cj_t *cjTmp = list->cjOuter;
4417 list->cjOuter = list->cj;
4418 list->cj = cjTmp;
4420 /* Signal that this inner list is currently invalid */
4421 list->nci = -1;