2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2012,2013,2014,2015,2016,2017,2018,2019, 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.
48 #include "gromacs/domdec/domdec_struct.h"
49 #include "gromacs/gmxlib/nrnb.h"
50 #include "gromacs/math/functions.h"
51 #include "gromacs/math/utilities.h"
52 #include "gromacs/math/vec.h"
53 #include "gromacs/mdlib/gmx_omp_nthreads.h"
54 #include "gromacs/mdlib/ns.h"
55 #include "gromacs/mdtypes/group.h"
56 #include "gromacs/mdtypes/md_enums.h"
57 #include "gromacs/nbnxm/atomdata.h"
58 #include "gromacs/nbnxm/nbnxm.h"
59 #include "gromacs/nbnxm/nbnxm_geometry.h"
60 #include "gromacs/nbnxm/nbnxm_simd.h"
61 #include "gromacs/nbnxm/pairlistset.h"
62 #include "gromacs/pbcutil/ishift.h"
63 #include "gromacs/pbcutil/pbc.h"
64 #include "gromacs/simd/simd.h"
65 #include "gromacs/simd/vector_operations.h"
66 #include "gromacs/topology/block.h"
67 #include "gromacs/utility/exceptions.h"
68 #include "gromacs/utility/fatalerror.h"
69 #include "gromacs/utility/gmxomp.h"
70 #include "gromacs/utility/smalloc.h"
74 #include "pairlistwork.h"
76 using namespace gmx; // TODO: Remove when this file is moved into gmx namespace
79 /* We shift the i-particles backward for PBC.
80 * This leads to more conditionals than shifting forward.
81 * We do this to get more balanced pair lists.
83 constexpr bool c_pbcShiftBackward = true;
86 static void nbs_cycle_clear(nbnxn_cycle_t *cc)
88 for (int i = 0; i < enbsCCnr; i++)
95 static double Mcyc_av(const nbnxn_cycle_t *cc)
97 return static_cast<double>(cc->c)*1e-6/cc->count;
100 static void nbs_cycle_print(FILE *fp, const nbnxn_search *nbs)
103 fprintf(fp, "ns %4d grid %4.1f search %4.1f red.f %5.3f",
104 nbs->cc[enbsCCgrid].count,
105 Mcyc_av(&nbs->cc[enbsCCgrid]),
106 Mcyc_av(&nbs->cc[enbsCCsearch]),
107 Mcyc_av(&nbs->cc[enbsCCreducef]));
109 if (nbs->work.size() > 1)
111 if (nbs->cc[enbsCCcombine].count > 0)
113 fprintf(fp, " comb %5.2f",
114 Mcyc_av(&nbs->cc[enbsCCcombine]));
116 fprintf(fp, " s. th");
117 for (const nbnxn_search_work_t &work : nbs->work)
119 fprintf(fp, " %4.1f",
120 Mcyc_av(&work.cc[enbsCCsearch]));
126 /* Layout for the nonbonded NxN pair lists */
127 enum class NbnxnLayout
129 NoSimd4x4, // i-cluster size 4, j-cluster size 4
130 Simd4xN, // i-cluster size 4, j-cluster size SIMD width
131 Simd2xNN, // i-cluster size 4, j-cluster size half SIMD width
132 Gpu8x8x8 // i-cluster size 8, j-cluster size 8 + super-clustering
136 /* Returns the j-cluster size */
137 template <NbnxnLayout layout>
138 static constexpr int jClusterSize()
140 static_assert(layout == NbnxnLayout::NoSimd4x4 || layout == NbnxnLayout::Simd4xN || layout == NbnxnLayout::Simd2xNN, "Currently jClusterSize only supports CPU layouts");
142 return layout == NbnxnLayout::Simd4xN ? GMX_SIMD_REAL_WIDTH : (layout == NbnxnLayout::Simd2xNN ? GMX_SIMD_REAL_WIDTH/2 : c_nbnxnCpuIClusterSize);
145 /*! \brief Returns the j-cluster index given the i-cluster index.
147 * \tparam jClusterSize The number of atoms in a j-cluster
148 * \tparam jSubClusterIndex The j-sub-cluster index (0/1), used when size(j-cluster) < size(i-cluster)
149 * \param[in] ci The i-cluster index
151 template <int jClusterSize, int jSubClusterIndex>
152 static inline int cjFromCi(int ci)
154 static_assert(jClusterSize == c_nbnxnCpuIClusterSize/2 || jClusterSize == c_nbnxnCpuIClusterSize || jClusterSize == c_nbnxnCpuIClusterSize*2, "Only j-cluster sizes 2, 4 and 8 are currently implemented");
156 static_assert(jSubClusterIndex == 0 || jSubClusterIndex == 1,
157 "Only sub-cluster indices 0 and 1 are supported");
159 if (jClusterSize == c_nbnxnCpuIClusterSize/2)
161 if (jSubClusterIndex == 0)
167 return ((ci + 1) << 1) - 1;
170 else if (jClusterSize == c_nbnxnCpuIClusterSize)
180 /*! \brief Returns the j-cluster index given the i-cluster index.
182 * \tparam layout The pair-list layout
183 * \tparam jSubClusterIndex The j-sub-cluster index (0/1), used when size(j-cluster) < size(i-cluster)
184 * \param[in] ci The i-cluster index
186 template <NbnxnLayout layout, int jSubClusterIndex>
187 static inline int cjFromCi(int ci)
189 constexpr int clusterSize = jClusterSize<layout>();
191 return cjFromCi<clusterSize, jSubClusterIndex>(ci);
194 /* Returns the nbnxn coordinate data index given the i-cluster index */
195 template <NbnxnLayout layout>
196 static inline int xIndexFromCi(int ci)
198 constexpr int clusterSize = jClusterSize<layout>();
200 static_assert(clusterSize == c_nbnxnCpuIClusterSize/2 || clusterSize == c_nbnxnCpuIClusterSize || clusterSize == c_nbnxnCpuIClusterSize*2, "Only j-cluster sizes 2, 4 and 8 are currently implemented");
202 if (clusterSize <= c_nbnxnCpuIClusterSize)
204 /* Coordinates are stored packed in groups of 4 */
209 /* Coordinates packed in 8, i-cluster size is half the packing width */
210 return (ci >> 1)*STRIDE_P8 + (ci & 1)*(c_packX8 >> 1);
214 /* Returns the nbnxn coordinate data index given the j-cluster index */
215 template <NbnxnLayout layout>
216 static inline int xIndexFromCj(int cj)
218 constexpr int clusterSize = jClusterSize<layout>();
220 static_assert(clusterSize == c_nbnxnCpuIClusterSize/2 || clusterSize == c_nbnxnCpuIClusterSize || clusterSize == c_nbnxnCpuIClusterSize*2, "Only j-cluster sizes 2, 4 and 8 are currently implemented");
222 if (clusterSize == c_nbnxnCpuIClusterSize/2)
224 /* Coordinates are stored packed in groups of 4 */
225 return (cj >> 1)*STRIDE_P4 + (cj & 1)*(c_packX4 >> 1);
227 else if (clusterSize == c_nbnxnCpuIClusterSize)
229 /* Coordinates are stored packed in groups of 4 */
234 /* Coordinates are stored packed in groups of 8 */
240 gmx_bool nbnxn_kernel_pairlist_simple(int nb_kernel_type)
242 if (nb_kernel_type == nbnxnkNotSet)
244 gmx_fatal(FARGS, "Non-bonded kernel type not set for Verlet-style pair-list.");
247 switch (nb_kernel_type)
249 case nbnxnk8x8x8_GPU:
250 case nbnxnk8x8x8_PlainC:
253 case nbnxnk4x4_PlainC:
254 case nbnxnk4xN_SIMD_4xN:
255 case nbnxnk4xN_SIMD_2xNN:
259 gmx_incons("Invalid nonbonded kernel type passed!");
264 /* Initializes a single nbnxn_pairlist_t data structure */
265 static void nbnxn_init_pairlist_fep(t_nblist *nl)
267 nl->type = GMX_NBLIST_INTERACTION_FREE_ENERGY;
268 nl->igeometry = GMX_NBLIST_GEOMETRY_PARTICLE_PARTICLE;
269 /* The interaction functions are set in the free energy kernel fuction */
282 nl->jindex = nullptr;
284 nl->excl_fep = nullptr;
288 static void free_nblist(t_nblist *nl)
298 nbnxn_search_work_t::nbnxn_search_work_t() :
301 buffer_flags({0, nullptr, 0}),
303 nbl_fep(new t_nblist),
306 nbnxn_init_pairlist_fep(nbl_fep.get());
311 nbnxn_search_work_t::~nbnxn_search_work_t()
313 sfree(buffer_flags.flag);
315 free_nblist(nbl_fep.get());
318 nbnxn_search::nbnxn_search(const ivec *n_dd_cells,
319 const gmx_domdec_zones_t *zones,
323 ePBC(epbcNONE), // The correct value will be set during the gridding
330 // The correct value will be set during the gridding
334 DomDec = n_dd_cells != nullptr;
337 for (int d = 0; d < DIM; d++)
339 if ((*n_dd_cells)[d] > 1)
342 /* Each grid matches a DD zone */
348 grid.resize(numGrids);
350 /* Initialize detailed nbsearch cycle counting */
351 print_cycles = (getenv("GMX_NBNXN_CYCLE") != nullptr);
355 nbnxn_search *nbnxn_init_search(const ivec *n_dd_cells,
356 const gmx_domdec_zones_t *zones,
360 return new nbnxn_search(n_dd_cells, zones, bFEP, nthread_max);
363 static void init_buffer_flags(nbnxn_buffer_flags_t *flags,
366 flags->nflag = (natoms + NBNXN_BUFFERFLAG_SIZE - 1)/NBNXN_BUFFERFLAG_SIZE;
367 if (flags->nflag > flags->flag_nalloc)
369 flags->flag_nalloc = over_alloc_large(flags->nflag);
370 srenew(flags->flag, flags->flag_nalloc);
372 for (int b = 0; b < flags->nflag; b++)
374 bitmask_clear(&(flags->flag[b]));
378 /* Returns the pair-list cutoff between a bounding box and a grid cell given an atom-to-atom pair-list cutoff
380 * Given a cutoff distance between atoms, this functions returns the cutoff
381 * distance2 between a bounding box of a group of atoms and a grid cell.
382 * Since atoms can be geometrically outside of the cell they have been
383 * assigned to (when atom groups instead of individual atoms are assigned
384 * to cells), this distance returned can be larger than the input.
386 static real listRangeForBoundingBoxToGridCell(real rlist,
387 const nbnxn_grid_t &grid)
389 return rlist + grid.maxAtomGroupRadius;
392 /* Returns the pair-list cutoff between a grid cells given an atom-to-atom pair-list cutoff
394 * Given a cutoff distance between atoms, this functions returns the cutoff
395 * distance2 between two grid cells.
396 * Since atoms can be geometrically outside of the cell they have been
397 * assigned to (when atom groups instead of individual atoms are assigned
398 * to cells), this distance returned can be larger than the input.
400 static real listRangeForGridCellToGridCell(real rlist,
401 const nbnxn_grid_t &iGrid,
402 const nbnxn_grid_t &jGrid)
404 return rlist + iGrid.maxAtomGroupRadius + jGrid.maxAtomGroupRadius;
407 /* Determines the cell range along one dimension that
408 * the bounding box b0 - b1 sees.
411 static void get_cell_range(real b0, real b1,
412 const nbnxn_grid_t &jGrid,
413 real d2, real rlist, int *cf, int *cl)
415 real listRangeBBToCell2 = gmx::square(listRangeForBoundingBoxToGridCell(rlist, jGrid));
416 real distanceInCells = (b0 - jGrid.c0[dim])*jGrid.invCellSize[dim];
417 *cf = std::max(static_cast<int>(distanceInCells), 0);
420 d2 + gmx::square((b0 - jGrid.c0[dim]) - (*cf - 1 + 1)*jGrid.cellSize[dim]) < listRangeBBToCell2)
425 *cl = std::min(static_cast<int>((b1 - jGrid.c0[dim])*jGrid.invCellSize[dim]), jGrid.numCells[dim] - 1);
426 while (*cl < jGrid.numCells[dim] - 1 &&
427 d2 + gmx::square((*cl + 1)*jGrid.cellSize[dim] - (b1 - jGrid.c0[dim])) < listRangeBBToCell2)
433 /* Reference code calculating the distance^2 between two bounding boxes */
435 static float box_dist2(float bx0, float bx1, float by0,
436 float by1, float bz0, float bz1,
437 const nbnxn_bb_t *bb)
440 float dl, dh, dm, dm0;
444 dl = bx0 - bb->upper[BB_X];
445 dh = bb->lower[BB_X] - bx1;
446 dm = std::max(dl, dh);
447 dm0 = std::max(dm, 0.0f);
450 dl = by0 - bb->upper[BB_Y];
451 dh = bb->lower[BB_Y] - by1;
452 dm = std::max(dl, dh);
453 dm0 = std::max(dm, 0.0f);
456 dl = bz0 - bb->upper[BB_Z];
457 dh = bb->lower[BB_Z] - bz1;
458 dm = std::max(dl, dh);
459 dm0 = std::max(dm, 0.0f);
466 /* Plain C code calculating the distance^2 between two bounding boxes */
467 static float subc_bb_dist2(int si,
468 const nbnxn_bb_t *bb_i_ci,
470 gmx::ArrayRef<const nbnxn_bb_t> bb_j_all)
472 const nbnxn_bb_t *bb_i = bb_i_ci + si;
473 const nbnxn_bb_t *bb_j = bb_j_all.data() + csj;
476 float dl, dh, dm, dm0;
478 dl = bb_i->lower[BB_X] - bb_j->upper[BB_X];
479 dh = bb_j->lower[BB_X] - bb_i->upper[BB_X];
480 dm = std::max(dl, dh);
481 dm0 = std::max(dm, 0.0f);
484 dl = bb_i->lower[BB_Y] - bb_j->upper[BB_Y];
485 dh = bb_j->lower[BB_Y] - bb_i->upper[BB_Y];
486 dm = std::max(dl, dh);
487 dm0 = std::max(dm, 0.0f);
490 dl = bb_i->lower[BB_Z] - bb_j->upper[BB_Z];
491 dh = bb_j->lower[BB_Z] - bb_i->upper[BB_Z];
492 dm = std::max(dl, dh);
493 dm0 = std::max(dm, 0.0f);
499 #if NBNXN_SEARCH_BB_SIMD4
501 /* 4-wide SIMD code for bb distance for bb format xyz0 */
502 static float subc_bb_dist2_simd4(int si,
503 const nbnxn_bb_t *bb_i_ci,
505 gmx::ArrayRef<const nbnxn_bb_t> bb_j_all)
507 // TODO: During SIMDv2 transition only some archs use namespace (remove when done)
510 Simd4Float bb_i_S0, bb_i_S1;
511 Simd4Float bb_j_S0, bb_j_S1;
517 bb_i_S0 = load4(&bb_i_ci[si].lower[0]);
518 bb_i_S1 = load4(&bb_i_ci[si].upper[0]);
519 bb_j_S0 = load4(&bb_j_all[csj].lower[0]);
520 bb_j_S1 = load4(&bb_j_all[csj].upper[0]);
522 dl_S = bb_i_S0 - bb_j_S1;
523 dh_S = bb_j_S0 - bb_i_S1;
525 dm_S = max(dl_S, dh_S);
526 dm0_S = max(dm_S, simd4SetZeroF());
528 return dotProduct(dm0_S, dm0_S);
531 /* Calculate bb bounding distances of bb_i[si,...,si+3] and store them in d2 */
532 #define SUBC_BB_DIST2_SIMD4_XXXX_INNER(si, bb_i, d2) \
536 Simd4Float dx_0, dy_0, dz_0; \
537 Simd4Float dx_1, dy_1, dz_1; \
539 Simd4Float mx, my, mz; \
540 Simd4Float m0x, m0y, m0z; \
542 Simd4Float d2x, d2y, d2z; \
543 Simd4Float d2s, d2t; \
545 shi = (si)*NNBSBB_D*DIM; \
547 xi_l = load4((bb_i)+shi+0*STRIDE_PBB); \
548 yi_l = load4((bb_i)+shi+1*STRIDE_PBB); \
549 zi_l = load4((bb_i)+shi+2*STRIDE_PBB); \
550 xi_h = load4((bb_i)+shi+3*STRIDE_PBB); \
551 yi_h = load4((bb_i)+shi+4*STRIDE_PBB); \
552 zi_h = load4((bb_i)+shi+5*STRIDE_PBB); \
554 dx_0 = xi_l - xj_h; \
555 dy_0 = yi_l - yj_h; \
556 dz_0 = zi_l - zj_h; \
558 dx_1 = xj_l - xi_h; \
559 dy_1 = yj_l - yi_h; \
560 dz_1 = zj_l - zi_h; \
562 mx = max(dx_0, dx_1); \
563 my = max(dy_0, dy_1); \
564 mz = max(dz_0, dz_1); \
566 m0x = max(mx, zero); \
567 m0y = max(my, zero); \
568 m0z = max(mz, zero); \
577 store4((d2)+(si), d2t); \
580 /* 4-wide SIMD code for nsi bb distances for bb format xxxxyyyyzzzz */
581 static void subc_bb_dist2_simd4_xxxx(const float *bb_j,
582 int nsi, const float *bb_i,
585 // TODO: During SIMDv2 transition only some archs use namespace (remove when done)
588 Simd4Float xj_l, yj_l, zj_l;
589 Simd4Float xj_h, yj_h, zj_h;
590 Simd4Float xi_l, yi_l, zi_l;
591 Simd4Float xi_h, yi_h, zi_h;
597 xj_l = Simd4Float(bb_j[0*STRIDE_PBB]);
598 yj_l = Simd4Float(bb_j[1*STRIDE_PBB]);
599 zj_l = Simd4Float(bb_j[2*STRIDE_PBB]);
600 xj_h = Simd4Float(bb_j[3*STRIDE_PBB]);
601 yj_h = Simd4Float(bb_j[4*STRIDE_PBB]);
602 zj_h = Simd4Float(bb_j[5*STRIDE_PBB]);
604 /* Here we "loop" over si (0,STRIDE_PBB) from 0 to nsi with step STRIDE_PBB.
605 * But as we know the number of iterations is 1 or 2, we unroll manually.
607 SUBC_BB_DIST2_SIMD4_XXXX_INNER(0, bb_i, d2);
608 if (STRIDE_PBB < nsi)
610 SUBC_BB_DIST2_SIMD4_XXXX_INNER(STRIDE_PBB, bb_i, d2);
614 #endif /* NBNXN_SEARCH_BB_SIMD4 */
617 /* Returns if any atom pair from two clusters is within distance sqrt(rlist2) */
618 static inline gmx_bool
619 clusterpair_in_range(const NbnxnPairlistGpuWork &work,
621 int csj, int stride, const real *x_j,
624 #if !GMX_SIMD4_HAVE_REAL
627 * All coordinates are stored as xyzxyz...
630 const real *x_i = work.iSuperClusterData.x.data();
632 for (int i = 0; i < c_nbnxnGpuClusterSize; i++)
634 int i0 = (si*c_nbnxnGpuClusterSize + i)*DIM;
635 for (int j = 0; j < c_nbnxnGpuClusterSize; j++)
637 int j0 = (csj*c_nbnxnGpuClusterSize + j)*stride;
639 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]);
650 #else /* !GMX_SIMD4_HAVE_REAL */
652 /* 4-wide SIMD version.
653 * The coordinates x_i are stored as xxxxyyyy..., x_j is stored xyzxyz...
654 * Using 8-wide AVX(2) is not faster on Intel Sandy Bridge and Haswell.
656 static_assert(c_nbnxnGpuClusterSize == 8 || c_nbnxnGpuClusterSize == 4,
657 "A cluster is hard-coded to 4/8 atoms.");
659 Simd4Real rc2_S = Simd4Real(rlist2);
661 const real *x_i = work.iSuperClusterData.xSimd.data();
663 int dim_stride = c_nbnxnGpuClusterSize*DIM;
664 Simd4Real ix_S0 = load4(x_i + si*dim_stride + 0*GMX_SIMD4_WIDTH);
665 Simd4Real iy_S0 = load4(x_i + si*dim_stride + 1*GMX_SIMD4_WIDTH);
666 Simd4Real iz_S0 = load4(x_i + si*dim_stride + 2*GMX_SIMD4_WIDTH);
668 Simd4Real ix_S1, iy_S1, iz_S1;
669 if (c_nbnxnGpuClusterSize == 8)
671 ix_S1 = load4(x_i + si*dim_stride + 3*GMX_SIMD4_WIDTH);
672 iy_S1 = load4(x_i + si*dim_stride + 4*GMX_SIMD4_WIDTH);
673 iz_S1 = load4(x_i + si*dim_stride + 5*GMX_SIMD4_WIDTH);
675 /* We loop from the outer to the inner particles to maximize
676 * the chance that we find a pair in range quickly and return.
678 int j0 = csj*c_nbnxnGpuClusterSize;
679 int j1 = j0 + c_nbnxnGpuClusterSize - 1;
682 Simd4Real jx0_S, jy0_S, jz0_S;
683 Simd4Real jx1_S, jy1_S, jz1_S;
685 Simd4Real dx_S0, dy_S0, dz_S0;
686 Simd4Real dx_S1, dy_S1, dz_S1;
687 Simd4Real dx_S2, dy_S2, dz_S2;
688 Simd4Real dx_S3, dy_S3, dz_S3;
699 Simd4Bool wco_any_S01, wco_any_S23, wco_any_S;
701 jx0_S = Simd4Real(x_j[j0*stride+0]);
702 jy0_S = Simd4Real(x_j[j0*stride+1]);
703 jz0_S = Simd4Real(x_j[j0*stride+2]);
705 jx1_S = Simd4Real(x_j[j1*stride+0]);
706 jy1_S = Simd4Real(x_j[j1*stride+1]);
707 jz1_S = Simd4Real(x_j[j1*stride+2]);
709 /* Calculate distance */
710 dx_S0 = ix_S0 - jx0_S;
711 dy_S0 = iy_S0 - jy0_S;
712 dz_S0 = iz_S0 - jz0_S;
713 dx_S2 = ix_S0 - jx1_S;
714 dy_S2 = iy_S0 - jy1_S;
715 dz_S2 = iz_S0 - jz1_S;
716 if (c_nbnxnGpuClusterSize == 8)
718 dx_S1 = ix_S1 - jx0_S;
719 dy_S1 = iy_S1 - jy0_S;
720 dz_S1 = iz_S1 - jz0_S;
721 dx_S3 = ix_S1 - jx1_S;
722 dy_S3 = iy_S1 - jy1_S;
723 dz_S3 = iz_S1 - jz1_S;
726 /* rsq = dx*dx+dy*dy+dz*dz */
727 rsq_S0 = norm2(dx_S0, dy_S0, dz_S0);
728 rsq_S2 = norm2(dx_S2, dy_S2, dz_S2);
729 if (c_nbnxnGpuClusterSize == 8)
731 rsq_S1 = norm2(dx_S1, dy_S1, dz_S1);
732 rsq_S3 = norm2(dx_S3, dy_S3, dz_S3);
735 wco_S0 = (rsq_S0 < rc2_S);
736 wco_S2 = (rsq_S2 < rc2_S);
737 if (c_nbnxnGpuClusterSize == 8)
739 wco_S1 = (rsq_S1 < rc2_S);
740 wco_S3 = (rsq_S3 < rc2_S);
742 if (c_nbnxnGpuClusterSize == 8)
744 wco_any_S01 = wco_S0 || wco_S1;
745 wco_any_S23 = wco_S2 || wco_S3;
746 wco_any_S = wco_any_S01 || wco_any_S23;
750 wco_any_S = wco_S0 || wco_S2;
753 if (anyTrue(wco_any_S))
764 #endif /* !GMX_SIMD4_HAVE_REAL */
767 /* Returns the j-cluster index for index cjIndex in a cj list */
768 static inline int nblCj(gmx::ArrayRef<const nbnxn_cj_t> cjList,
771 return cjList[cjIndex].cj;
774 /* Returns the j-cluster index for index cjIndex in a cj4 list */
775 static inline int nblCj(gmx::ArrayRef<const nbnxn_cj4_t> cj4List,
778 return cj4List[cjIndex/c_nbnxnGpuJgroupSize].cj[cjIndex & (c_nbnxnGpuJgroupSize - 1)];
781 /* Returns the i-interaction mask of the j sub-cell for index cj_ind */
782 static unsigned int nbl_imask0(const NbnxnPairlistGpu *nbl, int cj_ind)
784 return nbl->cj4[cj_ind/c_nbnxnGpuJgroupSize].imei[0].imask;
787 /* Initializes a single NbnxnPairlistCpu data structure */
788 static void nbnxn_init_pairlist(NbnxnPairlistCpu *nbl)
790 nbl->na_ci = c_nbnxnCpuIClusterSize;
793 nbl->ciOuter.clear();
796 nbl->cjOuter.clear();
799 nbl->work = new NbnxnPairlistCpuWork();
802 NbnxnPairlistGpu::NbnxnPairlistGpu(gmx::PinningPolicy pinningPolicy) :
803 na_ci(c_nbnxnGpuClusterSize),
804 na_cj(c_nbnxnGpuClusterSize),
805 na_sc(c_gpuNumClusterPerCell*c_nbnxnGpuClusterSize),
807 sci({}, {pinningPolicy}),
808 cj4({}, {pinningPolicy}),
809 excl({}, {pinningPolicy}),
812 static_assert(c_nbnxnGpuNumClusterPerSupercluster == c_gpuNumClusterPerCell,
813 "The search code assumes that the a super-cluster matches a search grid cell");
815 static_assert(sizeof(cj4[0].imei[0].imask)*8 >= c_nbnxnGpuJgroupSize*c_gpuNumClusterPerCell,
816 "The i super-cluster cluster interaction mask does not contain a sufficient number of bits");
818 static_assert(sizeof(excl[0])*8 >= c_nbnxnGpuJgroupSize*c_gpuNumClusterPerCell, "The GPU exclusion mask does not contain a sufficient number of bits");
820 // We always want a first entry without any exclusions
823 work = new NbnxnPairlistGpuWork();
826 void nbnxn_init_pairlist_set(nbnxn_pairlist_set_t *nbl_list,
827 gmx_bool bSimple, gmx_bool bCombined)
829 GMX_RELEASE_ASSERT(!bSimple || !bCombined, "Can only combine non-simple lists");
831 nbl_list->bSimple = bSimple;
832 nbl_list->bCombined = bCombined;
834 nbl_list->nnbl = gmx_omp_nthreads_get(emntNonbonded);
836 if (!nbl_list->bCombined &&
837 nbl_list->nnbl > NBNXN_BUFFERFLAG_MAX_THREADS)
839 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.",
840 nbl_list->nnbl, NBNXN_BUFFERFLAG_MAX_THREADS, NBNXN_BUFFERFLAG_MAX_THREADS);
845 snew(nbl_list->nbl, nbl_list->nnbl);
846 if (nbl_list->nnbl > 1)
848 snew(nbl_list->nbl_work, nbl_list->nnbl);
853 snew(nbl_list->nblGpu, nbl_list->nnbl);
855 snew(nbl_list->nbl_fep, nbl_list->nnbl);
856 /* Execute in order to avoid memory interleaving between threads */
857 #pragma omp parallel for num_threads(nbl_list->nnbl) schedule(static)
858 for (int i = 0; i < nbl_list->nnbl; i++)
862 /* Allocate the nblist data structure locally on each thread
863 * to optimize memory access for NUMA architectures.
867 nbl_list->nbl[i] = new NbnxnPairlistCpu();
869 nbnxn_init_pairlist(nbl_list->nbl[i]);
870 if (nbl_list->nnbl > 1)
872 nbl_list->nbl_work[i] = new NbnxnPairlistCpu();
873 nbnxn_init_pairlist(nbl_list->nbl_work[i]);
878 /* Only list 0 is used on the GPU, use normal allocation for i>0 */
879 auto pinningPolicy = (i == 0 ? gmx::PinningPolicy::PinnedIfSupported : gmx::PinningPolicy::CannotBePinned);
881 nbl_list->nblGpu[i] = new NbnxnPairlistGpu(pinningPolicy);
884 snew(nbl_list->nbl_fep[i], 1);
885 nbnxn_init_pairlist_fep(nbl_list->nbl_fep[i]);
887 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
891 /* Print statistics of a pair list, used for debug output */
892 static void print_nblist_statistics(FILE *fp, const NbnxnPairlistCpu *nbl,
893 const nbnxn_search *nbs, real rl)
895 const nbnxn_grid_t *grid;
899 grid = &nbs->grid[0];
901 fprintf(fp, "nbl nci %zu ncj %d\n",
902 nbl->ci.size(), nbl->ncjInUse);
903 fprintf(fp, "nbl na_cj %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n",
904 nbl->na_cj, rl, nbl->ncjInUse, nbl->ncjInUse/static_cast<double>(grid->nc),
905 nbl->ncjInUse/static_cast<double>(grid->nc)*grid->na_cj,
906 nbl->ncjInUse/static_cast<double>(grid->nc)*grid->na_cj/(0.5*4.0/3.0*M_PI*rl*rl*rl*grid->nc*grid->na_cj/(grid->size[XX]*grid->size[YY]*grid->size[ZZ])));
908 fprintf(fp, "nbl average j cell list length %.1f\n",
909 0.25*nbl->ncjInUse/std::max(static_cast<double>(nbl->ci.size()), 1.0));
911 for (int s = 0; s < SHIFTS; s++)
916 for (const nbnxn_ci_t &ciEntry : nbl->ci)
918 cs[ciEntry.shift & NBNXN_CI_SHIFT] +=
919 ciEntry.cj_ind_end - ciEntry.cj_ind_start;
921 int j = ciEntry.cj_ind_start;
922 while (j < ciEntry.cj_ind_end &&
923 nbl->cj[j].excl != NBNXN_INTERACTION_MASK_ALL)
929 fprintf(fp, "nbl cell pairs, total: %zu excl: %d %.1f%%\n",
930 nbl->cj.size(), npexcl, 100*npexcl/std::max(static_cast<double>(nbl->cj.size()), 1.0));
931 for (int s = 0; s < SHIFTS; s++)
935 fprintf(fp, "nbl shift %2d ncj %3d\n", s, cs[s]);
940 /* Print statistics of a pair lists, used for debug output */
941 static void print_nblist_statistics(FILE *fp, const NbnxnPairlistGpu *nbl,
942 const nbnxn_search *nbs, real rl)
944 const nbnxn_grid_t *grid;
946 int c[c_gpuNumClusterPerCell + 1];
947 double sum_nsp, sum_nsp2;
950 /* This code only produces correct statistics with domain decomposition */
951 grid = &nbs->grid[0];
953 fprintf(fp, "nbl nsci %zu ncj4 %zu nsi %d excl4 %zu\n",
954 nbl->sci.size(), nbl->cj4.size(), nbl->nci_tot, nbl->excl.size());
955 fprintf(fp, "nbl na_c %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n",
956 nbl->na_ci, rl, nbl->nci_tot, nbl->nci_tot/static_cast<double>(grid->nsubc_tot),
957 nbl->nci_tot/static_cast<double>(grid->nsubc_tot)*grid->na_c,
958 nbl->nci_tot/static_cast<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])));
963 for (int si = 0; si <= c_gpuNumClusterPerCell; si++)
967 for (const nbnxn_sci_t &sci : nbl->sci)
970 for (int j4 = sci.cj4_ind_start; j4 < sci.cj4_ind_end; j4++)
972 for (int j = 0; j < c_nbnxnGpuJgroupSize; j++)
975 for (int si = 0; si < c_gpuNumClusterPerCell; si++)
977 if (nbl->cj4[j4].imei[0].imask & (1U << (j*c_gpuNumClusterPerCell + si)))
988 nsp_max = std::max(nsp_max, nsp);
990 if (!nbl->sci.empty())
992 sum_nsp /= nbl->sci.size();
993 sum_nsp2 /= nbl->sci.size();
995 fprintf(fp, "nbl #cluster-pairs: av %.1f stddev %.1f max %d\n",
996 sum_nsp, std::sqrt(sum_nsp2 - sum_nsp*sum_nsp), nsp_max);
998 if (!nbl->cj4.empty())
1000 for (b = 0; b <= c_gpuNumClusterPerCell; b++)
1002 fprintf(fp, "nbl j-list #i-subcell %d %7d %4.1f\n",
1003 b, c[b], 100.0*c[b]/size_t {nbl->cj4.size()*c_nbnxnGpuJgroupSize});
1008 /* Returns a pointer to the exclusion mask for j-cluster-group \p cj4 and warp \p warp
1009 * Generates a new exclusion entry when the j-cluster-group uses
1010 * the default all-interaction mask at call time, so the returned mask
1011 * can be modified when needed.
1013 static nbnxn_excl_t *get_exclusion_mask(NbnxnPairlistGpu *nbl,
1017 if (nbl->cj4[cj4].imei[warp].excl_ind == 0)
1019 /* No exclusions set, make a new list entry */
1020 const size_t oldSize = nbl->excl.size();
1021 GMX_ASSERT(oldSize >= 1, "We should always have entry [0]");
1022 /* Add entry with default values: no exclusions */
1023 nbl->excl.resize(oldSize + 1);
1024 nbl->cj4[cj4].imei[warp].excl_ind = oldSize;
1027 return &nbl->excl[nbl->cj4[cj4].imei[warp].excl_ind];
1030 static void set_self_and_newton_excls_supersub(NbnxnPairlistGpu *nbl,
1031 int cj4_ind, int sj_offset,
1032 int i_cluster_in_cell)
1034 nbnxn_excl_t *excl[c_nbnxnGpuClusterpairSplit];
1036 /* Here we only set the set self and double pair exclusions */
1038 /* Reserve extra elements, so the resize() in get_exclusion_mask()
1039 * will not invalidate excl entries in the loop below
1041 nbl->excl.reserve(nbl->excl.size() + c_nbnxnGpuClusterpairSplit);
1042 for (int w = 0; w < c_nbnxnGpuClusterpairSplit; w++)
1044 excl[w] = get_exclusion_mask(nbl, cj4_ind, w);
1047 /* Only minor < major bits set */
1048 for (int ej = 0; ej < nbl->na_ci; ej++)
1051 for (int ei = ej; ei < nbl->na_ci; ei++)
1053 excl[w]->pair[(ej & (c_nbnxnGpuJgroupSize-1))*nbl->na_ci + ei] &=
1054 ~(1U << (sj_offset*c_gpuNumClusterPerCell + i_cluster_in_cell));
1059 /* Returns a diagonal or off-diagonal interaction mask for plain C lists */
1060 static unsigned int get_imask(gmx_bool rdiag, int ci, int cj)
1062 return (rdiag && ci == cj ? NBNXN_INTERACTION_MASK_DIAG : NBNXN_INTERACTION_MASK_ALL);
1065 /* Returns a diagonal or off-diagonal interaction mask for cj-size=2 */
1066 gmx_unused static unsigned int get_imask_simd_j2(gmx_bool rdiag, int ci, int cj)
1068 return (rdiag && ci*2 == cj ? NBNXN_INTERACTION_MASK_DIAG_J2_0 :
1069 (rdiag && ci*2+1 == cj ? NBNXN_INTERACTION_MASK_DIAG_J2_1 :
1070 NBNXN_INTERACTION_MASK_ALL));
1073 /* Returns a diagonal or off-diagonal interaction mask for cj-size=4 */
1074 gmx_unused static unsigned int get_imask_simd_j4(gmx_bool rdiag, int ci, int cj)
1076 return (rdiag && ci == cj ? NBNXN_INTERACTION_MASK_DIAG : NBNXN_INTERACTION_MASK_ALL);
1079 /* Returns a diagonal or off-diagonal interaction mask for cj-size=8 */
1080 gmx_unused static unsigned int get_imask_simd_j8(gmx_bool rdiag, int ci, int cj)
1082 return (rdiag && ci == cj*2 ? NBNXN_INTERACTION_MASK_DIAG_J8_0 :
1083 (rdiag && ci == cj*2+1 ? NBNXN_INTERACTION_MASK_DIAG_J8_1 :
1084 NBNXN_INTERACTION_MASK_ALL));
1088 #if GMX_SIMD_REAL_WIDTH == 2
1089 #define get_imask_simd_4xn get_imask_simd_j2
1091 #if GMX_SIMD_REAL_WIDTH == 4
1092 #define get_imask_simd_4xn get_imask_simd_j4
1094 #if GMX_SIMD_REAL_WIDTH == 8
1095 #define get_imask_simd_4xn get_imask_simd_j8
1096 #define get_imask_simd_2xnn get_imask_simd_j4
1098 #if GMX_SIMD_REAL_WIDTH == 16
1099 #define get_imask_simd_2xnn get_imask_simd_j8
1103 /* Plain C code for checking and adding cluster-pairs to the list.
1105 * \param[in] gridj The j-grid
1106 * \param[in,out] nbl The pair-list to store the cluster pairs in
1107 * \param[in] icluster The index of the i-cluster
1108 * \param[in] jclusterFirst The first cluster in the j-range
1109 * \param[in] jclusterLast The last cluster in the j-range
1110 * \param[in] excludeSubDiagonal Exclude atom pairs with i-index > j-index
1111 * \param[in] x_j Coordinates for the j-atom, in xyz format
1112 * \param[in] rlist2 The squared list cut-off
1113 * \param[in] rbb2 The squared cut-off for putting cluster-pairs in the list based on bounding box distance only
1114 * \param[in,out] numDistanceChecks The number of distance checks performed
1117 makeClusterListSimple(const nbnxn_grid_t &jGrid,
1118 NbnxnPairlistCpu * nbl,
1122 bool excludeSubDiagonal,
1123 const real * gmx_restrict x_j,
1126 int * gmx_restrict numDistanceChecks)
1128 const nbnxn_bb_t * gmx_restrict bb_ci = nbl->work->iClusterData.bb.data();
1129 const real * gmx_restrict x_ci = nbl->work->iClusterData.x.data();
1134 while (!InRange && jclusterFirst <= jclusterLast)
1136 real d2 = subc_bb_dist2(0, bb_ci, jclusterFirst, jGrid.bb);
1137 *numDistanceChecks += 2;
1139 /* Check if the distance is within the distance where
1140 * we use only the bounding box distance rbb,
1141 * or within the cut-off and there is at least one atom pair
1142 * within the cut-off.
1148 else if (d2 < rlist2)
1150 int cjf_gl = jGrid.cell0 + jclusterFirst;
1151 for (int i = 0; i < c_nbnxnCpuIClusterSize && !InRange; i++)
1153 for (int j = 0; j < c_nbnxnCpuIClusterSize; j++)
1155 InRange = InRange ||
1156 (gmx::square(x_ci[i*STRIDE_XYZ+XX] - x_j[(cjf_gl*c_nbnxnCpuIClusterSize+j)*STRIDE_XYZ+XX]) +
1157 gmx::square(x_ci[i*STRIDE_XYZ+YY] - x_j[(cjf_gl*c_nbnxnCpuIClusterSize+j)*STRIDE_XYZ+YY]) +
1158 gmx::square(x_ci[i*STRIDE_XYZ+ZZ] - x_j[(cjf_gl*c_nbnxnCpuIClusterSize+j)*STRIDE_XYZ+ZZ]) < rlist2);
1161 *numDistanceChecks += c_nbnxnCpuIClusterSize*c_nbnxnCpuIClusterSize;
1174 while (!InRange && jclusterLast > jclusterFirst)
1176 real d2 = subc_bb_dist2(0, bb_ci, jclusterLast, jGrid.bb);
1177 *numDistanceChecks += 2;
1179 /* Check if the distance is within the distance where
1180 * we use only the bounding box distance rbb,
1181 * or within the cut-off and there is at least one atom pair
1182 * within the cut-off.
1188 else if (d2 < rlist2)
1190 int cjl_gl = jGrid.cell0 + jclusterLast;
1191 for (int i = 0; i < c_nbnxnCpuIClusterSize && !InRange; i++)
1193 for (int j = 0; j < c_nbnxnCpuIClusterSize; j++)
1195 InRange = InRange ||
1196 (gmx::square(x_ci[i*STRIDE_XYZ+XX] - x_j[(cjl_gl*c_nbnxnCpuIClusterSize+j)*STRIDE_XYZ+XX]) +
1197 gmx::square(x_ci[i*STRIDE_XYZ+YY] - x_j[(cjl_gl*c_nbnxnCpuIClusterSize+j)*STRIDE_XYZ+YY]) +
1198 gmx::square(x_ci[i*STRIDE_XYZ+ZZ] - x_j[(cjl_gl*c_nbnxnCpuIClusterSize+j)*STRIDE_XYZ+ZZ]) < rlist2);
1201 *numDistanceChecks += c_nbnxnCpuIClusterSize*c_nbnxnCpuIClusterSize;
1209 if (jclusterFirst <= jclusterLast)
1211 for (int jcluster = jclusterFirst; jcluster <= jclusterLast; jcluster++)
1213 /* Store cj and the interaction mask */
1215 cjEntry.cj = jGrid.cell0 + jcluster;
1216 cjEntry.excl = get_imask(excludeSubDiagonal, icluster, jcluster);
1217 nbl->cj.push_back(cjEntry);
1219 /* Increase the closing index in the i list */
1220 nbl->ci.back().cj_ind_end = nbl->cj.size();
1224 #ifdef GMX_NBNXN_SIMD_4XN
1225 #include "gromacs/nbnxm/pairlist_simd_4xm.h"
1227 #ifdef GMX_NBNXN_SIMD_2XNN
1228 #include "gromacs/nbnxm/pairlist_simd_2xmm.h"
1231 /* Plain C or SIMD4 code for making a pair list of super-cell sci vs scj.
1232 * Checks bounding box distances and possibly atom pair distances.
1234 static void make_cluster_list_supersub(const nbnxn_grid_t &iGrid,
1235 const nbnxn_grid_t &jGrid,
1236 NbnxnPairlistGpu *nbl,
1239 const bool excludeSubDiagonal,
1244 int *numDistanceChecks)
1246 NbnxnPairlistGpuWork &work = *nbl->work;
1249 const float *pbb_ci = work.iSuperClusterData.bbPacked.data();
1251 const nbnxn_bb_t *bb_ci = work.iSuperClusterData.bb.data();
1254 assert(c_nbnxnGpuClusterSize == iGrid.na_c);
1255 assert(c_nbnxnGpuClusterSize == jGrid.na_c);
1257 /* We generate the pairlist mainly based on bounding-box distances
1258 * and do atom pair distance based pruning on the GPU.
1259 * Only if a j-group contains a single cluster-pair, we try to prune
1260 * that pair based on atom distances on the CPU to avoid empty j-groups.
1262 #define PRUNE_LIST_CPU_ONE 1
1263 #define PRUNE_LIST_CPU_ALL 0
1265 #if PRUNE_LIST_CPU_ONE
1269 float *d2l = work.distanceBuffer.data();
1271 for (int subc = 0; subc < jGrid.nsubc[scj]; subc++)
1273 const int cj4_ind = work.cj_ind/c_nbnxnGpuJgroupSize;
1274 const int cj_offset = work.cj_ind - cj4_ind*c_nbnxnGpuJgroupSize;
1275 const int cj = scj*c_gpuNumClusterPerCell + subc;
1277 const int cj_gl = jGrid.cell0*c_gpuNumClusterPerCell + cj;
1280 if (excludeSubDiagonal && sci == scj)
1286 ci1 = iGrid.nsubc[sci];
1290 /* Determine all ci1 bb distances in one call with SIMD4 */
1291 subc_bb_dist2_simd4_xxxx(jGrid.pbb.data() + (cj >> STRIDE_PBB_2LOG)*NNBSBB_XXXX + (cj & (STRIDE_PBB-1)),
1293 *numDistanceChecks += c_nbnxnGpuClusterSize*2;
1297 unsigned int imask = 0;
1298 /* We use a fixed upper-bound instead of ci1 to help optimization */
1299 for (int ci = 0; ci < c_gpuNumClusterPerCell; ci++)
1307 /* Determine the bb distance between ci and cj */
1308 d2l[ci] = subc_bb_dist2(ci, bb_ci, cj, jGrid.bb);
1309 *numDistanceChecks += 2;
1313 #if PRUNE_LIST_CPU_ALL
1314 /* Check if the distance is within the distance where
1315 * we use only the bounding box distance rbb,
1316 * or within the cut-off and there is at least one atom pair
1317 * within the cut-off. This check is very costly.
1319 *numDistanceChecks += c_nbnxnGpuClusterSize*c_nbnxnGpuClusterSize;
1322 clusterpair_in_range(work, ci, cj_gl, stride, x, rlist2)))
1324 /* Check if the distance between the two bounding boxes
1325 * in within the pair-list cut-off.
1330 /* Flag this i-subcell to be taken into account */
1331 imask |= (1U << (cj_offset*c_gpuNumClusterPerCell + ci));
1333 #if PRUNE_LIST_CPU_ONE
1341 #if PRUNE_LIST_CPU_ONE
1342 /* If we only found 1 pair, check if any atoms are actually
1343 * within the cut-off, so we could get rid of it.
1345 if (npair == 1 && d2l[ci_last] >= rbb2 &&
1346 !clusterpair_in_range(work, ci_last, cj_gl, stride, x, rlist2))
1348 imask &= ~(1U << (cj_offset*c_gpuNumClusterPerCell + ci_last));
1355 /* We have at least one cluster pair: add a j-entry */
1356 if (static_cast<size_t>(cj4_ind) == nbl->cj4.size())
1358 nbl->cj4.resize(nbl->cj4.size() + 1);
1360 nbnxn_cj4_t *cj4 = &nbl->cj4[cj4_ind];
1362 cj4->cj[cj_offset] = cj_gl;
1364 /* Set the exclusions for the ci==sj entry.
1365 * Here we don't bother to check if this entry is actually flagged,
1366 * as it will nearly always be in the list.
1368 if (excludeSubDiagonal && sci == scj)
1370 set_self_and_newton_excls_supersub(nbl, cj4_ind, cj_offset, subc);
1373 /* Copy the cluster interaction mask to the list */
1374 for (int w = 0; w < c_nbnxnGpuClusterpairSplit; w++)
1376 cj4->imei[w].imask |= imask;
1379 nbl->work->cj_ind++;
1381 /* Keep the count */
1382 nbl->nci_tot += npair;
1384 /* Increase the closing index in i super-cell list */
1385 nbl->sci.back().cj4_ind_end =
1386 (nbl->work->cj_ind + c_nbnxnGpuJgroupSize - 1)/c_nbnxnGpuJgroupSize;
1391 /* Returns how many contiguous j-clusters we have starting in the i-list */
1392 template <typename CjListType>
1393 static int numContiguousJClusters(const int cjIndexStart,
1394 const int cjIndexEnd,
1395 gmx::ArrayRef<const CjListType> cjList)
1397 const int firstJCluster = nblCj(cjList, cjIndexStart);
1399 int numContiguous = 0;
1401 while (cjIndexStart + numContiguous < cjIndexEnd &&
1402 nblCj(cjList, cjIndexStart + numContiguous) == firstJCluster + numContiguous)
1407 return numContiguous;
1411 * \brief Helper struct for efficient searching for excluded atoms in a j-list
1415 /*! \brief Constructs a j-list range from \p cjList with the given index range */
1416 template <typename CjListType>
1417 JListRanges(int cjIndexStart,
1419 gmx::ArrayRef<const CjListType> cjList);
1421 int cjIndexStart; //!< The start index in the j-list
1422 int cjIndexEnd; //!< The end index in the j-list
1423 int cjFirst; //!< The j-cluster with index cjIndexStart
1424 int cjLast; //!< The j-cluster with index cjIndexEnd-1
1425 int numDirect; //!< Up to cjIndexStart+numDirect the j-clusters are cjFirst + the index offset
1429 template <typename CjListType>
1430 JListRanges::JListRanges(int cjIndexStart,
1432 gmx::ArrayRef<const CjListType> cjList) :
1433 cjIndexStart(cjIndexStart),
1434 cjIndexEnd(cjIndexEnd)
1436 GMX_ASSERT(cjIndexEnd > cjIndexStart, "JListRanges should only be called with non-empty lists");
1438 cjFirst = nblCj(cjList, cjIndexStart);
1439 cjLast = nblCj(cjList, cjIndexEnd - 1);
1441 /* Determine how many contiguous j-cells we have starting
1442 * from the first i-cell. This number can be used to directly
1443 * calculate j-cell indices for excluded atoms.
1445 numDirect = numContiguousJClusters(cjIndexStart, cjIndexEnd, cjList);
1449 /* Return the index of \p jCluster in the given range or -1 when not present
1451 * Note: This code is executed very often and therefore performance is
1452 * important. It should be inlined and fully optimized.
1454 template <typename CjListType>
1456 findJClusterInJList(int jCluster,
1457 const JListRanges &ranges,
1458 gmx::ArrayRef<const CjListType> cjList)
1462 if (jCluster < ranges.cjFirst + ranges.numDirect)
1464 /* We can calculate the index directly using the offset */
1465 index = ranges.cjIndexStart + jCluster - ranges.cjFirst;
1469 /* Search for jCluster using bisection */
1471 int rangeStart = ranges.cjIndexStart + ranges.numDirect;
1472 int rangeEnd = ranges.cjIndexEnd;
1474 while (index == -1 && rangeStart < rangeEnd)
1476 rangeMiddle = (rangeStart + rangeEnd) >> 1;
1478 const int clusterMiddle = nblCj(cjList, rangeMiddle);
1480 if (jCluster == clusterMiddle)
1482 index = rangeMiddle;
1484 else if (jCluster < clusterMiddle)
1486 rangeEnd = rangeMiddle;
1490 rangeStart = rangeMiddle + 1;
1498 // TODO: Get rid of the two functions below by renaming sci to ci (or something better)
1500 /* Return the i-entry in the list we are currently operating on */
1501 static nbnxn_ci_t *getOpenIEntry(NbnxnPairlistCpu *nbl)
1503 return &nbl->ci.back();
1506 /* Return the i-entry in the list we are currently operating on */
1507 static nbnxn_sci_t *getOpenIEntry(NbnxnPairlistGpu *nbl)
1509 return &nbl->sci.back();
1512 /* Set all atom-pair exclusions for a simple type list i-entry
1514 * Set all atom-pair exclusions from the topology stored in exclusions
1515 * as masks in the pair-list for simple list entry iEntry.
1518 setExclusionsForIEntry(const nbnxn_search *nbs,
1519 NbnxnPairlistCpu *nbl,
1520 gmx_bool diagRemoved,
1522 const nbnxn_ci_t &iEntry,
1523 const t_blocka &exclusions)
1525 if (iEntry.cj_ind_end == iEntry.cj_ind_start)
1527 /* Empty list: no exclusions */
1531 const JListRanges ranges(iEntry.cj_ind_start, iEntry.cj_ind_end, gmx::makeConstArrayRef(nbl->cj));
1533 const int iCluster = iEntry.ci;
1535 gmx::ArrayRef<const int> cell = nbs->cell;
1537 /* Loop over the atoms in the i-cluster */
1538 for (int i = 0; i < nbl->na_ci; i++)
1540 const int iIndex = iCluster*nbl->na_ci + i;
1541 const int iAtom = nbs->a[iIndex];
1544 /* Loop over the topology-based exclusions for this i-atom */
1545 for (int exclIndex = exclusions.index[iAtom]; exclIndex < exclusions.index[iAtom + 1]; exclIndex++)
1547 const int jAtom = exclusions.a[exclIndex];
1551 /* The self exclusion are already set, save some time */
1555 /* Get the index of the j-atom in the nbnxn atom data */
1556 const int jIndex = cell[jAtom];
1558 /* Without shifts we only calculate interactions j>i
1559 * for one-way pair-lists.
1561 if (diagRemoved && jIndex <= iIndex)
1566 const int jCluster = (jIndex >> na_cj_2log);
1568 /* Could the cluster se be in our list? */
1569 if (jCluster >= ranges.cjFirst && jCluster <= ranges.cjLast)
1572 findJClusterInJList(jCluster, ranges,
1573 gmx::makeConstArrayRef(nbl->cj));
1577 /* We found an exclusion, clear the corresponding
1580 const int innerJ = jIndex - (jCluster << na_cj_2log);
1582 nbl->cj[index].excl &= ~(1U << ((i << na_cj_2log) + innerJ));
1590 /* Add a new i-entry to the FEP list and copy the i-properties */
1591 static inline void fep_list_new_nri_copy(t_nblist *nlist)
1593 /* Add a new i-entry */
1596 assert(nlist->nri < nlist->maxnri);
1598 /* Duplicate the last i-entry, except for jindex, which continues */
1599 nlist->iinr[nlist->nri] = nlist->iinr[nlist->nri-1];
1600 nlist->shift[nlist->nri] = nlist->shift[nlist->nri-1];
1601 nlist->gid[nlist->nri] = nlist->gid[nlist->nri-1];
1602 nlist->jindex[nlist->nri] = nlist->nrj;
1605 /* For load balancing of the free-energy lists over threads, we set
1606 * the maximum nrj size of an i-entry to 40. This leads to good
1607 * load balancing in the worst case scenario of a single perturbed
1608 * particle on 16 threads, while not introducing significant overhead.
1609 * Note that half of the perturbed pairs will anyhow end up in very small lists,
1610 * since non perturbed i-particles will see few perturbed j-particles).
1612 const int max_nrj_fep = 40;
1614 /* Exclude the perturbed pairs from the Verlet list. This is only done to avoid
1615 * singularities for overlapping particles (0/0), since the charges and
1616 * LJ parameters have been zeroed in the nbnxn data structure.
1617 * Simultaneously make a group pair list for the perturbed pairs.
1619 static void make_fep_list(const nbnxn_search *nbs,
1620 const nbnxn_atomdata_t *nbat,
1621 NbnxnPairlistCpu *nbl,
1622 gmx_bool bDiagRemoved,
1624 real gmx_unused shx,
1625 real gmx_unused shy,
1626 real gmx_unused shz,
1627 real gmx_unused rlist_fep2,
1628 const nbnxn_grid_t &iGrid,
1629 const nbnxn_grid_t &jGrid,
1632 int ci, cj_ind_start, cj_ind_end, cja, cjr;
1634 int ngid, gid_i = 0, gid_j, gid;
1635 int egp_shift, egp_mask;
1637 int ind_i, ind_j, ai, aj;
1639 gmx_bool bFEP_i, bFEP_i_all;
1641 if (nbl_ci->cj_ind_end == nbl_ci->cj_ind_start)
1649 cj_ind_start = nbl_ci->cj_ind_start;
1650 cj_ind_end = nbl_ci->cj_ind_end;
1652 /* In worst case we have alternating energy groups
1653 * and create #atom-pair lists, which means we need the size
1654 * of a cluster pair (na_ci*na_cj) times the number of cj's.
1656 nri_max = nbl->na_ci*nbl->na_cj*(cj_ind_end - cj_ind_start);
1657 if (nlist->nri + nri_max > nlist->maxnri)
1659 nlist->maxnri = over_alloc_large(nlist->nri + nri_max);
1660 reallocate_nblist(nlist);
1663 const nbnxn_atomdata_t::Params &nbatParams = nbat->params();
1665 ngid = nbatParams.nenergrp;
1667 if (ngid*jGrid.na_cj > gmx::index(sizeof(gid_cj)*8))
1669 gmx_fatal(FARGS, "The Verlet scheme with %dx%d kernels and free-energy only supports up to %zu energy groups",
1670 iGrid.na_c, jGrid.na_cj, (sizeof(gid_cj)*8)/jGrid.na_cj);
1673 egp_shift = nbatParams.neg_2log;
1674 egp_mask = (1 << egp_shift) - 1;
1676 /* Loop over the atoms in the i sub-cell */
1678 for (int i = 0; i < nbl->na_ci; i++)
1680 ind_i = ci*nbl->na_ci + i;
1685 nlist->jindex[nri+1] = nlist->jindex[nri];
1686 nlist->iinr[nri] = ai;
1687 /* The actual energy group pair index is set later */
1688 nlist->gid[nri] = 0;
1689 nlist->shift[nri] = nbl_ci->shift & NBNXN_CI_SHIFT;
1691 bFEP_i = ((iGrid.fep[ci - iGrid.cell0] & (1 << i)) != 0u);
1693 bFEP_i_all = bFEP_i_all && bFEP_i;
1695 if (nlist->nrj + (cj_ind_end - cj_ind_start)*nbl->na_cj > nlist->maxnrj)
1697 nlist->maxnrj = over_alloc_small(nlist->nrj + (cj_ind_end - cj_ind_start)*nbl->na_cj);
1698 srenew(nlist->jjnr, nlist->maxnrj);
1699 srenew(nlist->excl_fep, nlist->maxnrj);
1704 gid_i = (nbatParams.energrp[ci] >> (egp_shift*i)) & egp_mask;
1707 for (int cj_ind = cj_ind_start; cj_ind < cj_ind_end; cj_ind++)
1709 unsigned int fep_cj;
1711 cja = nbl->cj[cj_ind].cj;
1713 if (jGrid.na_cj == jGrid.na_c)
1715 cjr = cja - jGrid.cell0;
1716 fep_cj = jGrid.fep[cjr];
1719 gid_cj = nbatParams.energrp[cja];
1722 else if (2*jGrid.na_cj == jGrid.na_c)
1724 cjr = cja - jGrid.cell0*2;
1725 /* Extract half of the ci fep/energrp mask */
1726 fep_cj = (jGrid.fep[cjr>>1] >> ((cjr&1)*jGrid.na_cj)) & ((1<<jGrid.na_cj) - 1);
1729 gid_cj = nbatParams.energrp[cja>>1] >> ((cja&1)*jGrid.na_cj*egp_shift) & ((1<<(jGrid.na_cj*egp_shift)) - 1);
1734 cjr = cja - (jGrid.cell0>>1);
1735 /* Combine two ci fep masks/energrp */
1736 fep_cj = jGrid.fep[cjr*2] + (jGrid.fep[cjr*2+1] << jGrid.na_c);
1739 gid_cj = nbatParams.energrp[cja*2] + (nbatParams.energrp[cja*2+1] << (jGrid.na_c*egp_shift));
1743 if (bFEP_i || fep_cj != 0)
1745 for (int j = 0; j < nbl->na_cj; j++)
1747 /* Is this interaction perturbed and not excluded? */
1748 ind_j = cja*nbl->na_cj + j;
1751 (bFEP_i || (fep_cj & (1 << j))) &&
1752 (!bDiagRemoved || ind_j >= ind_i))
1756 gid_j = (gid_cj >> (j*egp_shift)) & egp_mask;
1757 gid = GID(gid_i, gid_j, ngid);
1759 if (nlist->nrj > nlist->jindex[nri] &&
1760 nlist->gid[nri] != gid)
1762 /* Energy group pair changed: new list */
1763 fep_list_new_nri_copy(nlist);
1766 nlist->gid[nri] = gid;
1769 if (nlist->nrj - nlist->jindex[nri] >= max_nrj_fep)
1771 fep_list_new_nri_copy(nlist);
1775 /* Add it to the FEP list */
1776 nlist->jjnr[nlist->nrj] = aj;
1777 nlist->excl_fep[nlist->nrj] = (nbl->cj[cj_ind].excl >> (i*nbl->na_cj + j)) & 1;
1780 /* Exclude it from the normal list.
1781 * Note that the charge has been set to zero,
1782 * but we need to avoid 0/0, as perturbed atoms
1783 * can be on top of each other.
1785 nbl->cj[cj_ind].excl &= ~(1U << (i*nbl->na_cj + j));
1791 if (nlist->nrj > nlist->jindex[nri])
1793 /* Actually add this new, non-empty, list */
1795 nlist->jindex[nlist->nri] = nlist->nrj;
1802 /* All interactions are perturbed, we can skip this entry */
1803 nbl_ci->cj_ind_end = cj_ind_start;
1804 nbl->ncjInUse -= cj_ind_end - cj_ind_start;
1808 /* Return the index of atom a within a cluster */
1809 static inline int cj_mod_cj4(int cj)
1811 return cj & (c_nbnxnGpuJgroupSize - 1);
1814 /* Convert a j-cluster to a cj4 group */
1815 static inline int cj_to_cj4(int cj)
1817 return cj/c_nbnxnGpuJgroupSize;
1820 /* Return the index of an j-atom within a warp */
1821 static inline int a_mod_wj(int a)
1823 return a & (c_nbnxnGpuClusterSize/c_nbnxnGpuClusterpairSplit - 1);
1826 /* As make_fep_list above, but for super/sub lists. */
1827 static void make_fep_list(const nbnxn_search *nbs,
1828 const nbnxn_atomdata_t *nbat,
1829 NbnxnPairlistGpu *nbl,
1830 gmx_bool bDiagRemoved,
1831 const nbnxn_sci_t *nbl_sci,
1836 const nbnxn_grid_t &iGrid,
1837 const nbnxn_grid_t &jGrid,
1842 int ind_i, ind_j, ai, aj;
1846 const nbnxn_cj4_t *cj4;
1848 const int numJClusterGroups = nbl_sci->numJClusterGroups();
1849 if (numJClusterGroups == 0)
1855 const int sci = nbl_sci->sci;
1857 const int cj4_ind_start = nbl_sci->cj4_ind_start;
1858 const int cj4_ind_end = nbl_sci->cj4_ind_end;
1860 /* Here we process one super-cell, max #atoms na_sc, versus a list
1861 * cj4 entries, each with max c_nbnxnGpuJgroupSize cj's, each
1862 * of size na_cj atoms.
1863 * On the GPU we don't support energy groups (yet).
1864 * So for each of the na_sc i-atoms, we need max one FEP list
1865 * for each max_nrj_fep j-atoms.
1867 nri_max = nbl->na_sc*nbl->na_cj*(1 + (numJClusterGroups*c_nbnxnGpuJgroupSize)/max_nrj_fep);
1868 if (nlist->nri + nri_max > nlist->maxnri)
1870 nlist->maxnri = over_alloc_large(nlist->nri + nri_max);
1871 reallocate_nblist(nlist);
1874 /* Loop over the atoms in the i super-cluster */
1875 for (int c = 0; c < c_gpuNumClusterPerCell; c++)
1877 c_abs = sci*c_gpuNumClusterPerCell + c;
1879 for (int i = 0; i < nbl->na_ci; i++)
1881 ind_i = c_abs*nbl->na_ci + i;
1886 nlist->jindex[nri+1] = nlist->jindex[nri];
1887 nlist->iinr[nri] = ai;
1888 /* With GPUs, energy groups are not supported */
1889 nlist->gid[nri] = 0;
1890 nlist->shift[nri] = nbl_sci->shift & NBNXN_CI_SHIFT;
1892 bFEP_i = ((iGrid.fep[c_abs - iGrid.cell0*c_gpuNumClusterPerCell] & (1 << i)) != 0u);
1894 xi = nbat->x()[ind_i*nbat->xstride+XX] + shx;
1895 yi = nbat->x()[ind_i*nbat->xstride+YY] + shy;
1896 zi = nbat->x()[ind_i*nbat->xstride+ZZ] + shz;
1898 const int nrjMax = nlist->nrj + numJClusterGroups*c_nbnxnGpuJgroupSize*nbl->na_cj;
1899 if (nrjMax > nlist->maxnrj)
1901 nlist->maxnrj = over_alloc_small(nrjMax);
1902 srenew(nlist->jjnr, nlist->maxnrj);
1903 srenew(nlist->excl_fep, nlist->maxnrj);
1906 for (int cj4_ind = cj4_ind_start; cj4_ind < cj4_ind_end; cj4_ind++)
1908 cj4 = &nbl->cj4[cj4_ind];
1910 for (int gcj = 0; gcj < c_nbnxnGpuJgroupSize; gcj++)
1912 unsigned int fep_cj;
1914 if ((cj4->imei[0].imask & (1U << (gcj*c_gpuNumClusterPerCell + c))) == 0)
1916 /* Skip this ci for this cj */
1921 cj4->cj[gcj] - jGrid.cell0*c_gpuNumClusterPerCell;
1923 fep_cj = jGrid.fep[cjr];
1925 if (bFEP_i || fep_cj != 0)
1927 for (int j = 0; j < nbl->na_cj; j++)
1929 /* Is this interaction perturbed and not excluded? */
1930 ind_j = (jGrid.cell0*c_gpuNumClusterPerCell + cjr)*nbl->na_cj + j;
1933 (bFEP_i || (fep_cj & (1 << j))) &&
1934 (!bDiagRemoved || ind_j >= ind_i))
1937 unsigned int excl_bit;
1940 const int jHalf = j/(c_nbnxnGpuClusterSize/c_nbnxnGpuClusterpairSplit);
1941 nbnxn_excl_t *excl =
1942 get_exclusion_mask(nbl, cj4_ind, jHalf);
1944 excl_pair = a_mod_wj(j)*nbl->na_ci + i;
1945 excl_bit = (1U << (gcj*c_gpuNumClusterPerCell + c));
1947 dx = nbat->x()[ind_j*nbat->xstride+XX] - xi;
1948 dy = nbat->x()[ind_j*nbat->xstride+YY] - yi;
1949 dz = nbat->x()[ind_j*nbat->xstride+ZZ] - zi;
1951 /* The unpruned GPU list has more than 2/3
1952 * of the atom pairs beyond rlist. Using
1953 * this list will cause a lot of overhead
1954 * in the CPU FEP kernels, especially
1955 * relative to the fast GPU kernels.
1956 * So we prune the FEP list here.
1958 if (dx*dx + dy*dy + dz*dz < rlist_fep2)
1960 if (nlist->nrj - nlist->jindex[nri] >= max_nrj_fep)
1962 fep_list_new_nri_copy(nlist);
1966 /* Add it to the FEP list */
1967 nlist->jjnr[nlist->nrj] = aj;
1968 nlist->excl_fep[nlist->nrj] = (excl->pair[excl_pair] & excl_bit) ? 1 : 0;
1972 /* Exclude it from the normal list.
1973 * Note that the charge and LJ parameters have
1974 * been set to zero, but we need to avoid 0/0,
1975 * as perturbed atoms can be on top of each other.
1977 excl->pair[excl_pair] &= ~excl_bit;
1981 /* Note that we could mask out this pair in imask
1982 * if all i- and/or all j-particles are perturbed.
1983 * But since the perturbed pairs on the CPU will
1984 * take an order of magnitude more time, the GPU
1985 * will finish before the CPU and there is no gain.
1991 if (nlist->nrj > nlist->jindex[nri])
1993 /* Actually add this new, non-empty, list */
1995 nlist->jindex[nlist->nri] = nlist->nrj;
2002 /* Set all atom-pair exclusions for a GPU type list i-entry
2004 * Sets all atom-pair exclusions from the topology stored in exclusions
2005 * as masks in the pair-list for i-super-cluster list entry iEntry.
2008 setExclusionsForIEntry(const nbnxn_search *nbs,
2009 NbnxnPairlistGpu *nbl,
2010 gmx_bool diagRemoved,
2011 int gmx_unused na_cj_2log,
2012 const nbnxn_sci_t &iEntry,
2013 const t_blocka &exclusions)
2015 if (iEntry.numJClusterGroups() == 0)
2021 /* Set the search ranges using start and end j-cluster indices.
2022 * Note that here we can not use cj4_ind_end, since the last cj4
2023 * can be only partially filled, so we use cj_ind.
2025 const JListRanges ranges(iEntry.cj4_ind_start*c_nbnxnGpuJgroupSize,
2027 gmx::makeConstArrayRef(nbl->cj4));
2029 GMX_ASSERT(nbl->na_ci == c_nbnxnGpuClusterSize, "na_ci should match the GPU cluster size");
2030 constexpr int c_clusterSize = c_nbnxnGpuClusterSize;
2031 constexpr int c_superClusterSize = c_nbnxnGpuNumClusterPerSupercluster*c_nbnxnGpuClusterSize;
2033 const int iSuperCluster = iEntry.sci;
2035 gmx::ArrayRef<const int> cell = nbs->cell;
2037 /* Loop over the atoms in the i super-cluster */
2038 for (int i = 0; i < c_superClusterSize; i++)
2040 const int iIndex = iSuperCluster*c_superClusterSize + i;
2041 const int iAtom = nbs->a[iIndex];
2044 const int iCluster = i/c_clusterSize;
2046 /* Loop over the topology-based exclusions for this i-atom */
2047 for (int exclIndex = exclusions.index[iAtom]; exclIndex < exclusions.index[iAtom + 1]; exclIndex++)
2049 const int jAtom = exclusions.a[exclIndex];
2053 /* The self exclusions are already set, save some time */
2057 /* Get the index of the j-atom in the nbnxn atom data */
2058 const int jIndex = cell[jAtom];
2060 /* Without shifts we only calculate interactions j>i
2061 * for one-way pair-lists.
2063 /* NOTE: We would like to use iIndex on the right hand side,
2064 * but that makes this routine 25% slower with gcc6/7.
2065 * Even using c_superClusterSize makes it slower.
2066 * Either of these changes triggers peeling of the exclIndex
2067 * loop, which apparently leads to far less efficient code.
2069 if (diagRemoved && jIndex <= iSuperCluster*nbl->na_sc + i)
2074 const int jCluster = jIndex/c_clusterSize;
2076 /* Check whether the cluster is in our list? */
2077 if (jCluster >= ranges.cjFirst && jCluster <= ranges.cjLast)
2080 findJClusterInJList(jCluster, ranges,
2081 gmx::makeConstArrayRef(nbl->cj4));
2085 /* We found an exclusion, clear the corresponding
2088 const unsigned int pairMask = (1U << (cj_mod_cj4(index)*c_gpuNumClusterPerCell + iCluster));
2089 /* Check if the i-cluster interacts with the j-cluster */
2090 if (nbl_imask0(nbl, index) & pairMask)
2092 const int innerI = (i & (c_clusterSize - 1));
2093 const int innerJ = (jIndex & (c_clusterSize - 1));
2095 /* Determine which j-half (CUDA warp) we are in */
2096 const int jHalf = innerJ/(c_clusterSize/c_nbnxnGpuClusterpairSplit);
2098 nbnxn_excl_t *interactionMask =
2099 get_exclusion_mask(nbl, cj_to_cj4(index), jHalf);
2101 interactionMask->pair[a_mod_wj(innerJ)*c_clusterSize + innerI] &= ~pairMask;
2110 /* Make a new ci entry at the back of nbl->ci */
2111 static void addNewIEntry(NbnxnPairlistCpu *nbl, int ci, int shift, int flags)
2115 ciEntry.shift = shift;
2116 /* Store the interaction flags along with the shift */
2117 ciEntry.shift |= flags;
2118 ciEntry.cj_ind_start = nbl->cj.size();
2119 ciEntry.cj_ind_end = nbl->cj.size();
2120 nbl->ci.push_back(ciEntry);
2123 /* Make a new sci entry at index nbl->nsci */
2124 static void addNewIEntry(NbnxnPairlistGpu *nbl, int sci, int shift, int gmx_unused flags)
2126 nbnxn_sci_t sciEntry;
2128 sciEntry.shift = shift;
2129 sciEntry.cj4_ind_start = nbl->cj4.size();
2130 sciEntry.cj4_ind_end = nbl->cj4.size();
2132 nbl->sci.push_back(sciEntry);
2135 /* Sort the simple j-list cj on exclusions.
2136 * Entries with exclusions will all be sorted to the beginning of the list.
2138 static void sort_cj_excl(nbnxn_cj_t *cj, int ncj,
2139 NbnxnPairlistCpuWork *work)
2141 work->cj.resize(ncj);
2143 /* Make a list of the j-cells involving exclusions */
2145 for (int j = 0; j < ncj; j++)
2147 if (cj[j].excl != NBNXN_INTERACTION_MASK_ALL)
2149 work->cj[jnew++] = cj[j];
2152 /* Check if there are exclusions at all or not just the first entry */
2153 if (!((jnew == 0) ||
2154 (jnew == 1 && cj[0].excl != NBNXN_INTERACTION_MASK_ALL)))
2156 for (int j = 0; j < ncj; j++)
2158 if (cj[j].excl == NBNXN_INTERACTION_MASK_ALL)
2160 work->cj[jnew++] = cj[j];
2163 for (int j = 0; j < ncj; j++)
2165 cj[j] = work->cj[j];
2170 /* Close this simple list i entry */
2171 static void closeIEntry(NbnxnPairlistCpu *nbl,
2172 int gmx_unused sp_max_av,
2173 gmx_bool gmx_unused progBal,
2174 float gmx_unused nsp_tot_est,
2175 int gmx_unused thread,
2176 int gmx_unused nthread)
2178 nbnxn_ci_t &ciEntry = nbl->ci.back();
2180 /* All content of the new ci entry have already been filled correctly,
2181 * we only need to sort and increase counts or remove the entry when empty.
2183 const int jlen = ciEntry.cj_ind_end - ciEntry.cj_ind_start;
2186 sort_cj_excl(nbl->cj.data() + ciEntry.cj_ind_start, jlen, nbl->work);
2188 /* The counts below are used for non-bonded pair/flop counts
2189 * and should therefore match the available kernel setups.
2191 if (!(ciEntry.shift & NBNXN_CI_DO_COUL(0)))
2193 nbl->work->ncj_noq += jlen;
2195 else if ((ciEntry.shift & NBNXN_CI_HALF_LJ(0)) ||
2196 !(ciEntry.shift & NBNXN_CI_DO_LJ(0)))
2198 nbl->work->ncj_hlj += jlen;
2203 /* Entry is empty: remove it */
2208 /* Split sci entry for load balancing on the GPU.
2209 * Splitting ensures we have enough lists to fully utilize the whole GPU.
2210 * With progBal we generate progressively smaller lists, which improves
2211 * load balancing. As we only know the current count on our own thread,
2212 * we will need to estimate the current total amount of i-entries.
2213 * As the lists get concatenated later, this estimate depends
2214 * both on nthread and our own thread index.
2216 static void split_sci_entry(NbnxnPairlistGpu *nbl,
2218 gmx_bool progBal, float nsp_tot_est,
2219 int thread, int nthread)
2227 /* Estimate the total numbers of ci's of the nblist combined
2228 * over all threads using the target number of ci's.
2230 nsp_est = (nsp_tot_est*thread)/nthread + nbl->nci_tot;
2232 /* The first ci blocks should be larger, to avoid overhead.
2233 * The last ci blocks should be smaller, to improve load balancing.
2234 * The factor 3/2 makes the first block 3/2 times the target average
2235 * and ensures that the total number of blocks end up equal to
2236 * that of equally sized blocks of size nsp_target_av.
2238 nsp_max = static_cast<int>(nsp_target_av*(nsp_tot_est*1.5/(nsp_est + nsp_tot_est)));
2242 nsp_max = nsp_target_av;
2245 const int cj4_start = nbl->sci.back().cj4_ind_start;
2246 const int cj4_end = nbl->sci.back().cj4_ind_end;
2247 const int j4len = cj4_end - cj4_start;
2249 if (j4len > 1 && j4len*c_gpuNumClusterPerCell*c_nbnxnGpuJgroupSize > nsp_max)
2251 /* Modify the last ci entry and process the cj4's again */
2257 for (int cj4 = cj4_start; cj4 < cj4_end; cj4++)
2259 int nsp_cj4_p = nsp_cj4;
2260 /* Count the number of cluster pairs in this cj4 group */
2262 for (int p = 0; p < c_gpuNumClusterPerCell*c_nbnxnGpuJgroupSize; p++)
2264 nsp_cj4 += (nbl->cj4[cj4].imei[0].imask >> p) & 1;
2267 /* If adding the current cj4 with nsp_cj4 pairs get us further
2268 * away from our target nsp_max, split the list before this cj4.
2270 if (nsp > 0 && nsp_max - nsp < nsp + nsp_cj4 - nsp_max)
2272 /* Split the list at cj4 */
2273 nbl->sci.back().cj4_ind_end = cj4;
2274 /* Create a new sci entry */
2276 sciNew.sci = nbl->sci.back().sci;
2277 sciNew.shift = nbl->sci.back().shift;
2278 sciNew.cj4_ind_start = cj4;
2279 nbl->sci.push_back(sciNew);
2282 nsp_cj4_e = nsp_cj4_p;
2288 /* Put the remaining cj4's in the last sci entry */
2289 nbl->sci.back().cj4_ind_end = cj4_end;
2291 /* Possibly balance out the last two sci's
2292 * by moving the last cj4 of the second last sci.
2294 if (nsp_sci - nsp_cj4_e >= nsp + nsp_cj4_e)
2296 GMX_ASSERT(nbl->sci.size() >= 2, "We expect at least two elements");
2297 nbl->sci[nbl->sci.size() - 2].cj4_ind_end--;
2298 nbl->sci[nbl->sci.size() - 1].cj4_ind_start--;
2303 /* Clost this super/sub list i entry */
2304 static void closeIEntry(NbnxnPairlistGpu *nbl,
2306 gmx_bool progBal, float nsp_tot_est,
2307 int thread, int nthread)
2309 nbnxn_sci_t &sciEntry = *getOpenIEntry(nbl);
2311 /* All content of the new ci entry have already been filled correctly,
2312 * we only need to, potentially, split or remove the entry when empty.
2314 int j4len = sciEntry.numJClusterGroups();
2317 /* We can only have complete blocks of 4 j-entries in a list,
2318 * so round the count up before closing.
2320 int ncj4 = (nbl->work->cj_ind + c_nbnxnGpuJgroupSize - 1)/c_nbnxnGpuJgroupSize;
2321 nbl->work->cj_ind = ncj4*c_nbnxnGpuJgroupSize;
2325 /* Measure the size of the new entry and potentially split it */
2326 split_sci_entry(nbl, nsp_max_av, progBal, nsp_tot_est,
2332 /* Entry is empty: remove it */
2333 nbl->sci.pop_back();
2337 /* Syncs the working array before adding another grid pair to the GPU list */
2338 static void sync_work(NbnxnPairlistCpu gmx_unused *nbl)
2342 /* Syncs the working array before adding another grid pair to the GPU list */
2343 static void sync_work(NbnxnPairlistGpu *nbl)
2345 nbl->work->cj_ind = nbl->cj4.size()*c_nbnxnGpuJgroupSize;
2348 /* Clears an NbnxnPairlistCpu data structure */
2349 static void clear_pairlist(NbnxnPairlistCpu *nbl)
2355 nbl->ciOuter.clear();
2356 nbl->cjOuter.clear();
2358 nbl->work->ncj_noq = 0;
2359 nbl->work->ncj_hlj = 0;
2362 /* Clears an NbnxnPairlistGpu data structure */
2363 static void clear_pairlist(NbnxnPairlistGpu *nbl)
2367 nbl->excl.resize(1);
2371 /* Clears a group scheme pair list */
2372 static void clear_pairlist_fep(t_nblist *nl)
2376 if (nl->jindex == nullptr)
2378 snew(nl->jindex, 1);
2383 /* Sets a simple list i-cell bounding box, including PBC shift */
2384 static inline void set_icell_bb_simple(gmx::ArrayRef<const nbnxn_bb_t> bb,
2386 real shx, real shy, real shz,
2389 bb_ci->lower[BB_X] = bb[ci].lower[BB_X] + shx;
2390 bb_ci->lower[BB_Y] = bb[ci].lower[BB_Y] + shy;
2391 bb_ci->lower[BB_Z] = bb[ci].lower[BB_Z] + shz;
2392 bb_ci->upper[BB_X] = bb[ci].upper[BB_X] + shx;
2393 bb_ci->upper[BB_Y] = bb[ci].upper[BB_Y] + shy;
2394 bb_ci->upper[BB_Z] = bb[ci].upper[BB_Z] + shz;
2397 /* Sets a simple list i-cell bounding box, including PBC shift */
2398 static inline void set_icell_bb(const nbnxn_grid_t &iGrid,
2400 real shx, real shy, real shz,
2401 NbnxnPairlistCpuWork *work)
2403 set_icell_bb_simple(iGrid.bb, ci, shx, shy, shz, &work->iClusterData.bb[0]);
2407 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
2408 static void set_icell_bbxxxx_supersub(gmx::ArrayRef<const float> bb,
2410 real shx, real shy, real shz,
2413 int ia = ci*(c_gpuNumClusterPerCell >> STRIDE_PBB_2LOG)*NNBSBB_XXXX;
2414 for (int m = 0; m < (c_gpuNumClusterPerCell >> STRIDE_PBB_2LOG)*NNBSBB_XXXX; m += NNBSBB_XXXX)
2416 for (int i = 0; i < STRIDE_PBB; i++)
2418 bb_ci[m+0*STRIDE_PBB+i] = bb[ia+m+0*STRIDE_PBB+i] + shx;
2419 bb_ci[m+1*STRIDE_PBB+i] = bb[ia+m+1*STRIDE_PBB+i] + shy;
2420 bb_ci[m+2*STRIDE_PBB+i] = bb[ia+m+2*STRIDE_PBB+i] + shz;
2421 bb_ci[m+3*STRIDE_PBB+i] = bb[ia+m+3*STRIDE_PBB+i] + shx;
2422 bb_ci[m+4*STRIDE_PBB+i] = bb[ia+m+4*STRIDE_PBB+i] + shy;
2423 bb_ci[m+5*STRIDE_PBB+i] = bb[ia+m+5*STRIDE_PBB+i] + shz;
2429 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
2430 gmx_unused static void set_icell_bb_supersub(gmx::ArrayRef<const nbnxn_bb_t> bb,
2432 real shx, real shy, real shz,
2435 for (int i = 0; i < c_gpuNumClusterPerCell; i++)
2437 set_icell_bb_simple(bb, ci*c_gpuNumClusterPerCell+i,
2443 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
2444 gmx_unused static void set_icell_bb(const nbnxn_grid_t &iGrid,
2446 real shx, real shy, real shz,
2447 NbnxnPairlistGpuWork *work)
2450 set_icell_bbxxxx_supersub(iGrid.pbb, ci, shx, shy, shz,
2451 work->iSuperClusterData.bbPacked.data());
2453 set_icell_bb_supersub(iGrid.bb, ci, shx, shy, shz,
2454 work->iSuperClusterData.bb.data());
2458 /* Copies PBC shifted i-cell atom coordinates x,y,z to working array */
2459 static void icell_set_x_simple(int ci,
2460 real shx, real shy, real shz,
2461 int stride, const real *x,
2462 NbnxnPairlistCpuWork::IClusterData *iClusterData)
2464 const int ia = ci*c_nbnxnCpuIClusterSize;
2466 for (int i = 0; i < c_nbnxnCpuIClusterSize; i++)
2468 iClusterData->x[i*STRIDE_XYZ+XX] = x[(ia+i)*stride+XX] + shx;
2469 iClusterData->x[i*STRIDE_XYZ+YY] = x[(ia+i)*stride+YY] + shy;
2470 iClusterData->x[i*STRIDE_XYZ+ZZ] = x[(ia+i)*stride+ZZ] + shz;
2474 static void icell_set_x(int ci,
2475 real shx, real shy, real shz,
2476 int stride, const real *x,
2478 NbnxnPairlistCpuWork *work)
2480 switch (nb_kernel_type)
2483 #ifdef GMX_NBNXN_SIMD_4XN
2484 case nbnxnk4xN_SIMD_4xN:
2485 icell_set_x_simd_4xn(ci, shx, shy, shz, stride, x, work);
2488 #ifdef GMX_NBNXN_SIMD_2XNN
2489 case nbnxnk4xN_SIMD_2xNN:
2490 icell_set_x_simd_2xnn(ci, shx, shy, shz, stride, x, work);
2494 case nbnxnk4x4_PlainC:
2495 icell_set_x_simple(ci, shx, shy, shz, stride, x, &work->iClusterData);
2498 GMX_ASSERT(false, "Unhandled case");
2503 /* Copies PBC shifted super-cell atom coordinates x,y,z to working array */
2504 static void icell_set_x(int ci,
2505 real shx, real shy, real shz,
2506 int stride, const real *x,
2507 int gmx_unused nb_kernel_type,
2508 NbnxnPairlistGpuWork *work)
2510 #if !GMX_SIMD4_HAVE_REAL
2512 real * x_ci = work->iSuperClusterData.x.data();
2514 int ia = ci*c_gpuNumClusterPerCell*c_nbnxnGpuClusterSize;
2515 for (int i = 0; i < c_gpuNumClusterPerCell*c_nbnxnGpuClusterSize; i++)
2517 x_ci[i*DIM + XX] = x[(ia+i)*stride + XX] + shx;
2518 x_ci[i*DIM + YY] = x[(ia+i)*stride + YY] + shy;
2519 x_ci[i*DIM + ZZ] = x[(ia+i)*stride + ZZ] + shz;
2522 #else /* !GMX_SIMD4_HAVE_REAL */
2524 real * x_ci = work->iSuperClusterData.xSimd.data();
2526 for (int si = 0; si < c_gpuNumClusterPerCell; si++)
2528 for (int i = 0; i < c_nbnxnGpuClusterSize; i += GMX_SIMD4_WIDTH)
2530 int io = si*c_nbnxnGpuClusterSize + i;
2531 int ia = ci*c_gpuNumClusterPerCell*c_nbnxnGpuClusterSize + io;
2532 for (int j = 0; j < GMX_SIMD4_WIDTH; j++)
2534 x_ci[io*DIM + j + XX*GMX_SIMD4_WIDTH] = x[(ia + j)*stride + XX] + shx;
2535 x_ci[io*DIM + j + YY*GMX_SIMD4_WIDTH] = x[(ia + j)*stride + YY] + shy;
2536 x_ci[io*DIM + j + ZZ*GMX_SIMD4_WIDTH] = x[(ia + j)*stride + ZZ] + shz;
2541 #endif /* !GMX_SIMD4_HAVE_REAL */
2544 static real minimum_subgrid_size_xy(const nbnxn_grid_t &grid)
2548 return std::min(grid.cellSize[XX], grid.cellSize[YY]);
2552 return std::min(grid.cellSize[XX]/c_gpuNumClusterPerCellX,
2553 grid.cellSize[YY]/c_gpuNumClusterPerCellY);
2557 static real effective_buffer_1x1_vs_MxN(const nbnxn_grid_t &iGrid,
2558 const nbnxn_grid_t &jGrid)
2560 const real eff_1x1_buffer_fac_overest = 0.1;
2562 /* Determine an atom-pair list cut-off buffer size for atom pairs,
2563 * to be added to rlist (including buffer) used for MxN.
2564 * This is for converting an MxN list to a 1x1 list. This means we can't
2565 * use the normal buffer estimate, as we have an MxN list in which
2566 * some atom pairs beyond rlist are missing. We want to capture
2567 * the beneficial effect of buffering by extra pairs just outside rlist,
2568 * while removing the useless pairs that are further away from rlist.
2569 * (Also the buffer could have been set manually not using the estimate.)
2570 * This buffer size is an overestimate.
2571 * We add 10% of the smallest grid sub-cell dimensions.
2572 * Note that the z-size differs per cell and we don't use this,
2573 * so we overestimate.
2574 * With PME, the 10% value gives a buffer that is somewhat larger
2575 * than the effective buffer with a tolerance of 0.005 kJ/mol/ps.
2576 * Smaller tolerances or using RF lead to a smaller effective buffer,
2577 * so 10% gives a safe overestimate.
2579 return eff_1x1_buffer_fac_overest*(minimum_subgrid_size_xy(iGrid) +
2580 minimum_subgrid_size_xy(jGrid));
2583 /* Clusters at the cut-off only increase rlist by 60% of their size */
2584 static real nbnxn_rlist_inc_outside_fac = 0.6;
2586 /* Due to the cluster size the effective pair-list is longer than
2587 * that of a simple atom pair-list. This function gives the extra distance.
2589 real nbnxn_get_rlist_effective_inc(int cluster_size_j, real atom_density)
2592 real vol_inc_i, vol_inc_j;
2594 /* We should get this from the setup, but currently it's the same for
2595 * all setups, including GPUs.
2597 cluster_size_i = c_nbnxnCpuIClusterSize;
2599 vol_inc_i = (cluster_size_i - 1)/atom_density;
2600 vol_inc_j = (cluster_size_j - 1)/atom_density;
2602 return nbnxn_rlist_inc_outside_fac*std::cbrt(vol_inc_i + vol_inc_j);
2605 /* Estimates the interaction volume^2 for non-local interactions */
2606 static real nonlocal_vol2(const struct gmx_domdec_zones_t *zones, const rvec ls, real r)
2614 /* Here we simply add up the volumes of 1, 2 or 3 1D decomposition
2615 * not home interaction volume^2. As these volumes are not additive,
2616 * this is an overestimate, but it would only be significant in the limit
2617 * of small cells, where we anyhow need to split the lists into
2618 * as small parts as possible.
2621 for (int z = 0; z < zones->n; z++)
2623 if (zones->shift[z][XX] + zones->shift[z][YY] + zones->shift[z][ZZ] == 1)
2628 for (int d = 0; d < DIM; d++)
2630 if (zones->shift[z][d] == 0)
2634 za *= zones->size[z].x1[d] - zones->size[z].x0[d];
2638 /* 4 octants of a sphere */
2639 vold_est = 0.25*M_PI*r*r*r*r;
2640 /* 4 quarter pie slices on the edges */
2641 vold_est += 4*cl*M_PI/6.0*r*r*r;
2642 /* One rectangular volume on a face */
2643 vold_est += ca*0.5*r*r;
2645 vol2_est_tot += vold_est*za;
2649 return vol2_est_tot;
2652 /* Estimates the average size of a full j-list for super/sub setup */
2653 static void get_nsubpair_target(const nbnxn_search *nbs,
2656 int min_ci_balanced,
2657 int *nsubpair_target,
2658 float *nsubpair_tot_est)
2660 /* The target value of 36 seems to be the optimum for Kepler.
2661 * Maxwell is less sensitive to the exact value.
2663 const int nsubpair_target_min = 36;
2665 real r_eff_sup, vol_est, nsp_est, nsp_est_nl;
2667 const nbnxn_grid_t &grid = nbs->grid[0];
2669 /* We don't need to balance list sizes if:
2670 * - We didn't request balancing.
2671 * - The number of grid cells >= the number of lists requested,
2672 * since we will always generate at least #cells lists.
2673 * - We don't have any cells, since then there won't be any lists.
2675 if (min_ci_balanced <= 0 || grid.nc >= min_ci_balanced || grid.nc == 0)
2677 /* nsubpair_target==0 signals no balancing */
2678 *nsubpair_target = 0;
2679 *nsubpair_tot_est = 0;
2684 ls[XX] = (grid.c1[XX] - grid.c0[XX])/(grid.numCells[XX]*c_gpuNumClusterPerCellX);
2685 ls[YY] = (grid.c1[YY] - grid.c0[YY])/(grid.numCells[YY]*c_gpuNumClusterPerCellY);
2686 ls[ZZ] = grid.na_c/(grid.atom_density*ls[XX]*ls[YY]);
2688 /* The average length of the diagonal of a sub cell */
2689 real diagonal = std::sqrt(ls[XX]*ls[XX] + ls[YY]*ls[YY] + ls[ZZ]*ls[ZZ]);
2691 /* The formulas below are a heuristic estimate of the average nsj per si*/
2692 r_eff_sup = rlist + nbnxn_rlist_inc_outside_fac*gmx::square((grid.na_c - 1.0)/grid.na_c)*0.5*diagonal;
2694 if (!nbs->DomDec || nbs->zones->n == 1)
2701 gmx::square(grid.atom_density/grid.na_c)*
2702 nonlocal_vol2(nbs->zones, ls, r_eff_sup);
2707 /* Sub-cell interacts with itself */
2708 vol_est = ls[XX]*ls[YY]*ls[ZZ];
2709 /* 6/2 rectangular volume on the faces */
2710 vol_est += (ls[XX]*ls[YY] + ls[XX]*ls[ZZ] + ls[YY]*ls[ZZ])*r_eff_sup;
2711 /* 12/2 quarter pie slices on the edges */
2712 vol_est += 2*(ls[XX] + ls[YY] + ls[ZZ])*0.25*M_PI*gmx::square(r_eff_sup);
2713 /* 4 octants of a sphere */
2714 vol_est += 0.5*4.0/3.0*M_PI*gmx::power3(r_eff_sup);
2716 /* Estimate the number of cluster pairs as the local number of
2717 * clusters times the volume they interact with times the density.
2719 nsp_est = grid.nsubc_tot*vol_est*grid.atom_density/grid.na_c;
2721 /* Subtract the non-local pair count */
2722 nsp_est -= nsp_est_nl;
2724 /* For small cut-offs nsp_est will be an underesimate.
2725 * With DD nsp_est_nl is an overestimate so nsp_est can get negative.
2726 * So to avoid too small or negative nsp_est we set a minimum of
2727 * all cells interacting with all 3^3 direct neighbors (3^3-1)/2+1=14.
2728 * This might be a slight overestimate for small non-periodic groups of
2729 * atoms as will occur for a local domain with DD, but for small
2730 * groups of atoms we'll anyhow be limited by nsubpair_target_min,
2731 * so this overestimation will not matter.
2733 nsp_est = std::max(nsp_est, grid.nsubc_tot*14._real);
2737 fprintf(debug, "nsp_est local %5.1f non-local %5.1f\n",
2738 nsp_est, nsp_est_nl);
2743 nsp_est = nsp_est_nl;
2746 /* Thus the (average) maximum j-list size should be as follows.
2747 * Since there is overhead, we shouldn't make the lists too small
2748 * (and we can't chop up j-groups) so we use a minimum target size of 36.
2750 *nsubpair_target = std::max(nsubpair_target_min,
2751 roundToInt(nsp_est/min_ci_balanced));
2752 *nsubpair_tot_est = static_cast<int>(nsp_est);
2756 fprintf(debug, "nbl nsp estimate %.1f, nsubpair_target %d\n",
2757 nsp_est, *nsubpair_target);
2761 /* Debug list print function */
2762 static void print_nblist_ci_cj(FILE *fp, const NbnxnPairlistCpu *nbl)
2764 for (const nbnxn_ci_t &ciEntry : nbl->ci)
2766 fprintf(fp, "ci %4d shift %2d ncj %3d\n",
2767 ciEntry.ci, ciEntry.shift,
2768 ciEntry.cj_ind_end - ciEntry.cj_ind_start);
2770 for (int j = ciEntry.cj_ind_start; j < ciEntry.cj_ind_end; j++)
2772 fprintf(fp, " cj %5d imask %x\n",
2779 /* Debug list print function */
2780 static void print_nblist_sci_cj(FILE *fp, const NbnxnPairlistGpu *nbl)
2782 for (const nbnxn_sci_t &sci : nbl->sci)
2784 fprintf(fp, "ci %4d shift %2d ncj4 %2d\n",
2786 sci.numJClusterGroups());
2789 for (int j4 = sci.cj4_ind_start; j4 < sci.cj4_ind_end; j4++)
2791 for (int j = 0; j < c_nbnxnGpuJgroupSize; j++)
2793 fprintf(fp, " sj %5d imask %x\n",
2795 nbl->cj4[j4].imei[0].imask);
2796 for (int si = 0; si < c_gpuNumClusterPerCell; si++)
2798 if (nbl->cj4[j4].imei[0].imask & (1U << (j*c_gpuNumClusterPerCell + si)))
2805 fprintf(fp, "ci %4d shift %2d ncj4 %2d ncp %3d\n",
2807 sci.numJClusterGroups(),
2812 /* Combine pair lists *nbl generated on multiple threads nblc */
2813 static void combine_nblists(int nnbl, NbnxnPairlistGpu **nbl,
2814 NbnxnPairlistGpu *nblc)
2816 int nsci = nblc->sci.size();
2817 int ncj4 = nblc->cj4.size();
2818 int nexcl = nblc->excl.size();
2819 for (int i = 0; i < nnbl; i++)
2821 nsci += nbl[i]->sci.size();
2822 ncj4 += nbl[i]->cj4.size();
2823 nexcl += nbl[i]->excl.size();
2826 /* Resize with the final, combined size, so we can fill in parallel */
2827 /* NOTE: For better performance we should use default initialization */
2828 nblc->sci.resize(nsci);
2829 nblc->cj4.resize(ncj4);
2830 nblc->excl.resize(nexcl);
2832 /* Each thread should copy its own data to the combined arrays,
2833 * as otherwise data will go back and forth between different caches.
2835 #if GMX_OPENMP && !(defined __clang_analyzer__)
2836 int nthreads = gmx_omp_nthreads_get(emntPairsearch);
2839 #pragma omp parallel for num_threads(nthreads) schedule(static)
2840 for (int n = 0; n < nnbl; n++)
2844 /* Determine the offset in the combined data for our thread.
2845 * Note that the original sizes in nblc are lost.
2847 int sci_offset = nsci;
2848 int cj4_offset = ncj4;
2849 int excl_offset = nexcl;
2851 for (int i = n; i < nnbl; i++)
2853 sci_offset -= nbl[i]->sci.size();
2854 cj4_offset -= nbl[i]->cj4.size();
2855 excl_offset -= nbl[i]->excl.size();
2858 const NbnxnPairlistGpu &nbli = *nbl[n];
2860 for (size_t i = 0; i < nbli.sci.size(); i++)
2862 nblc->sci[sci_offset + i] = nbli.sci[i];
2863 nblc->sci[sci_offset + i].cj4_ind_start += cj4_offset;
2864 nblc->sci[sci_offset + i].cj4_ind_end += cj4_offset;
2867 for (size_t j4 = 0; j4 < nbli.cj4.size(); j4++)
2869 nblc->cj4[cj4_offset + j4] = nbli.cj4[j4];
2870 nblc->cj4[cj4_offset + j4].imei[0].excl_ind += excl_offset;
2871 nblc->cj4[cj4_offset + j4].imei[1].excl_ind += excl_offset;
2874 for (size_t j4 = 0; j4 < nbli.excl.size(); j4++)
2876 nblc->excl[excl_offset + j4] = nbli.excl[j4];
2879 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
2882 for (int n = 0; n < nnbl; n++)
2884 nblc->nci_tot += nbl[n]->nci_tot;
2888 static void balance_fep_lists(const nbnxn_search *nbs,
2889 nbnxn_pairlist_set_t *nbl_lists)
2892 int nri_tot, nrj_tot, nrj_target;
2896 nnbl = nbl_lists->nnbl;
2900 /* Nothing to balance */
2904 /* Count the total i-lists and pairs */
2907 for (int th = 0; th < nnbl; th++)
2909 nri_tot += nbl_lists->nbl_fep[th]->nri;
2910 nrj_tot += nbl_lists->nbl_fep[th]->nrj;
2913 nrj_target = (nrj_tot + nnbl - 1)/nnbl;
2915 assert(gmx_omp_nthreads_get(emntNonbonded) == nnbl);
2917 #pragma omp parallel for schedule(static) num_threads(nnbl)
2918 for (int th = 0; th < nnbl; th++)
2922 t_nblist *nbl = nbs->work[th].nbl_fep.get();
2924 /* Note that here we allocate for the total size, instead of
2925 * a per-thread esimate (which is hard to obtain).
2927 if (nri_tot > nbl->maxnri)
2929 nbl->maxnri = over_alloc_large(nri_tot);
2930 reallocate_nblist(nbl);
2932 if (nri_tot > nbl->maxnri || nrj_tot > nbl->maxnrj)
2934 nbl->maxnrj = over_alloc_small(nrj_tot);
2935 srenew(nbl->jjnr, nbl->maxnrj);
2936 srenew(nbl->excl_fep, nbl->maxnrj);
2939 clear_pairlist_fep(nbl);
2941 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
2944 /* Loop over the source lists and assign and copy i-entries */
2946 nbld = nbs->work[th_dest].nbl_fep.get();
2947 for (int th = 0; th < nnbl; th++)
2951 nbls = nbl_lists->nbl_fep[th];
2953 for (int i = 0; i < nbls->nri; i++)
2957 /* The number of pairs in this i-entry */
2958 nrj = nbls->jindex[i+1] - nbls->jindex[i];
2960 /* Decide if list th_dest is too large and we should procede
2961 * to the next destination list.
2963 if (th_dest+1 < nnbl && nbld->nrj > 0 &&
2964 nbld->nrj + nrj - nrj_target > nrj_target - nbld->nrj)
2967 nbld = nbs->work[th_dest].nbl_fep.get();
2970 nbld->iinr[nbld->nri] = nbls->iinr[i];
2971 nbld->gid[nbld->nri] = nbls->gid[i];
2972 nbld->shift[nbld->nri] = nbls->shift[i];
2974 for (int j = nbls->jindex[i]; j < nbls->jindex[i+1]; j++)
2976 nbld->jjnr[nbld->nrj] = nbls->jjnr[j];
2977 nbld->excl_fep[nbld->nrj] = nbls->excl_fep[j];
2981 nbld->jindex[nbld->nri] = nbld->nrj;
2985 /* Swap the list pointers */
2986 for (int th = 0; th < nnbl; th++)
2988 t_nblist *nbl_tmp = nbs->work[th].nbl_fep.release();
2989 nbs->work[th].nbl_fep.reset(nbl_lists->nbl_fep[th]);
2990 nbl_lists->nbl_fep[th] = nbl_tmp;
2994 fprintf(debug, "nbl_fep[%d] nri %4d nrj %4d\n",
2996 nbl_lists->nbl_fep[th]->nri,
2997 nbl_lists->nbl_fep[th]->nrj);
3002 /* Returns the next ci to be processes by our thread */
3003 static gmx_bool next_ci(const nbnxn_grid_t &grid,
3004 int nth, int ci_block,
3005 int *ci_x, int *ci_y,
3011 if (*ci_b == ci_block)
3013 /* Jump to the next block assigned to this task */
3014 *ci += (nth - 1)*ci_block;
3023 while (*ci >= grid.cxy_ind[*ci_x*grid.numCells[YY] + *ci_y + 1])
3026 if (*ci_y == grid.numCells[YY])
3036 /* Returns the distance^2 for which we put cell pairs in the list
3037 * without checking atom pair distances. This is usually < rlist^2.
3039 static float boundingbox_only_distance2(const nbnxn_grid_t &iGrid,
3040 const nbnxn_grid_t &jGrid,
3044 /* If the distance between two sub-cell bounding boxes is less
3045 * than this distance, do not check the distance between
3046 * all particle pairs in the sub-cell, since then it is likely
3047 * that the box pair has atom pairs within the cut-off.
3048 * We use the nblist cut-off minus 0.5 times the average x/y diagonal
3049 * spacing of the sub-cells. Around 40% of the checked pairs are pruned.
3050 * Using more than 0.5 gains at most 0.5%.
3051 * If forces are calculated more than twice, the performance gain
3052 * in the force calculation outweighs the cost of checking.
3053 * Note that with subcell lists, the atom-pair distance check
3054 * is only performed when only 1 out of 8 sub-cells in within range,
3055 * this is because the GPU is much faster than the cpu.
3060 bbx = 0.5*(iGrid.cellSize[XX] + jGrid.cellSize[XX]);
3061 bby = 0.5*(iGrid.cellSize[YY] + jGrid.cellSize[YY]);
3064 bbx /= c_gpuNumClusterPerCellX;
3065 bby /= c_gpuNumClusterPerCellY;
3068 rbb2 = std::max(0.0, rlist - 0.5*std::sqrt(bbx*bbx + bby*bby));
3074 return (float)((1+GMX_FLOAT_EPS)*rbb2);
3078 static int get_ci_block_size(const nbnxn_grid_t &iGrid,
3079 gmx_bool bDomDec, int nth)
3081 const int ci_block_enum = 5;
3082 const int ci_block_denom = 11;
3083 const int ci_block_min_atoms = 16;
3086 /* Here we decide how to distribute the blocks over the threads.
3087 * We use prime numbers to try to avoid that the grid size becomes
3088 * a multiple of the number of threads, which would lead to some
3089 * threads getting "inner" pairs and others getting boundary pairs,
3090 * which in turns will lead to load imbalance between threads.
3091 * Set the block size as 5/11/ntask times the average number of cells
3092 * in a y,z slab. This should ensure a quite uniform distribution
3093 * of the grid parts of the different thread along all three grid
3094 * zone boundaries with 3D domain decomposition. At the same time
3095 * the blocks will not become too small.
3097 ci_block = (iGrid.nc*ci_block_enum)/(ci_block_denom*iGrid.numCells[XX]*nth);
3099 /* Ensure the blocks are not too small: avoids cache invalidation */
3100 if (ci_block*iGrid.na_sc < ci_block_min_atoms)
3102 ci_block = (ci_block_min_atoms + iGrid.na_sc - 1)/iGrid.na_sc;
3105 /* Without domain decomposition
3106 * or with less than 3 blocks per task, divide in nth blocks.
3108 if (!bDomDec || nth*3*ci_block > iGrid.nc)
3110 ci_block = (iGrid.nc + nth - 1)/nth;
3113 if (ci_block > 1 && (nth - 1)*ci_block >= iGrid.nc)
3115 /* Some threads have no work. Although reducing the block size
3116 * does not decrease the block count on the first few threads,
3117 * with GPUs better mixing of "upper" cells that have more empty
3118 * clusters results in a somewhat lower max load over all threads.
3119 * Without GPUs the regime of so few atoms per thread is less
3120 * performance relevant, but with 8-wide SIMD the same reasoning
3121 * applies, since the pair list uses 4 i-atom "sub-clusters".
3129 /* Returns the number of bits to right-shift a cluster index to obtain
3130 * the corresponding force buffer flag index.
3132 static int getBufferFlagShift(int numAtomsPerCluster)
3134 int bufferFlagShift = 0;
3135 while ((numAtomsPerCluster << bufferFlagShift) < NBNXN_BUFFERFLAG_SIZE)
3140 return bufferFlagShift;
3143 static bool pairlistIsSimple(const NbnxnPairlistCpu gmx_unused &pairlist)
3148 static bool pairlistIsSimple(const NbnxnPairlistGpu gmx_unused &pairlist)
3153 static void makeClusterListWrapper(NbnxnPairlistCpu *nbl,
3154 const nbnxn_grid_t gmx_unused &iGrid,
3156 const nbnxn_grid_t &jGrid,
3157 const int firstCell,
3159 const bool excludeSubDiagonal,
3160 const nbnxn_atomdata_t *nbat,
3163 const int nb_kernel_type,
3164 int *numDistanceChecks)
3166 switch (nb_kernel_type)
3168 case nbnxnk4x4_PlainC:
3169 makeClusterListSimple(jGrid,
3170 nbl, ci, firstCell, lastCell,
3176 #ifdef GMX_NBNXN_SIMD_4XN
3177 case nbnxnk4xN_SIMD_4xN:
3178 makeClusterListSimd4xn(jGrid,
3179 nbl, ci, firstCell, lastCell,
3186 #ifdef GMX_NBNXN_SIMD_2XNN
3187 case nbnxnk4xN_SIMD_2xNN:
3188 makeClusterListSimd2xnn(jGrid,
3189 nbl, ci, firstCell, lastCell,
3199 static void makeClusterListWrapper(NbnxnPairlistGpu *nbl,
3200 const nbnxn_grid_t &gmx_unused iGrid,
3202 const nbnxn_grid_t &jGrid,
3203 const int firstCell,
3205 const bool excludeSubDiagonal,
3206 const nbnxn_atomdata_t *nbat,
3209 const int gmx_unused nb_kernel_type,
3210 int *numDistanceChecks)
3212 for (int cj = firstCell; cj <= lastCell; cj++)
3214 make_cluster_list_supersub(iGrid, jGrid,
3217 nbat->xstride, nbat->x().data(),
3223 static int getNumSimpleJClustersInList(const NbnxnPairlistCpu &nbl)
3225 return nbl.cj.size();
3228 static int getNumSimpleJClustersInList(const gmx_unused NbnxnPairlistGpu &nbl)
3233 static void incrementNumSimpleJClustersInList(NbnxnPairlistCpu *nbl,
3236 nbl->ncjInUse += nbl->cj.size() - ncj_old_j;
3239 static void incrementNumSimpleJClustersInList(NbnxnPairlistGpu gmx_unused *nbl,
3240 int gmx_unused ncj_old_j)
3244 static void checkListSizeConsistency(const NbnxnPairlistCpu &nbl,
3245 const bool haveFreeEnergy)
3247 GMX_RELEASE_ASSERT(static_cast<size_t>(nbl.ncjInUse) == nbl.cj.size() || haveFreeEnergy,
3248 "Without free-energy all cj pair-list entries should be in use. "
3249 "Note that subsequent code does not make use of the equality, "
3250 "this check is only here to catch bugs");
3253 static void checkListSizeConsistency(const NbnxnPairlistGpu gmx_unused &nbl,
3254 bool gmx_unused haveFreeEnergy)
3256 /* We currently can not check consistency here */
3259 /* Set the buffer flags for newly added entries in the list */
3260 static void setBufferFlags(const NbnxnPairlistCpu &nbl,
3261 const int ncj_old_j,
3262 const int gridj_flag_shift,
3263 gmx_bitmask_t *gridj_flag,
3266 if (gmx::ssize(nbl.cj) > ncj_old_j)
3268 int cbFirst = nbl.cj[ncj_old_j].cj >> gridj_flag_shift;
3269 int cbLast = nbl.cj.back().cj >> gridj_flag_shift;
3270 for (int cb = cbFirst; cb <= cbLast; cb++)
3272 bitmask_init_bit(&gridj_flag[cb], th);
3277 static void setBufferFlags(const NbnxnPairlistGpu gmx_unused &nbl,
3278 int gmx_unused ncj_old_j,
3279 int gmx_unused gridj_flag_shift,
3280 gmx_bitmask_t gmx_unused *gridj_flag,
3283 GMX_ASSERT(false, "This function should never be called");
3286 /* Generates the part of pair-list nbl assigned to our thread */
3287 template <typename T>
3288 static void nbnxn_make_pairlist_part(const nbnxn_search *nbs,
3289 const nbnxn_grid_t &iGrid,
3290 const nbnxn_grid_t &jGrid,
3291 nbnxn_search_work_t *work,
3292 const nbnxn_atomdata_t *nbat,
3293 const t_blocka &exclusions,
3297 gmx_bool bFBufferFlag,
3300 float nsubpair_tot_est,
3307 real rlist2, rl_fep2 = 0;
3309 int ci_b, ci, ci_x, ci_y, ci_xy;
3311 real bx0, bx1, by0, by1, bz0, bz1;
3313 real d2cx, d2z, d2z_cx, d2z_cy, d2zx, d2zxy, d2xy;
3314 int cxf, cxl, cyf, cyf_x, cyl;
3315 int numDistanceChecks;
3316 int gridi_flag_shift = 0, gridj_flag_shift = 0;
3317 gmx_bitmask_t *gridj_flag = nullptr;
3318 int ncj_old_i, ncj_old_j;
3320 nbs_cycle_start(&work->cc[enbsCCsearch]);
3322 if (jGrid.bSimple != pairlistIsSimple(*nbl) ||
3323 iGrid.bSimple != pairlistIsSimple(*nbl))
3325 gmx_incons("Grid incompatible with pair-list");
3329 GMX_ASSERT(nbl->na_ci == jGrid.na_c, "The cluster sizes in the list and grid should match");
3330 nbl->na_cj = nbnxn_kernel_to_cluster_j_size(nb_kernel_type);
3331 na_cj_2log = get_2log(nbl->na_cj);
3337 /* Determine conversion of clusters to flag blocks */
3338 gridi_flag_shift = getBufferFlagShift(nbl->na_ci);
3339 gridj_flag_shift = getBufferFlagShift(nbl->na_cj);
3341 gridj_flag = work->buffer_flags.flag;
3344 copy_mat(nbs->box, box);
3346 rlist2 = nbl->rlist*nbl->rlist;
3348 if (nbs->bFEP && !pairlistIsSimple(*nbl))
3350 /* Determine an atom-pair list cut-off distance for FEP atom pairs.
3351 * We should not simply use rlist, since then we would not have
3352 * the small, effective buffering of the NxN lists.
3353 * The buffer is on overestimate, but the resulting cost for pairs
3354 * beyond rlist is neglible compared to the FEP pairs within rlist.
3356 rl_fep2 = nbl->rlist + effective_buffer_1x1_vs_MxN(iGrid, jGrid);
3360 fprintf(debug, "nbl_fep atom-pair rlist %f\n", rl_fep2);
3362 rl_fep2 = rl_fep2*rl_fep2;
3365 rbb2 = boundingbox_only_distance2(iGrid, jGrid, nbl->rlist, pairlistIsSimple(*nbl));
3369 fprintf(debug, "nbl bounding box only distance %f\n", std::sqrt(rbb2));
3372 const bool isIntraGridList = (&iGrid == &jGrid);
3374 /* Set the shift range */
3375 for (int d = 0; d < DIM; d++)
3377 /* Check if we need periodicity shifts.
3378 * Without PBC or with domain decomposition we don't need them.
3380 if (d >= ePBC2npbcdim(nbs->ePBC) || nbs->dd_dim[d])
3386 const real listRangeCellToCell = listRangeForGridCellToGridCell(rlist, iGrid, jGrid);
3388 box[XX][XX] - fabs(box[YY][XX]) - fabs(box[ZZ][XX]) < listRangeCellToCell)
3398 const bool bSimple = pairlistIsSimple(*nbl);
3399 gmx::ArrayRef<const nbnxn_bb_t> bb_i;
3401 gmx::ArrayRef<const float> pbb_i;
3411 /* We use the normal bounding box format for both grid types */
3414 gmx::ArrayRef<const float> bbcz_i = iGrid.bbcz;
3415 gmx::ArrayRef<const int> flags_i = iGrid.flags;
3416 gmx::ArrayRef<const float> bbcz_j = jGrid.bbcz;
3417 int cell0_i = iGrid.cell0;
3421 fprintf(debug, "nbl nc_i %d col.av. %.1f ci_block %d\n",
3422 iGrid.nc, iGrid.nc/static_cast<double>(iGrid.numCells[XX]*iGrid.numCells[YY]), ci_block);
3425 numDistanceChecks = 0;
3427 const real listRangeBBToJCell2 = gmx::square(listRangeForBoundingBoxToGridCell(rlist, jGrid));
3429 /* Initially ci_b and ci to 1 before where we want them to start,
3430 * as they will both be incremented in next_ci.
3433 ci = th*ci_block - 1;
3436 while (next_ci(iGrid, nth, ci_block, &ci_x, &ci_y, &ci_b, &ci))
3438 if (bSimple && flags_i[ci] == 0)
3443 ncj_old_i = getNumSimpleJClustersInList(*nbl);
3446 if (!isIntraGridList && shp[XX] == 0)
3450 bx1 = bb_i[ci].upper[BB_X];
3454 bx1 = iGrid.c0[XX] + (ci_x+1)*iGrid.cellSize[XX];
3456 if (bx1 < jGrid.c0[XX])
3458 d2cx = gmx::square(jGrid.c0[XX] - bx1);
3460 if (d2cx >= listRangeBBToJCell2)
3467 ci_xy = ci_x*iGrid.numCells[YY] + ci_y;
3469 /* Loop over shift vectors in three dimensions */
3470 for (int tz = -shp[ZZ]; tz <= shp[ZZ]; tz++)
3472 const real shz = tz*box[ZZ][ZZ];
3474 bz0 = bbcz_i[ci*NNBSBB_D ] + shz;
3475 bz1 = bbcz_i[ci*NNBSBB_D+1] + shz;
3483 d2z = gmx::square(bz1);
3487 d2z = gmx::square(bz0 - box[ZZ][ZZ]);
3490 d2z_cx = d2z + d2cx;
3492 if (d2z_cx >= rlist2)
3497 bz1_frac = bz1/(iGrid.cxy_ind[ci_xy+1] - iGrid.cxy_ind[ci_xy]);
3502 /* The check with bz1_frac close to or larger than 1 comes later */
3504 for (int ty = -shp[YY]; ty <= shp[YY]; ty++)
3506 const real shy = ty*box[YY][YY] + tz*box[ZZ][YY];
3510 by0 = bb_i[ci].lower[BB_Y] + shy;
3511 by1 = bb_i[ci].upper[BB_Y] + shy;
3515 by0 = iGrid.c0[YY] + (ci_y )*iGrid.cellSize[YY] + shy;
3516 by1 = iGrid.c0[YY] + (ci_y+1)*iGrid.cellSize[YY] + shy;
3519 get_cell_range<YY>(by0, by1,
3530 if (by1 < jGrid.c0[YY])
3532 d2z_cy += gmx::square(jGrid.c0[YY] - by1);
3534 else if (by0 > jGrid.c1[YY])
3536 d2z_cy += gmx::square(by0 - jGrid.c1[YY]);
3539 for (int tx = -shp[XX]; tx <= shp[XX]; tx++)
3541 const int shift = XYZ2IS(tx, ty, tz);
3543 const bool excludeSubDiagonal = (isIntraGridList && shift == CENTRAL);
3545 if (c_pbcShiftBackward && isIntraGridList && shift > CENTRAL)
3550 const real shx = tx*box[XX][XX] + ty*box[YY][XX] + tz*box[ZZ][XX];
3554 bx0 = bb_i[ci].lower[BB_X] + shx;
3555 bx1 = bb_i[ci].upper[BB_X] + shx;
3559 bx0 = iGrid.c0[XX] + (ci_x )*iGrid.cellSize[XX] + shx;
3560 bx1 = iGrid.c0[XX] + (ci_x+1)*iGrid.cellSize[XX] + shx;
3563 get_cell_range<XX>(bx0, bx1,
3573 addNewIEntry(nbl, cell0_i+ci, shift, flags_i[ci]);
3575 if ((!c_pbcShiftBackward || excludeSubDiagonal) &&
3578 /* Leave the pairs with i > j.
3579 * x is the major index, so skip half of it.
3584 set_icell_bb(iGrid, ci, shx, shy, shz,
3587 icell_set_x(cell0_i+ci, shx, shy, shz,
3588 nbat->xstride, nbat->x().data(),
3592 for (int cx = cxf; cx <= cxl; cx++)
3595 if (jGrid.c0[XX] + cx*jGrid.cellSize[XX] > bx1)
3597 d2zx += gmx::square(jGrid.c0[XX] + cx*jGrid.cellSize[XX] - bx1);
3599 else if (jGrid.c0[XX] + (cx+1)*jGrid.cellSize[XX] < bx0)
3601 d2zx += gmx::square(jGrid.c0[XX] + (cx+1)*jGrid.cellSize[XX] - bx0);
3604 if (isIntraGridList &&
3606 (!c_pbcShiftBackward || shift == CENTRAL) &&
3609 /* Leave the pairs with i > j.
3610 * Skip half of y when i and j have the same x.
3619 for (int cy = cyf_x; cy <= cyl; cy++)
3621 const int columnStart = jGrid.cxy_ind[cx*jGrid.numCells[YY] + cy];
3622 const int columnEnd = jGrid.cxy_ind[cx*jGrid.numCells[YY] + cy + 1];
3625 if (jGrid.c0[YY] + cy*jGrid.cellSize[YY] > by1)
3627 d2zxy += gmx::square(jGrid.c0[YY] + cy*jGrid.cellSize[YY] - by1);
3629 else if (jGrid.c0[YY] + (cy+1)*jGrid.cellSize[YY] < by0)
3631 d2zxy += gmx::square(jGrid.c0[YY] + (cy+1)*jGrid.cellSize[YY] - by0);
3633 if (columnStart < columnEnd && d2zxy < listRangeBBToJCell2)
3635 /* To improve efficiency in the common case
3636 * of a homogeneous particle distribution,
3637 * we estimate the index of the middle cell
3638 * in range (midCell). We search down and up
3639 * starting from this index.
3641 * Note that the bbcz_j array contains bounds
3642 * for i-clusters, thus for clusters of 4 atoms.
3643 * For the common case where the j-cluster size
3644 * is 8, we could step with a stride of 2,
3645 * but we do not do this because it would
3646 * complicate this code even more.
3648 int midCell = columnStart + static_cast<int>(bz1_frac*(columnEnd - columnStart));
3649 if (midCell >= columnEnd)
3651 midCell = columnEnd - 1;
3656 /* Find the lowest cell that can possibly
3658 * Check if we hit the bottom of the grid,
3659 * if the j-cell is below the i-cell and if so,
3660 * if it is within range.
3662 int downTestCell = midCell;
3663 while (downTestCell >= columnStart &&
3664 (bbcz_j[downTestCell*NNBSBB_D + 1] >= bz0 ||
3665 d2xy + gmx::square(bbcz_j[downTestCell*NNBSBB_D + 1] - bz0) < rlist2))
3669 int firstCell = downTestCell + 1;
3671 /* Find the highest cell that can possibly
3673 * Check if we hit the top of the grid,
3674 * if the j-cell is above the i-cell and if so,
3675 * if it is within range.
3677 int upTestCell = midCell + 1;
3678 while (upTestCell < columnEnd &&
3679 (bbcz_j[upTestCell*NNBSBB_D] <= bz1 ||
3680 d2xy + gmx::square(bbcz_j[upTestCell*NNBSBB_D] - bz1) < rlist2))
3684 int lastCell = upTestCell - 1;
3686 #define NBNXN_REFCODE 0
3689 /* Simple reference code, for debugging,
3690 * overrides the more complex code above.
3692 firstCell = columnEnd;
3694 for (int k = columnStart; k < columnEnd; k++)
3696 if (d2xy + gmx::square(bbcz_j[k*NNBSBB_D + 1] - bz0) < rlist2 &&
3701 if (d2xy + gmx::square(bbcz_j[k*NNBSBB_D] - bz1) < rlist2 &&
3710 if (isIntraGridList)
3712 /* We want each atom/cell pair only once,
3713 * only use cj >= ci.
3715 if (!c_pbcShiftBackward || shift == CENTRAL)
3717 firstCell = std::max(firstCell, ci);
3721 if (firstCell <= lastCell)
3723 GMX_ASSERT(firstCell >= columnStart && lastCell < columnEnd, "The range should reside within the current grid column");
3725 /* For f buffer flags with simple lists */
3726 ncj_old_j = getNumSimpleJClustersInList(*nbl);
3728 makeClusterListWrapper(nbl,
3730 jGrid, firstCell, lastCell,
3735 &numDistanceChecks);
3739 setBufferFlags(*nbl, ncj_old_j, gridj_flag_shift,
3743 incrementNumSimpleJClustersInList(nbl, ncj_old_j);
3749 /* Set the exclusions for this ci list */
3750 setExclusionsForIEntry(nbs,
3754 *getOpenIEntry(nbl),
3759 make_fep_list(nbs, nbat, nbl,
3764 iGrid, jGrid, nbl_fep);
3767 /* Close this ci list */
3770 progBal, nsubpair_tot_est,
3776 if (bFBufferFlag && getNumSimpleJClustersInList(*nbl) > ncj_old_i)
3778 bitmask_init_bit(&(work->buffer_flags.flag[(iGrid.cell0+ci) >> gridi_flag_shift]), th);
3782 work->ndistc = numDistanceChecks;
3784 nbs_cycle_stop(&work->cc[enbsCCsearch]);
3786 checkListSizeConsistency(*nbl, nbs->bFEP);
3790 fprintf(debug, "number of distance checks %d\n", numDistanceChecks);
3792 print_nblist_statistics(debug, nbl, nbs, rlist);
3796 fprintf(debug, "nbl FEP list pairs: %d\n", nbl_fep->nrj);
3801 static void reduce_buffer_flags(const nbnxn_search *nbs,
3803 const nbnxn_buffer_flags_t *dest)
3805 for (int s = 0; s < nsrc; s++)
3807 gmx_bitmask_t * flag = nbs->work[s].buffer_flags.flag;
3809 for (int b = 0; b < dest->nflag; b++)
3811 bitmask_union(&(dest->flag[b]), flag[b]);
3816 static void print_reduction_cost(const nbnxn_buffer_flags_t *flags, int nout)
3818 int nelem, nkeep, ncopy, nred, out;
3819 gmx_bitmask_t mask_0;
3825 bitmask_init_bit(&mask_0, 0);
3826 for (int b = 0; b < flags->nflag; b++)
3828 if (bitmask_is_equal(flags->flag[b], mask_0))
3830 /* Only flag 0 is set, no copy of reduction required */
3834 else if (!bitmask_is_zero(flags->flag[b]))
3837 for (out = 0; out < nout; out++)
3839 if (bitmask_is_set(flags->flag[b], out))
3856 fprintf(debug, "nbnxn reduction: #flag %d #list %d elem %4.2f, keep %4.2f copy %4.2f red %4.2f\n",
3858 nelem/static_cast<double>(flags->nflag),
3859 nkeep/static_cast<double>(flags->nflag),
3860 ncopy/static_cast<double>(flags->nflag),
3861 nred/static_cast<double>(flags->nflag));
3864 /* Copies the list entries from src to dest when cjStart <= *cjGlobal < cjEnd.
3865 * *cjGlobal is updated with the cj count in src.
3866 * When setFlags==true, flag bit t is set in flag for all i and j clusters.
3868 template<bool setFlags>
3869 static void copySelectedListRange(const nbnxn_ci_t * gmx_restrict srcCi,
3870 const NbnxnPairlistCpu * gmx_restrict src,
3871 NbnxnPairlistCpu * gmx_restrict dest,
3872 gmx_bitmask_t *flag,
3873 int iFlagShift, int jFlagShift, int t)
3875 const int ncj = srcCi->cj_ind_end - srcCi->cj_ind_start;
3877 dest->ci.push_back(*srcCi);
3878 dest->ci.back().cj_ind_start = dest->cj.size();
3879 dest->ci.back().cj_ind_end = dest->cj.size() + ncj;
3883 bitmask_init_bit(&flag[srcCi->ci >> iFlagShift], t);
3886 for (int j = srcCi->cj_ind_start; j < srcCi->cj_ind_end; j++)
3888 dest->cj.push_back(src->cj[j]);
3892 /* NOTE: This is relatively expensive, since this
3893 * operation is done for all elements in the list,
3894 * whereas at list generation this is done only
3895 * once for each flag entry.
3897 bitmask_init_bit(&flag[src->cj[j].cj >> jFlagShift], t);
3902 /* This routine re-balances the pairlists such that all are nearly equally
3903 * sized. Only whole i-entries are moved between lists. These are moved
3904 * between the ends of the lists, such that the buffer reduction cost should
3905 * not change significantly.
3906 * Note that all original reduction flags are currently kept. This can lead
3907 * to reduction of parts of the force buffer that could be avoided. But since
3908 * the original lists are quite balanced, this will only give minor overhead.
3910 static void rebalanceSimpleLists(int numLists,
3911 NbnxnPairlistCpu * const * const srcSet,
3912 NbnxnPairlistCpu **destSet,
3913 gmx::ArrayRef<nbnxn_search_work_t> searchWork)
3916 for (int s = 0; s < numLists; s++)
3918 ncjTotal += srcSet[s]->ncjInUse;
3920 int ncjTarget = (ncjTotal + numLists - 1)/numLists;
3922 #pragma omp parallel num_threads(numLists)
3924 int t = gmx_omp_get_thread_num();
3926 int cjStart = ncjTarget* t;
3927 int cjEnd = ncjTarget*(t + 1);
3929 /* The destination pair-list for task/thread t */
3930 NbnxnPairlistCpu *dest = destSet[t];
3932 clear_pairlist(dest);
3933 dest->na_cj = srcSet[0]->na_cj;
3935 /* Note that the flags in the work struct (still) contain flags
3936 * for all entries that are present in srcSet->nbl[t].
3938 gmx_bitmask_t *flag = searchWork[t].buffer_flags.flag;
3940 int iFlagShift = getBufferFlagShift(dest->na_ci);
3941 int jFlagShift = getBufferFlagShift(dest->na_cj);
3944 for (int s = 0; s < numLists && cjGlobal < cjEnd; s++)
3946 const NbnxnPairlistCpu *src = srcSet[s];
3948 if (cjGlobal + src->ncjInUse > cjStart)
3950 for (gmx::index i = 0; i < gmx::ssize(src->ci) && cjGlobal < cjEnd; i++)
3952 const nbnxn_ci_t *srcCi = &src->ci[i];
3953 int ncj = srcCi->cj_ind_end - srcCi->cj_ind_start;
3954 if (cjGlobal >= cjStart)
3956 /* If the source list is not our own, we need to set
3957 * extra flags (the template bool parameter).
3961 copySelectedListRange
3964 flag, iFlagShift, jFlagShift, t);
3968 copySelectedListRange
3971 dest, flag, iFlagShift, jFlagShift, t);
3979 cjGlobal += src->ncjInUse;
3983 dest->ncjInUse = dest->cj.size();
3987 int ncjTotalNew = 0;
3988 for (int s = 0; s < numLists; s++)
3990 ncjTotalNew += destSet[s]->ncjInUse;
3992 GMX_RELEASE_ASSERT(ncjTotalNew == ncjTotal, "The total size of the lists before and after rebalancing should match");
3996 /* Returns if the pairlists are so imbalanced that it is worth rebalancing. */
3997 static bool checkRebalanceSimpleLists(const nbnxn_pairlist_set_t *listSet)
3999 int numLists = listSet->nnbl;
4002 for (int s = 0; s < numLists; s++)
4004 ncjMax = std::max(ncjMax, listSet->nbl[s]->ncjInUse);
4005 ncjTotal += listSet->nbl[s]->ncjInUse;
4009 fprintf(debug, "Pair-list ncjMax %d ncjTotal %d\n", ncjMax, ncjTotal);
4011 /* The rebalancing adds 3% extra time to the search. Heuristically we
4012 * determined that under common conditions the non-bonded kernel balance
4013 * improvement will outweigh this when the imbalance is more than 3%.
4014 * But this will, obviously, depend on search vs kernel time and nstlist.
4016 const real rebalanceTolerance = 1.03;
4018 return numLists*ncjMax > ncjTotal*rebalanceTolerance;
4021 /* Perform a count (linear) sort to sort the smaller lists to the end.
4022 * This avoids load imbalance on the GPU, as large lists will be
4023 * scheduled and executed first and the smaller lists later.
4024 * Load balancing between multi-processors only happens at the end
4025 * and there smaller lists lead to more effective load balancing.
4026 * The sorting is done on the cj4 count, not on the actual pair counts.
4027 * Not only does this make the sort faster, but it also results in
4028 * better load balancing than using a list sorted on exact load.
4029 * This function swaps the pointer in the pair list to avoid a copy operation.
4031 static void sort_sci(NbnxnPairlistGpu *nbl)
4033 if (nbl->cj4.size() <= nbl->sci.size())
4035 /* nsci = 0 or all sci have size 1, sorting won't change the order */
4039 NbnxnPairlistGpuWork &work = *nbl->work;
4041 /* We will distinguish differences up to double the average */
4042 const int m = (2*nbl->cj4.size())/nbl->sci.size();
4044 /* Resize work.sci_sort so we can sort into it */
4045 work.sci_sort.resize(nbl->sci.size());
4047 std::vector<int> &sort = work.sortBuffer;
4048 /* Set up m + 1 entries in sort, initialized at 0 */
4050 sort.resize(m + 1, 0);
4051 /* Count the entries of each size */
4052 for (const nbnxn_sci_t &sci : nbl->sci)
4054 int i = std::min(m, sci.numJClusterGroups());
4057 /* Calculate the offset for each count */
4060 for (int i = m - 1; i >= 0; i--)
4063 sort[i] = sort[i + 1] + s0;
4067 /* Sort entries directly into place */
4068 gmx::ArrayRef<nbnxn_sci_t> sci_sort = work.sci_sort;
4069 for (const nbnxn_sci_t &sci : nbl->sci)
4071 int i = std::min(m, sci.numJClusterGroups());
4072 sci_sort[sort[i]++] = sci;
4075 /* Swap the sci pointers so we use the new, sorted list */
4076 std::swap(nbl->sci, work.sci_sort);
4079 /* Make a local or non-local pair-list, depending on iloc */
4080 void nbnxn_make_pairlist(nbnxn_search *nbs,
4081 nbnxn_atomdata_t *nbat,
4082 const t_blocka *excl,
4084 int min_ci_balanced,
4085 nbnxn_pairlist_set_t *nbl_list,
4090 int nsubpair_target;
4091 float nsubpair_tot_est;
4094 gmx_bool CombineNBLists;
4096 int np_tot, np_noq, np_hlj, nap;
4098 nnbl = nbl_list->nnbl;
4099 CombineNBLists = nbl_list->bCombined;
4103 fprintf(debug, "ns making %d nblists\n", nnbl);
4106 nbat->bUseBufferFlags = (nbat->out.size() > 1);
4107 /* We should re-init the flags before making the first list */
4108 if (nbat->bUseBufferFlags && LOCAL_I(iloc))
4110 init_buffer_flags(&nbat->buffer_flags, nbat->numAtoms());
4116 /* Only zone (grid) 0 vs 0 */
4121 nzi = nbs->zones->nizone;
4124 if (!nbl_list->bSimple && min_ci_balanced > 0)
4126 get_nsubpair_target(nbs, iloc, rlist, min_ci_balanced,
4127 &nsubpair_target, &nsubpair_tot_est);
4131 nsubpair_target = 0;
4132 nsubpair_tot_est = 0;
4135 /* Clear all pair-lists */
4136 for (int th = 0; th < nnbl; th++)
4138 if (nbl_list->bSimple)
4140 clear_pairlist(nbl_list->nbl[th]);
4144 clear_pairlist(nbl_list->nblGpu[th]);
4149 clear_pairlist_fep(nbl_list->nbl_fep[th]);
4153 for (int zi = 0; zi < nzi; zi++)
4155 const nbnxn_grid_t &iGrid = nbs->grid[zi];
4166 zj0 = nbs->zones->izone[zi].j0;
4167 zj1 = nbs->zones->izone[zi].j1;
4173 for (int zj = zj0; zj < zj1; zj++)
4175 const nbnxn_grid_t &jGrid = nbs->grid[zj];
4179 fprintf(debug, "ns search grid %d vs %d\n", zi, zj);
4182 nbs_cycle_start(&nbs->cc[enbsCCsearch]);
4184 ci_block = get_ci_block_size(iGrid, nbs->DomDec, nnbl);
4186 /* With GPU: generate progressively smaller lists for
4187 * load balancing for local only or non-local with 2 zones.
4189 progBal = (LOCAL_I(iloc) || nbs->zones->n <= 2);
4191 #pragma omp parallel for num_threads(nnbl) schedule(static)
4192 for (int th = 0; th < nnbl; th++)
4196 /* Re-init the thread-local work flag data before making
4197 * the first list (not an elegant conditional).
4199 if (nbat->bUseBufferFlags && ((zi == 0 && zj == 0)))
4201 init_buffer_flags(&nbs->work[th].buffer_flags, nbat->numAtoms());
4204 if (CombineNBLists && th > 0)
4206 GMX_ASSERT(!nbl_list->bSimple, "Can only combine GPU lists");
4208 clear_pairlist(nbl_list->nblGpu[th]);
4211 /* Divide the i super cell equally over the nblists */
4212 if (nbl_list->bSimple)
4214 nbnxn_make_pairlist_part(nbs, iGrid, jGrid,
4215 &nbs->work[th], nbat, *excl,
4219 nbat->bUseBufferFlags,
4221 progBal, nsubpair_tot_est,
4224 nbl_list->nbl_fep[th]);
4228 nbnxn_make_pairlist_part(nbs, iGrid, jGrid,
4229 &nbs->work[th], nbat, *excl,
4233 nbat->bUseBufferFlags,
4235 progBal, nsubpair_tot_est,
4237 nbl_list->nblGpu[th],
4238 nbl_list->nbl_fep[th]);
4241 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
4243 nbs_cycle_stop(&nbs->cc[enbsCCsearch]);
4248 for (int th = 0; th < nnbl; th++)
4250 inc_nrnb(nrnb, eNR_NBNXN_DIST2, nbs->work[th].ndistc);
4252 if (nbl_list->bSimple)
4254 NbnxnPairlistCpu *nbl = nbl_list->nbl[th];
4255 np_tot += nbl->cj.size();
4256 np_noq += nbl->work->ncj_noq;
4257 np_hlj += nbl->work->ncj_hlj;
4261 NbnxnPairlistGpu *nbl = nbl_list->nblGpu[th];
4262 /* This count ignores potential subsequent pair pruning */
4263 np_tot += nbl->nci_tot;
4266 if (nbl_list->bSimple)
4268 nap = nbl_list->nbl[0]->na_ci*nbl_list->nbl[0]->na_cj;
4272 nap = gmx::square(nbl_list->nblGpu[0]->na_ci);
4274 nbl_list->natpair_ljq = (np_tot - np_noq)*nap - np_hlj*nap/2;
4275 nbl_list->natpair_lj = np_noq*nap;
4276 nbl_list->natpair_q = np_hlj*nap/2;
4278 if (CombineNBLists && nnbl > 1)
4280 GMX_ASSERT(!nbl_list->bSimple, "Can only combine GPU lists");
4281 NbnxnPairlistGpu **nbl = nbl_list->nblGpu;
4283 nbs_cycle_start(&nbs->cc[enbsCCcombine]);
4285 combine_nblists(nnbl-1, nbl+1, nbl[0]);
4287 nbs_cycle_stop(&nbs->cc[enbsCCcombine]);
4292 if (nbl_list->bSimple)
4294 if (nnbl > 1 && checkRebalanceSimpleLists(nbl_list))
4296 rebalanceSimpleLists(nbl_list->nnbl, nbl_list->nbl, nbl_list->nbl_work, nbs->work);
4298 /* Swap the pointer of the sets of pair lists */
4299 NbnxnPairlistCpu **tmp = nbl_list->nbl;
4300 nbl_list->nbl = nbl_list->nbl_work;
4301 nbl_list->nbl_work = tmp;
4306 /* Sort the entries on size, large ones first */
4307 if (CombineNBLists || nnbl == 1)
4309 sort_sci(nbl_list->nblGpu[0]);
4313 #pragma omp parallel for num_threads(nnbl) schedule(static)
4314 for (int th = 0; th < nnbl; th++)
4318 sort_sci(nbl_list->nblGpu[th]);
4320 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
4325 if (nbat->bUseBufferFlags)
4327 reduce_buffer_flags(nbs, nbl_list->nnbl, &nbat->buffer_flags);
4332 /* Balance the free-energy lists over all the threads */
4333 balance_fep_lists(nbs, nbl_list);
4336 if (nbl_list->bSimple)
4338 /* This is a fresh list, so not pruned, stored using ci.
4339 * ciOuter is invalid at this point.
4341 GMX_ASSERT(nbl_list->nbl[0]->ciOuter.empty(), "ciOuter is invalid so it should be empty");
4344 /* Special performance logging stuff (env.var. GMX_NBNXN_CYCLE) */
4347 nbs->search_count++;
4349 if (nbs->print_cycles &&
4350 (!nbs->DomDec || !LOCAL_I(iloc)) &&
4351 nbs->search_count % 100 == 0)
4353 nbs_cycle_print(stderr, nbs);
4356 /* If we have more than one list, they either got rebalancing (CPU)
4357 * or combined (GPU), so we should dump the final result to debug.
4359 if (debug && nbl_list->nnbl > 1)
4361 if (nbl_list->bSimple)
4363 for (int t = 0; t < nbl_list->nnbl; t++)
4365 print_nblist_statistics(debug, nbl_list->nbl[t], nbs, rlist);
4370 print_nblist_statistics(debug, nbl_list->nblGpu[0], nbs, rlist);
4378 if (nbl_list->bSimple)
4380 for (int t = 0; t < nbl_list->nnbl; t++)
4382 print_nblist_ci_cj(debug, nbl_list->nbl[t]);
4387 print_nblist_sci_cj(debug, nbl_list->nblGpu[0]);
4391 if (nbat->bUseBufferFlags)
4393 print_reduction_cost(&nbat->buffer_flags, nbl_list->nnbl);
4398 void nbnxnPrepareListForDynamicPruning(nbnxn_pairlist_set_t *listSet)
4400 GMX_RELEASE_ASSERT(listSet->bSimple, "Should only be called for simple lists");
4402 /* TODO: Restructure the lists so we have actual outer and inner
4403 * list objects so we can set a single pointer instead of
4404 * swapping several pointers.
4407 for (int i = 0; i < listSet->nnbl; i++)
4409 NbnxnPairlistCpu &list = *listSet->nbl[i];
4411 /* The search produced a list in ci/cj.
4412 * Swap the list pointers so we get the outer list is ciOuter,cjOuter
4413 * and we can prune that to get an inner list in ci/cj.
4415 GMX_RELEASE_ASSERT(list.ciOuter.empty() && list.cjOuter.empty(),
4416 "The outer lists should be empty before preparation");
4418 std::swap(list.ci, list.ciOuter);
4419 std::swap(list.cj, list.cjOuter);