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/gpu_data_mgmt.h"
59 #include "gromacs/nbnxm/nbnxm.h"
60 #include "gromacs/nbnxm/nbnxm_geometry.h"
61 #include "gromacs/nbnxm/nbnxm_simd.h"
62 #include "gromacs/nbnxm/pairlistset.h"
63 #include "gromacs/pbcutil/ishift.h"
64 #include "gromacs/pbcutil/pbc.h"
65 #include "gromacs/simd/simd.h"
66 #include "gromacs/simd/vector_operations.h"
67 #include "gromacs/topology/block.h"
68 #include "gromacs/utility/exceptions.h"
69 #include "gromacs/utility/fatalerror.h"
70 #include "gromacs/utility/gmxomp.h"
71 #include "gromacs/utility/smalloc.h"
74 #include "pairlistsets.h"
75 #include "pairlistwork.h"
76 #include "pairsearch.h"
78 using namespace gmx; // TODO: Remove when this file is moved into gmx namespace
80 using BoundingBox = Nbnxm::BoundingBox; // TODO: Remove when refactoring this file
81 using BoundingBox1D = Nbnxm::BoundingBox1D; // TODO: Remove when refactoring this file
83 using Grid = Nbnxm::Grid; // TODO: Remove when refactoring this file
85 // Convience alias for partial Nbnxn namespace usage
86 using InteractionLocality = Nbnxm::InteractionLocality;
88 /* We shift the i-particles backward for PBC.
89 * This leads to more conditionals than shifting forward.
90 * We do this to get more balanced pair lists.
92 constexpr bool c_pbcShiftBackward = true;
94 /* Layout for the nonbonded NxN pair lists */
95 enum class NbnxnLayout
97 NoSimd4x4, // i-cluster size 4, j-cluster size 4
98 Simd4xN, // i-cluster size 4, j-cluster size SIMD width
99 Simd2xNN, // i-cluster size 4, j-cluster size half SIMD width
100 Gpu8x8x8 // i-cluster size 8, j-cluster size 8 + super-clustering
104 /* Returns the j-cluster size */
105 template <NbnxnLayout layout>
106 static constexpr int jClusterSize()
108 static_assert(layout == NbnxnLayout::NoSimd4x4 || layout == NbnxnLayout::Simd4xN || layout == NbnxnLayout::Simd2xNN, "Currently jClusterSize only supports CPU layouts");
110 return layout == NbnxnLayout::Simd4xN ? GMX_SIMD_REAL_WIDTH : (layout == NbnxnLayout::Simd2xNN ? GMX_SIMD_REAL_WIDTH/2 : c_nbnxnCpuIClusterSize);
113 /*! \brief Returns the j-cluster index given the i-cluster index.
115 * \tparam jClusterSize The number of atoms in a j-cluster
116 * \tparam jSubClusterIndex The j-sub-cluster index (0/1), used when size(j-cluster) < size(i-cluster)
117 * \param[in] ci The i-cluster index
119 template <int jClusterSize, int jSubClusterIndex>
120 static inline int cjFromCi(int ci)
122 static_assert(jClusterSize == c_nbnxnCpuIClusterSize/2 || jClusterSize == c_nbnxnCpuIClusterSize || jClusterSize == c_nbnxnCpuIClusterSize*2, "Only j-cluster sizes 2, 4 and 8 are currently implemented");
124 static_assert(jSubClusterIndex == 0 || jSubClusterIndex == 1,
125 "Only sub-cluster indices 0 and 1 are supported");
127 if (jClusterSize == c_nbnxnCpuIClusterSize/2)
129 if (jSubClusterIndex == 0)
135 return ((ci + 1) << 1) - 1;
138 else if (jClusterSize == c_nbnxnCpuIClusterSize)
148 /*! \brief Returns the j-cluster index given the i-cluster index.
150 * \tparam layout The pair-list layout
151 * \tparam jSubClusterIndex The j-sub-cluster index (0/1), used when size(j-cluster) < size(i-cluster)
152 * \param[in] ci The i-cluster index
154 template <NbnxnLayout layout, int jSubClusterIndex>
155 static inline int cjFromCi(int ci)
157 constexpr int clusterSize = jClusterSize<layout>();
159 return cjFromCi<clusterSize, jSubClusterIndex>(ci);
162 /* Returns the nbnxn coordinate data index given the i-cluster index */
163 template <NbnxnLayout layout>
164 static inline int xIndexFromCi(int ci)
166 constexpr int clusterSize = jClusterSize<layout>();
168 static_assert(clusterSize == c_nbnxnCpuIClusterSize/2 || clusterSize == c_nbnxnCpuIClusterSize || clusterSize == c_nbnxnCpuIClusterSize*2, "Only j-cluster sizes 2, 4 and 8 are currently implemented");
170 if (clusterSize <= c_nbnxnCpuIClusterSize)
172 /* Coordinates are stored packed in groups of 4 */
177 /* Coordinates packed in 8, i-cluster size is half the packing width */
178 return (ci >> 1)*STRIDE_P8 + (ci & 1)*(c_packX8 >> 1);
182 /* Returns the nbnxn coordinate data index given the j-cluster index */
183 template <NbnxnLayout layout>
184 static inline int xIndexFromCj(int cj)
186 constexpr int clusterSize = jClusterSize<layout>();
188 static_assert(clusterSize == c_nbnxnCpuIClusterSize/2 || clusterSize == c_nbnxnCpuIClusterSize || clusterSize == c_nbnxnCpuIClusterSize*2, "Only j-cluster sizes 2, 4 and 8 are currently implemented");
190 if (clusterSize == c_nbnxnCpuIClusterSize/2)
192 /* Coordinates are stored packed in groups of 4 */
193 return (cj >> 1)*STRIDE_P4 + (cj & 1)*(c_packX4 >> 1);
195 else if (clusterSize == c_nbnxnCpuIClusterSize)
197 /* Coordinates are stored packed in groups of 4 */
202 /* Coordinates are stored packed in groups of 8 */
209 void nbnxn_init_pairlist_fep(t_nblist *nl)
211 nl->type = GMX_NBLIST_INTERACTION_FREE_ENERGY;
212 nl->igeometry = GMX_NBLIST_GEOMETRY_PARTICLE_PARTICLE;
213 /* The interaction functions are set in the free energy kernel fuction */
226 nl->jindex = nullptr;
228 nl->excl_fep = nullptr;
232 static void init_buffer_flags(nbnxn_buffer_flags_t *flags,
235 flags->nflag = (natoms + NBNXN_BUFFERFLAG_SIZE - 1)/NBNXN_BUFFERFLAG_SIZE;
236 if (flags->nflag > flags->flag_nalloc)
238 flags->flag_nalloc = over_alloc_large(flags->nflag);
239 srenew(flags->flag, flags->flag_nalloc);
241 for (int b = 0; b < flags->nflag; b++)
243 bitmask_clear(&(flags->flag[b]));
247 /* Returns the pair-list cutoff between a bounding box and a grid cell given an atom-to-atom pair-list cutoff
249 * Given a cutoff distance between atoms, this functions returns the cutoff
250 * distance2 between a bounding box of a group of atoms and a grid cell.
251 * Since atoms can be geometrically outside of the cell they have been
252 * assigned to (when atom groups instead of individual atoms are assigned
253 * to cells), this distance returned can be larger than the input.
256 listRangeForBoundingBoxToGridCell(real rlist,
257 const Grid::Dimensions &gridDims)
259 return rlist + gridDims.maxAtomGroupRadius;
262 /* Returns the pair-list cutoff between a grid cells given an atom-to-atom pair-list cutoff
264 * Given a cutoff distance between atoms, this functions returns the cutoff
265 * distance2 between two grid cells.
266 * Since atoms can be geometrically outside of the cell they have been
267 * assigned to (when atom groups instead of individual atoms are assigned
268 * to cells), this distance returned can be larger than the input.
271 listRangeForGridCellToGridCell(real rlist,
272 const Grid::Dimensions &iGridDims,
273 const Grid::Dimensions &jGridDims)
275 return rlist + iGridDims.maxAtomGroupRadius + jGridDims.maxAtomGroupRadius;
278 /* Determines the cell range along one dimension that
279 * the bounding box b0 - b1 sees.
282 static void get_cell_range(real b0, real b1,
283 const Grid::Dimensions &jGridDims,
284 real d2, real rlist, int *cf, int *cl)
286 real listRangeBBToCell2 = gmx::square(listRangeForBoundingBoxToGridCell(rlist, jGridDims));
287 real distanceInCells = (b0 - jGridDims.lowerCorner[dim])*jGridDims.invCellSize[dim];
288 *cf = std::max(static_cast<int>(distanceInCells), 0);
291 d2 + gmx::square((b0 - jGridDims.lowerCorner[dim]) - (*cf - 1 + 1)*jGridDims.cellSize[dim]) < listRangeBBToCell2)
296 *cl = std::min(static_cast<int>((b1 - jGridDims.lowerCorner[dim])*jGridDims.invCellSize[dim]), jGridDims.numCells[dim] - 1);
297 while (*cl < jGridDims.numCells[dim] - 1 &&
298 d2 + gmx::square((*cl + 1)*jGridDims.cellSize[dim] - (b1 - jGridDims.lowerCorner[dim])) < listRangeBBToCell2)
304 /* Reference code calculating the distance^2 between two bounding boxes */
306 static float box_dist2(float bx0, float bx1, float by0,
307 float by1, float bz0, float bz1,
308 const BoundingBox *bb)
311 float dl, dh, dm, dm0;
315 dl = bx0 - bb->upper.x;
316 dh = bb->lower.x - bx1;
317 dm = std::max(dl, dh);
318 dm0 = std::max(dm, 0.0f);
321 dl = by0 - bb->upper.y;
322 dh = bb->lower.y - by1;
323 dm = std::max(dl, dh);
324 dm0 = std::max(dm, 0.0f);
327 dl = bz0 - bb->upper.z;
328 dh = bb->lower.z - bz1;
329 dm = std::max(dl, dh);
330 dm0 = std::max(dm, 0.0f);
337 #if !NBNXN_SEARCH_BB_SIMD4
339 /*! \brief Plain C code calculating the distance^2 between two bounding boxes in xyz0 format
341 * \param[in] bb_i First bounding box
342 * \param[in] bb_j Second bounding box
344 static float clusterBoundingBoxDistance2(const BoundingBox &bb_i,
345 const BoundingBox &bb_j)
347 float dl = bb_i.lower.x - bb_j.upper.x;
348 float dh = bb_j.lower.x - bb_i.upper.x;
349 float dm = std::max(dl, dh);
350 float dm0 = std::max(dm, 0.0f);
353 dl = bb_i.lower.y - bb_j.upper.y;
354 dh = bb_j.lower.y - bb_i.upper.y;
355 dm = std::max(dl, dh);
356 dm0 = std::max(dm, 0.0f);
359 dl = bb_i.lower.z - bb_j.upper.z;
360 dh = bb_j.lower.z - bb_i.upper.z;
361 dm = std::max(dl, dh);
362 dm0 = std::max(dm, 0.0f);
368 #else /* NBNXN_SEARCH_BB_SIMD4 */
370 /*! \brief 4-wide SIMD code calculating the distance^2 between two bounding boxes in xyz0 format
372 * \param[in] bb_i First bounding box, should be aligned for 4-wide SIMD
373 * \param[in] bb_j Second bounding box, should be aligned for 4-wide SIMD
375 static float clusterBoundingBoxDistance2(const BoundingBox &bb_i,
376 const BoundingBox &bb_j)
378 // TODO: During SIMDv2 transition only some archs use namespace (remove when done)
381 const Simd4Float bb_i_S0 = load4(bb_i.lower.ptr());
382 const Simd4Float bb_i_S1 = load4(bb_i.upper.ptr());
383 const Simd4Float bb_j_S0 = load4(bb_j.lower.ptr());
384 const Simd4Float bb_j_S1 = load4(bb_j.upper.ptr());
386 const Simd4Float dl_S = bb_i_S0 - bb_j_S1;
387 const Simd4Float dh_S = bb_j_S0 - bb_i_S1;
389 const Simd4Float dm_S = max(dl_S, dh_S);
390 const Simd4Float dm0_S = max(dm_S, simd4SetZeroF());
392 return dotProduct(dm0_S, dm0_S);
395 /* Calculate bb bounding distances of bb_i[si,...,si+3] and store them in d2 */
396 template <int boundingBoxStart>
397 static inline void gmx_simdcall
398 clusterBoundingBoxDistance2_xxxx_simd4_inner(const float *bb_i,
400 const Simd4Float xj_l,
401 const Simd4Float yj_l,
402 const Simd4Float zj_l,
403 const Simd4Float xj_h,
404 const Simd4Float yj_h,
405 const Simd4Float zj_h)
407 constexpr int stride = c_packedBoundingBoxesDimSize;
409 const int shi = boundingBoxStart*Nbnxm::c_numBoundingBoxBounds1D*DIM;
411 const Simd4Float zero = setZero();
413 const Simd4Float xi_l = load4(bb_i + shi + 0*stride);
414 const Simd4Float yi_l = load4(bb_i + shi + 1*stride);
415 const Simd4Float zi_l = load4(bb_i + shi + 2*stride);
416 const Simd4Float xi_h = load4(bb_i + shi + 3*stride);
417 const Simd4Float yi_h = load4(bb_i + shi + 4*stride);
418 const Simd4Float zi_h = load4(bb_i + shi + 5*stride);
420 const Simd4Float dx_0 = xi_l - xj_h;
421 const Simd4Float dy_0 = yi_l - yj_h;
422 const Simd4Float dz_0 = zi_l - zj_h;
424 const Simd4Float dx_1 = xj_l - xi_h;
425 const Simd4Float dy_1 = yj_l - yi_h;
426 const Simd4Float dz_1 = zj_l - zi_h;
428 const Simd4Float mx = max(dx_0, dx_1);
429 const Simd4Float my = max(dy_0, dy_1);
430 const Simd4Float mz = max(dz_0, dz_1);
432 const Simd4Float m0x = max(mx, zero);
433 const Simd4Float m0y = max(my, zero);
434 const Simd4Float m0z = max(mz, zero);
436 const Simd4Float d2x = m0x * m0x;
437 const Simd4Float d2y = m0y * m0y;
438 const Simd4Float d2z = m0z * m0z;
440 const Simd4Float d2s = d2x + d2y;
441 const Simd4Float d2t = d2s + d2z;
443 store4(d2 + boundingBoxStart, d2t);
446 /* 4-wide SIMD code for nsi bb distances for bb format xxxxyyyyzzzz */
448 clusterBoundingBoxDistance2_xxxx_simd4(const float *bb_j,
453 constexpr int stride = c_packedBoundingBoxesDimSize;
455 // TODO: During SIMDv2 transition only some archs use namespace (remove when done)
458 const Simd4Float xj_l = Simd4Float(bb_j[0*stride]);
459 const Simd4Float yj_l = Simd4Float(bb_j[1*stride]);
460 const Simd4Float zj_l = Simd4Float(bb_j[2*stride]);
461 const Simd4Float xj_h = Simd4Float(bb_j[3*stride]);
462 const Simd4Float yj_h = Simd4Float(bb_j[4*stride]);
463 const Simd4Float zj_h = Simd4Float(bb_j[5*stride]);
465 /* Here we "loop" over si (0,stride) from 0 to nsi with step stride.
466 * But as we know the number of iterations is 1 or 2, we unroll manually.
468 clusterBoundingBoxDistance2_xxxx_simd4_inner<0>(bb_i, d2,
473 clusterBoundingBoxDistance2_xxxx_simd4_inner<stride>(bb_i, d2,
479 #endif /* NBNXN_SEARCH_BB_SIMD4 */
482 /* Returns if any atom pair from two clusters is within distance sqrt(rlist2) */
483 static inline gmx_bool
484 clusterpair_in_range(const NbnxnPairlistGpuWork &work,
486 int csj, int stride, const real *x_j,
489 #if !GMX_SIMD4_HAVE_REAL
492 * All coordinates are stored as xyzxyz...
495 const real *x_i = work.iSuperClusterData.x.data();
497 for (int i = 0; i < c_nbnxnGpuClusterSize; i++)
499 int i0 = (si*c_nbnxnGpuClusterSize + i)*DIM;
500 for (int j = 0; j < c_nbnxnGpuClusterSize; j++)
502 int j0 = (csj*c_nbnxnGpuClusterSize + j)*stride;
504 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]);
515 #else /* !GMX_SIMD4_HAVE_REAL */
517 /* 4-wide SIMD version.
518 * The coordinates x_i are stored as xxxxyyyy..., x_j is stored xyzxyz...
519 * Using 8-wide AVX(2) is not faster on Intel Sandy Bridge and Haswell.
521 static_assert(c_nbnxnGpuClusterSize == 8 || c_nbnxnGpuClusterSize == 4,
522 "A cluster is hard-coded to 4/8 atoms.");
524 Simd4Real rc2_S = Simd4Real(rlist2);
526 const real *x_i = work.iSuperClusterData.xSimd.data();
528 int dim_stride = c_nbnxnGpuClusterSize*DIM;
529 Simd4Real ix_S0 = load4(x_i + si*dim_stride + 0*GMX_SIMD4_WIDTH);
530 Simd4Real iy_S0 = load4(x_i + si*dim_stride + 1*GMX_SIMD4_WIDTH);
531 Simd4Real iz_S0 = load4(x_i + si*dim_stride + 2*GMX_SIMD4_WIDTH);
533 Simd4Real ix_S1, iy_S1, iz_S1;
534 if (c_nbnxnGpuClusterSize == 8)
536 ix_S1 = load4(x_i + si*dim_stride + 3*GMX_SIMD4_WIDTH);
537 iy_S1 = load4(x_i + si*dim_stride + 4*GMX_SIMD4_WIDTH);
538 iz_S1 = load4(x_i + si*dim_stride + 5*GMX_SIMD4_WIDTH);
540 /* We loop from the outer to the inner particles to maximize
541 * the chance that we find a pair in range quickly and return.
543 int j0 = csj*c_nbnxnGpuClusterSize;
544 int j1 = j0 + c_nbnxnGpuClusterSize - 1;
547 Simd4Real jx0_S, jy0_S, jz0_S;
548 Simd4Real jx1_S, jy1_S, jz1_S;
550 Simd4Real dx_S0, dy_S0, dz_S0;
551 Simd4Real dx_S1, dy_S1, dz_S1;
552 Simd4Real dx_S2, dy_S2, dz_S2;
553 Simd4Real dx_S3, dy_S3, dz_S3;
564 Simd4Bool wco_any_S01, wco_any_S23, wco_any_S;
566 jx0_S = Simd4Real(x_j[j0*stride+0]);
567 jy0_S = Simd4Real(x_j[j0*stride+1]);
568 jz0_S = Simd4Real(x_j[j0*stride+2]);
570 jx1_S = Simd4Real(x_j[j1*stride+0]);
571 jy1_S = Simd4Real(x_j[j1*stride+1]);
572 jz1_S = Simd4Real(x_j[j1*stride+2]);
574 /* Calculate distance */
575 dx_S0 = ix_S0 - jx0_S;
576 dy_S0 = iy_S0 - jy0_S;
577 dz_S0 = iz_S0 - jz0_S;
578 dx_S2 = ix_S0 - jx1_S;
579 dy_S2 = iy_S0 - jy1_S;
580 dz_S2 = iz_S0 - jz1_S;
581 if (c_nbnxnGpuClusterSize == 8)
583 dx_S1 = ix_S1 - jx0_S;
584 dy_S1 = iy_S1 - jy0_S;
585 dz_S1 = iz_S1 - jz0_S;
586 dx_S3 = ix_S1 - jx1_S;
587 dy_S3 = iy_S1 - jy1_S;
588 dz_S3 = iz_S1 - jz1_S;
591 /* rsq = dx*dx+dy*dy+dz*dz */
592 rsq_S0 = norm2(dx_S0, dy_S0, dz_S0);
593 rsq_S2 = norm2(dx_S2, dy_S2, dz_S2);
594 if (c_nbnxnGpuClusterSize == 8)
596 rsq_S1 = norm2(dx_S1, dy_S1, dz_S1);
597 rsq_S3 = norm2(dx_S3, dy_S3, dz_S3);
600 wco_S0 = (rsq_S0 < rc2_S);
601 wco_S2 = (rsq_S2 < rc2_S);
602 if (c_nbnxnGpuClusterSize == 8)
604 wco_S1 = (rsq_S1 < rc2_S);
605 wco_S3 = (rsq_S3 < rc2_S);
607 if (c_nbnxnGpuClusterSize == 8)
609 wco_any_S01 = wco_S0 || wco_S1;
610 wco_any_S23 = wco_S2 || wco_S3;
611 wco_any_S = wco_any_S01 || wco_any_S23;
615 wco_any_S = wco_S0 || wco_S2;
618 if (anyTrue(wco_any_S))
629 #endif /* !GMX_SIMD4_HAVE_REAL */
632 /* Returns the j-cluster index for index cjIndex in a cj list */
633 static inline int nblCj(gmx::ArrayRef<const nbnxn_cj_t> cjList,
636 return cjList[cjIndex].cj;
639 /* Returns the j-cluster index for index cjIndex in a cj4 list */
640 static inline int nblCj(gmx::ArrayRef<const nbnxn_cj4_t> cj4List,
643 return cj4List[cjIndex/c_nbnxnGpuJgroupSize].cj[cjIndex & (c_nbnxnGpuJgroupSize - 1)];
646 /* Returns the i-interaction mask of the j sub-cell for index cj_ind */
647 static unsigned int nbl_imask0(const NbnxnPairlistGpu *nbl, int cj_ind)
649 return nbl->cj4[cj_ind/c_nbnxnGpuJgroupSize].imei[0].imask;
652 NbnxnPairlistCpu::NbnxnPairlistCpu() :
653 na_ci(c_nbnxnCpuIClusterSize),
658 work(std::make_unique<NbnxnPairlistCpuWork>())
662 NbnxnPairlistGpu::NbnxnPairlistGpu(gmx::PinningPolicy pinningPolicy) :
663 na_ci(c_nbnxnGpuClusterSize),
664 na_cj(c_nbnxnGpuClusterSize),
665 na_sc(c_gpuNumClusterPerCell*c_nbnxnGpuClusterSize),
667 sci({}, {pinningPolicy}),
668 cj4({}, {pinningPolicy}),
669 excl({}, {pinningPolicy}),
671 work(std::make_unique<NbnxnPairlistGpuWork>())
673 static_assert(c_nbnxnGpuNumClusterPerSupercluster == c_gpuNumClusterPerCell,
674 "The search code assumes that the a super-cluster matches a search grid cell");
676 static_assert(sizeof(cj4[0].imei[0].imask)*8 >= c_nbnxnGpuJgroupSize*c_gpuNumClusterPerCell,
677 "The i super-cluster cluster interaction mask does not contain a sufficient number of bits");
679 static_assert(sizeof(excl[0])*8 >= c_nbnxnGpuJgroupSize*c_gpuNumClusterPerCell, "The GPU exclusion mask does not contain a sufficient number of bits");
681 // We always want a first entry without any exclusions
685 // TODO: Move to pairlistset.cpp
686 PairlistSet::PairlistSet(const Nbnxm::InteractionLocality locality,
687 const PairlistParams &pairlistParams) :
689 params_(pairlistParams)
692 (params_.pairlistType == PairlistType::Simple4x2 ||
693 params_.pairlistType == PairlistType::Simple4x4 ||
694 params_.pairlistType == PairlistType::Simple4x8);
695 // Currently GPU lists are always combined
696 combineLists_ = !isCpuType_;
698 const int numLists = gmx_omp_nthreads_get(emntNonbonded);
700 if (!combineLists_ &&
701 numLists > NBNXN_BUFFERFLAG_MAX_THREADS)
703 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.",
704 numLists, NBNXN_BUFFERFLAG_MAX_THREADS, NBNXN_BUFFERFLAG_MAX_THREADS);
709 cpuLists_.resize(numLists);
712 cpuListsWork_.resize(numLists);
717 /* Only list 0 is used on the GPU, use normal allocation for i>0 */
718 gpuLists_.emplace_back(gmx::PinningPolicy::PinnedIfSupported);
719 /* Lists 0 to numLists are use for constructing lists in parallel
720 * on the CPU using numLists threads (and then merged into list 0).
722 for (int i = 1; i < numLists; i++)
724 gpuLists_.emplace_back(gmx::PinningPolicy::CannotBePinned);
729 fepLists_.resize(numLists);
731 /* Execute in order to avoid memory interleaving between threads */
732 #pragma omp parallel for num_threads(numLists) schedule(static)
733 for (int i = 0; i < numLists; i++)
737 /* We used to allocate all normal lists locally on each thread
738 * as well. The question is if allocating the object on the
739 * master thread (but all contained list memory thread local)
740 * impacts performance.
742 snew(fepLists_[i], 1);
743 nbnxn_init_pairlist_fep(fepLists_[i]);
745 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
750 /* Print statistics of a pair list, used for debug output */
751 static void print_nblist_statistics(FILE *fp,
752 const NbnxnPairlistCpu &nbl,
753 const PairSearch &pairSearch,
756 const Grid &grid = pairSearch.gridSet().grids()[0];
757 const Grid::Dimensions &dims = grid.dimensions();
759 fprintf(fp, "nbl nci %zu ncj %d\n",
760 nbl.ci.size(), nbl.ncjInUse);
761 const int numAtomsJCluster = grid.geometry().numAtomsJCluster;
762 const double numAtomsPerCell = nbl.ncjInUse/static_cast<double>(grid.numCells())*numAtomsJCluster;
763 fprintf(fp, "nbl na_cj %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n",
764 nbl.na_cj, rl, nbl.ncjInUse, nbl.ncjInUse/static_cast<double>(grid.numCells()),
766 numAtomsPerCell/(0.5*4.0/3.0*M_PI*rl*rl*rl*grid.numCells()*numAtomsJCluster/(dims.gridSize[XX]*dims.gridSize[YY]*dims.gridSize[ZZ])));
768 fprintf(fp, "nbl average j cell list length %.1f\n",
769 0.25*nbl.ncjInUse/std::max(static_cast<double>(nbl.ci.size()), 1.0));
771 int cs[SHIFTS] = { 0 };
773 for (const nbnxn_ci_t &ciEntry : nbl.ci)
775 cs[ciEntry.shift & NBNXN_CI_SHIFT] +=
776 ciEntry.cj_ind_end - ciEntry.cj_ind_start;
778 int j = ciEntry.cj_ind_start;
779 while (j < ciEntry.cj_ind_end &&
780 nbl.cj[j].excl != NBNXN_INTERACTION_MASK_ALL)
786 fprintf(fp, "nbl cell pairs, total: %zu excl: %d %.1f%%\n",
787 nbl.cj.size(), npexcl, 100*npexcl/std::max(static_cast<double>(nbl.cj.size()), 1.0));
788 for (int s = 0; s < SHIFTS; s++)
792 fprintf(fp, "nbl shift %2d ncj %3d\n", s, cs[s]);
797 /* Print statistics of a pair lists, used for debug output */
798 static void print_nblist_statistics(FILE *fp,
799 const NbnxnPairlistGpu &nbl,
800 const PairSearch &pairSearch,
803 const Grid &grid = pairSearch.gridSet().grids()[0];
804 const Grid::Dimensions &dims = grid.dimensions();
806 fprintf(fp, "nbl nsci %zu ncj4 %zu nsi %d excl4 %zu\n",
807 nbl.sci.size(), nbl.cj4.size(), nbl.nci_tot, nbl.excl.size());
808 const int numAtomsCluster = grid.geometry().numAtomsICluster;
809 const double numAtomsPerCell = nbl.nci_tot/static_cast<double>(grid.numClusters())*numAtomsCluster;
810 fprintf(fp, "nbl na_c %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n",
811 nbl.na_ci, rl, nbl.nci_tot, nbl.nci_tot/static_cast<double>(grid.numClusters()),
813 numAtomsPerCell/(0.5*4.0/3.0*M_PI*rl*rl*rl*grid.numClusters()*numAtomsCluster/(dims.gridSize[XX]*dims.gridSize[YY]*dims.gridSize[ZZ])));
818 int c[c_gpuNumClusterPerCell + 1] = { 0 };
819 for (const nbnxn_sci_t &sci : nbl.sci)
822 for (int j4 = sci.cj4_ind_start; j4 < sci.cj4_ind_end; j4++)
824 for (int j = 0; j < c_nbnxnGpuJgroupSize; j++)
827 for (int si = 0; si < c_gpuNumClusterPerCell; si++)
829 if (nbl.cj4[j4].imei[0].imask & (1U << (j*c_gpuNumClusterPerCell + si)))
840 nsp_max = std::max(nsp_max, nsp);
842 if (!nbl.sci.empty())
844 sum_nsp /= nbl.sci.size();
845 sum_nsp2 /= nbl.sci.size();
847 fprintf(fp, "nbl #cluster-pairs: av %.1f stddev %.1f max %d\n",
848 sum_nsp, std::sqrt(sum_nsp2 - sum_nsp*sum_nsp), nsp_max);
850 if (!nbl.cj4.empty())
852 for (int b = 0; b <= c_gpuNumClusterPerCell; b++)
854 fprintf(fp, "nbl j-list #i-subcell %d %7d %4.1f\n",
855 b, c[b], 100.0*c[b]/size_t {nbl.cj4.size()*c_nbnxnGpuJgroupSize});
860 /* Returns a pointer to the exclusion mask for j-cluster-group \p cj4 and warp \p warp
861 * Generates a new exclusion entry when the j-cluster-group uses
862 * the default all-interaction mask at call time, so the returned mask
863 * can be modified when needed.
865 static nbnxn_excl_t *get_exclusion_mask(NbnxnPairlistGpu *nbl,
869 if (nbl->cj4[cj4].imei[warp].excl_ind == 0)
871 /* No exclusions set, make a new list entry */
872 const size_t oldSize = nbl->excl.size();
873 GMX_ASSERT(oldSize >= 1, "We should always have entry [0]");
874 /* Add entry with default values: no exclusions */
875 nbl->excl.resize(oldSize + 1);
876 nbl->cj4[cj4].imei[warp].excl_ind = oldSize;
879 return &nbl->excl[nbl->cj4[cj4].imei[warp].excl_ind];
882 static void set_self_and_newton_excls_supersub(NbnxnPairlistGpu *nbl,
883 int cj4_ind, int sj_offset,
884 int i_cluster_in_cell)
886 nbnxn_excl_t *excl[c_nbnxnGpuClusterpairSplit];
888 /* Here we only set the set self and double pair exclusions */
890 /* Reserve extra elements, so the resize() in get_exclusion_mask()
891 * will not invalidate excl entries in the loop below
893 nbl->excl.reserve(nbl->excl.size() + c_nbnxnGpuClusterpairSplit);
894 for (int w = 0; w < c_nbnxnGpuClusterpairSplit; w++)
896 excl[w] = get_exclusion_mask(nbl, cj4_ind, w);
899 /* Only minor < major bits set */
900 for (int ej = 0; ej < nbl->na_ci; ej++)
903 for (int ei = ej; ei < nbl->na_ci; ei++)
905 excl[w]->pair[(ej & (c_nbnxnGpuJgroupSize-1))*nbl->na_ci + ei] &=
906 ~(1U << (sj_offset*c_gpuNumClusterPerCell + i_cluster_in_cell));
911 /* Returns a diagonal or off-diagonal interaction mask for plain C lists */
912 static unsigned int get_imask(gmx_bool rdiag, int ci, int cj)
914 return (rdiag && ci == cj ? NBNXN_INTERACTION_MASK_DIAG : NBNXN_INTERACTION_MASK_ALL);
917 /* Returns a diagonal or off-diagonal interaction mask for cj-size=2 */
918 gmx_unused static unsigned int get_imask_simd_j2(gmx_bool rdiag, int ci, int cj)
920 return (rdiag && ci*2 == cj ? NBNXN_INTERACTION_MASK_DIAG_J2_0 :
921 (rdiag && ci*2+1 == cj ? NBNXN_INTERACTION_MASK_DIAG_J2_1 :
922 NBNXN_INTERACTION_MASK_ALL));
925 /* Returns a diagonal or off-diagonal interaction mask for cj-size=4 */
926 gmx_unused static unsigned int get_imask_simd_j4(gmx_bool rdiag, int ci, int cj)
928 return (rdiag && ci == cj ? NBNXN_INTERACTION_MASK_DIAG : NBNXN_INTERACTION_MASK_ALL);
931 /* Returns a diagonal or off-diagonal interaction mask for cj-size=8 */
932 gmx_unused static unsigned int get_imask_simd_j8(gmx_bool rdiag, int ci, int cj)
934 return (rdiag && ci == cj*2 ? NBNXN_INTERACTION_MASK_DIAG_J8_0 :
935 (rdiag && ci == cj*2+1 ? NBNXN_INTERACTION_MASK_DIAG_J8_1 :
936 NBNXN_INTERACTION_MASK_ALL));
940 #if GMX_SIMD_REAL_WIDTH == 2
941 #define get_imask_simd_4xn get_imask_simd_j2
943 #if GMX_SIMD_REAL_WIDTH == 4
944 #define get_imask_simd_4xn get_imask_simd_j4
946 #if GMX_SIMD_REAL_WIDTH == 8
947 #define get_imask_simd_4xn get_imask_simd_j8
948 #define get_imask_simd_2xnn get_imask_simd_j4
950 #if GMX_SIMD_REAL_WIDTH == 16
951 #define get_imask_simd_2xnn get_imask_simd_j8
955 /* Plain C code for checking and adding cluster-pairs to the list.
957 * \param[in] gridj The j-grid
958 * \param[in,out] nbl The pair-list to store the cluster pairs in
959 * \param[in] icluster The index of the i-cluster
960 * \param[in] jclusterFirst The first cluster in the j-range
961 * \param[in] jclusterLast The last cluster in the j-range
962 * \param[in] excludeSubDiagonal Exclude atom pairs with i-index > j-index
963 * \param[in] x_j Coordinates for the j-atom, in xyz format
964 * \param[in] rlist2 The squared list cut-off
965 * \param[in] rbb2 The squared cut-off for putting cluster-pairs in the list based on bounding box distance only
966 * \param[in,out] numDistanceChecks The number of distance checks performed
969 makeClusterListSimple(const Grid &jGrid,
970 NbnxnPairlistCpu * nbl,
974 bool excludeSubDiagonal,
975 const real * gmx_restrict x_j,
978 int * gmx_restrict numDistanceChecks)
980 const BoundingBox * gmx_restrict bb_ci = nbl->work->iClusterData.bb.data();
981 const real * gmx_restrict x_ci = nbl->work->iClusterData.x.data();
986 while (!InRange && jclusterFirst <= jclusterLast)
988 real d2 = clusterBoundingBoxDistance2(bb_ci[0], jGrid.jBoundingBoxes()[jclusterFirst]);
989 *numDistanceChecks += 2;
991 /* Check if the distance is within the distance where
992 * we use only the bounding box distance rbb,
993 * or within the cut-off and there is at least one atom pair
994 * within the cut-off.
1000 else if (d2 < rlist2)
1002 int cjf_gl = jGrid.cellOffset() + jclusterFirst;
1003 for (int i = 0; i < c_nbnxnCpuIClusterSize && !InRange; i++)
1005 for (int j = 0; j < c_nbnxnCpuIClusterSize; j++)
1007 InRange = InRange ||
1008 (gmx::square(x_ci[i*STRIDE_XYZ+XX] - x_j[(cjf_gl*c_nbnxnCpuIClusterSize+j)*STRIDE_XYZ+XX]) +
1009 gmx::square(x_ci[i*STRIDE_XYZ+YY] - x_j[(cjf_gl*c_nbnxnCpuIClusterSize+j)*STRIDE_XYZ+YY]) +
1010 gmx::square(x_ci[i*STRIDE_XYZ+ZZ] - x_j[(cjf_gl*c_nbnxnCpuIClusterSize+j)*STRIDE_XYZ+ZZ]) < rlist2);
1013 *numDistanceChecks += c_nbnxnCpuIClusterSize*c_nbnxnCpuIClusterSize;
1026 while (!InRange && jclusterLast > jclusterFirst)
1028 real d2 = clusterBoundingBoxDistance2(bb_ci[0], jGrid.jBoundingBoxes()[jclusterLast]);
1029 *numDistanceChecks += 2;
1031 /* Check if the distance is within the distance where
1032 * we use only the bounding box distance rbb,
1033 * or within the cut-off and there is at least one atom pair
1034 * within the cut-off.
1040 else if (d2 < rlist2)
1042 int cjl_gl = jGrid.cellOffset() + jclusterLast;
1043 for (int i = 0; i < c_nbnxnCpuIClusterSize && !InRange; i++)
1045 for (int j = 0; j < c_nbnxnCpuIClusterSize; j++)
1047 InRange = InRange ||
1048 (gmx::square(x_ci[i*STRIDE_XYZ+XX] - x_j[(cjl_gl*c_nbnxnCpuIClusterSize+j)*STRIDE_XYZ+XX]) +
1049 gmx::square(x_ci[i*STRIDE_XYZ+YY] - x_j[(cjl_gl*c_nbnxnCpuIClusterSize+j)*STRIDE_XYZ+YY]) +
1050 gmx::square(x_ci[i*STRIDE_XYZ+ZZ] - x_j[(cjl_gl*c_nbnxnCpuIClusterSize+j)*STRIDE_XYZ+ZZ]) < rlist2);
1053 *numDistanceChecks += c_nbnxnCpuIClusterSize*c_nbnxnCpuIClusterSize;
1061 if (jclusterFirst <= jclusterLast)
1063 for (int jcluster = jclusterFirst; jcluster <= jclusterLast; jcluster++)
1065 /* Store cj and the interaction mask */
1067 cjEntry.cj = jGrid.cellOffset() + jcluster;
1068 cjEntry.excl = get_imask(excludeSubDiagonal, icluster, jcluster);
1069 nbl->cj.push_back(cjEntry);
1071 /* Increase the closing index in the i list */
1072 nbl->ci.back().cj_ind_end = nbl->cj.size();
1076 #ifdef GMX_NBNXN_SIMD_4XN
1077 #include "gromacs/nbnxm/pairlist_simd_4xm.h"
1079 #ifdef GMX_NBNXN_SIMD_2XNN
1080 #include "gromacs/nbnxm/pairlist_simd_2xmm.h"
1083 /* Plain C or SIMD4 code for making a pair list of super-cell sci vs scj.
1084 * Checks bounding box distances and possibly atom pair distances.
1086 static void make_cluster_list_supersub(const Grid &iGrid,
1088 NbnxnPairlistGpu *nbl,
1091 const bool excludeSubDiagonal,
1096 int *numDistanceChecks)
1098 NbnxnPairlistGpuWork &work = *nbl->work;
1101 const float *pbb_ci = work.iSuperClusterData.bbPacked.data();
1103 const BoundingBox *bb_ci = work.iSuperClusterData.bb.data();
1106 assert(c_nbnxnGpuClusterSize == iGrid.geometry().numAtomsICluster);
1107 assert(c_nbnxnGpuClusterSize == jGrid.geometry().numAtomsICluster);
1109 /* We generate the pairlist mainly based on bounding-box distances
1110 * and do atom pair distance based pruning on the GPU.
1111 * Only if a j-group contains a single cluster-pair, we try to prune
1112 * that pair based on atom distances on the CPU to avoid empty j-groups.
1114 #define PRUNE_LIST_CPU_ONE 1
1115 #define PRUNE_LIST_CPU_ALL 0
1117 #if PRUNE_LIST_CPU_ONE
1121 float *d2l = work.distanceBuffer.data();
1123 for (int subc = 0; subc < jGrid.numClustersPerCell()[scj]; subc++)
1125 const int cj4_ind = work.cj_ind/c_nbnxnGpuJgroupSize;
1126 const int cj_offset = work.cj_ind - cj4_ind*c_nbnxnGpuJgroupSize;
1127 const int cj = scj*c_gpuNumClusterPerCell + subc;
1129 const int cj_gl = jGrid.cellOffset()*c_gpuNumClusterPerCell + cj;
1132 if (excludeSubDiagonal && sci == scj)
1138 ci1 = iGrid.numClustersPerCell()[sci];
1142 /* Determine all ci1 bb distances in one call with SIMD4 */
1143 const int offset = packedBoundingBoxesIndex(cj) + (cj & (c_packedBoundingBoxesDimSize - 1));
1144 clusterBoundingBoxDistance2_xxxx_simd4(jGrid.packedBoundingBoxes().data() + offset,
1146 *numDistanceChecks += c_nbnxnGpuClusterSize*2;
1150 unsigned int imask = 0;
1151 /* We use a fixed upper-bound instead of ci1 to help optimization */
1152 for (int ci = 0; ci < c_gpuNumClusterPerCell; ci++)
1160 /* Determine the bb distance between ci and cj */
1161 d2l[ci] = clusterBoundingBoxDistance2(bb_ci[ci], jGrid.jBoundingBoxes()[cj]);
1162 *numDistanceChecks += 2;
1166 #if PRUNE_LIST_CPU_ALL
1167 /* Check if the distance is within the distance where
1168 * we use only the bounding box distance rbb,
1169 * or within the cut-off and there is at least one atom pair
1170 * within the cut-off. This check is very costly.
1172 *numDistanceChecks += c_nbnxnGpuClusterSize*c_nbnxnGpuClusterSize;
1175 clusterpair_in_range(work, ci, cj_gl, stride, x, rlist2)))
1177 /* Check if the distance between the two bounding boxes
1178 * in within the pair-list cut-off.
1183 /* Flag this i-subcell to be taken into account */
1184 imask |= (1U << (cj_offset*c_gpuNumClusterPerCell + ci));
1186 #if PRUNE_LIST_CPU_ONE
1194 #if PRUNE_LIST_CPU_ONE
1195 /* If we only found 1 pair, check if any atoms are actually
1196 * within the cut-off, so we could get rid of it.
1198 if (npair == 1 && d2l[ci_last] >= rbb2 &&
1199 !clusterpair_in_range(work, ci_last, cj_gl, stride, x, rlist2))
1201 imask &= ~(1U << (cj_offset*c_gpuNumClusterPerCell + ci_last));
1208 /* We have at least one cluster pair: add a j-entry */
1209 if (static_cast<size_t>(cj4_ind) == nbl->cj4.size())
1211 nbl->cj4.resize(nbl->cj4.size() + 1);
1213 nbnxn_cj4_t *cj4 = &nbl->cj4[cj4_ind];
1215 cj4->cj[cj_offset] = cj_gl;
1217 /* Set the exclusions for the ci==sj entry.
1218 * Here we don't bother to check if this entry is actually flagged,
1219 * as it will nearly always be in the list.
1221 if (excludeSubDiagonal && sci == scj)
1223 set_self_and_newton_excls_supersub(nbl, cj4_ind, cj_offset, subc);
1226 /* Copy the cluster interaction mask to the list */
1227 for (int w = 0; w < c_nbnxnGpuClusterpairSplit; w++)
1229 cj4->imei[w].imask |= imask;
1232 nbl->work->cj_ind++;
1234 /* Keep the count */
1235 nbl->nci_tot += npair;
1237 /* Increase the closing index in i super-cell list */
1238 nbl->sci.back().cj4_ind_end =
1239 (nbl->work->cj_ind + c_nbnxnGpuJgroupSize - 1)/c_nbnxnGpuJgroupSize;
1244 /* Returns how many contiguous j-clusters we have starting in the i-list */
1245 template <typename CjListType>
1246 static int numContiguousJClusters(const int cjIndexStart,
1247 const int cjIndexEnd,
1248 gmx::ArrayRef<const CjListType> cjList)
1250 const int firstJCluster = nblCj(cjList, cjIndexStart);
1252 int numContiguous = 0;
1254 while (cjIndexStart + numContiguous < cjIndexEnd &&
1255 nblCj(cjList, cjIndexStart + numContiguous) == firstJCluster + numContiguous)
1260 return numContiguous;
1264 * \brief Helper struct for efficient searching for excluded atoms in a j-list
1268 /*! \brief Constructs a j-list range from \p cjList with the given index range */
1269 template <typename CjListType>
1270 JListRanges(int cjIndexStart,
1272 gmx::ArrayRef<const CjListType> cjList);
1274 int cjIndexStart; //!< The start index in the j-list
1275 int cjIndexEnd; //!< The end index in the j-list
1276 int cjFirst; //!< The j-cluster with index cjIndexStart
1277 int cjLast; //!< The j-cluster with index cjIndexEnd-1
1278 int numDirect; //!< Up to cjIndexStart+numDirect the j-clusters are cjFirst + the index offset
1282 template <typename CjListType>
1283 JListRanges::JListRanges(int cjIndexStart,
1285 gmx::ArrayRef<const CjListType> cjList) :
1286 cjIndexStart(cjIndexStart),
1287 cjIndexEnd(cjIndexEnd)
1289 GMX_ASSERT(cjIndexEnd > cjIndexStart, "JListRanges should only be called with non-empty lists");
1291 cjFirst = nblCj(cjList, cjIndexStart);
1292 cjLast = nblCj(cjList, cjIndexEnd - 1);
1294 /* Determine how many contiguous j-cells we have starting
1295 * from the first i-cell. This number can be used to directly
1296 * calculate j-cell indices for excluded atoms.
1298 numDirect = numContiguousJClusters(cjIndexStart, cjIndexEnd, cjList);
1302 /* Return the index of \p jCluster in the given range or -1 when not present
1304 * Note: This code is executed very often and therefore performance is
1305 * important. It should be inlined and fully optimized.
1307 template <typename CjListType>
1309 findJClusterInJList(int jCluster,
1310 const JListRanges &ranges,
1311 gmx::ArrayRef<const CjListType> cjList)
1315 if (jCluster < ranges.cjFirst + ranges.numDirect)
1317 /* We can calculate the index directly using the offset */
1318 index = ranges.cjIndexStart + jCluster - ranges.cjFirst;
1322 /* Search for jCluster using bisection */
1324 int rangeStart = ranges.cjIndexStart + ranges.numDirect;
1325 int rangeEnd = ranges.cjIndexEnd;
1327 while (index == -1 && rangeStart < rangeEnd)
1329 rangeMiddle = (rangeStart + rangeEnd) >> 1;
1331 const int clusterMiddle = nblCj(cjList, rangeMiddle);
1333 if (jCluster == clusterMiddle)
1335 index = rangeMiddle;
1337 else if (jCluster < clusterMiddle)
1339 rangeEnd = rangeMiddle;
1343 rangeStart = rangeMiddle + 1;
1351 // TODO: Get rid of the two functions below by renaming sci to ci (or something better)
1353 /* Return the i-entry in the list we are currently operating on */
1354 static nbnxn_ci_t *getOpenIEntry(NbnxnPairlistCpu *nbl)
1356 return &nbl->ci.back();
1359 /* Return the i-entry in the list we are currently operating on */
1360 static nbnxn_sci_t *getOpenIEntry(NbnxnPairlistGpu *nbl)
1362 return &nbl->sci.back();
1365 /* Set all atom-pair exclusions for a simple type list i-entry
1367 * Set all atom-pair exclusions from the topology stored in exclusions
1368 * as masks in the pair-list for simple list entry iEntry.
1371 setExclusionsForIEntry(const Nbnxm::GridSet &gridSet,
1372 NbnxnPairlistCpu *nbl,
1373 gmx_bool diagRemoved,
1375 const nbnxn_ci_t &iEntry,
1376 const t_blocka &exclusions)
1378 if (iEntry.cj_ind_end == iEntry.cj_ind_start)
1380 /* Empty list: no exclusions */
1384 const JListRanges ranges(iEntry.cj_ind_start, iEntry.cj_ind_end, gmx::makeConstArrayRef(nbl->cj));
1386 const int iCluster = iEntry.ci;
1388 gmx::ArrayRef<const int> cell = gridSet.cells();
1389 gmx::ArrayRef<const int> atomIndices = gridSet.atomIndices();
1391 /* Loop over the atoms in the i-cluster */
1392 for (int i = 0; i < nbl->na_ci; i++)
1394 const int iIndex = iCluster*nbl->na_ci + i;
1395 const int iAtom = atomIndices[iIndex];
1398 /* Loop over the topology-based exclusions for this i-atom */
1399 for (int exclIndex = exclusions.index[iAtom]; exclIndex < exclusions.index[iAtom + 1]; exclIndex++)
1401 const int jAtom = exclusions.a[exclIndex];
1405 /* The self exclusion are already set, save some time */
1409 /* Get the index of the j-atom in the nbnxn atom data */
1410 const int jIndex = cell[jAtom];
1412 /* Without shifts we only calculate interactions j>i
1413 * for one-way pair-lists.
1415 if (diagRemoved && jIndex <= iIndex)
1420 const int jCluster = (jIndex >> na_cj_2log);
1422 /* Could the cluster se be in our list? */
1423 if (jCluster >= ranges.cjFirst && jCluster <= ranges.cjLast)
1426 findJClusterInJList(jCluster, ranges,
1427 gmx::makeConstArrayRef(nbl->cj));
1431 /* We found an exclusion, clear the corresponding
1434 const int innerJ = jIndex - (jCluster << na_cj_2log);
1436 nbl->cj[index].excl &= ~(1U << ((i << na_cj_2log) + innerJ));
1444 /* Add a new i-entry to the FEP list and copy the i-properties */
1445 static inline void fep_list_new_nri_copy(t_nblist *nlist)
1447 /* Add a new i-entry */
1450 assert(nlist->nri < nlist->maxnri);
1452 /* Duplicate the last i-entry, except for jindex, which continues */
1453 nlist->iinr[nlist->nri] = nlist->iinr[nlist->nri-1];
1454 nlist->shift[nlist->nri] = nlist->shift[nlist->nri-1];
1455 nlist->gid[nlist->nri] = nlist->gid[nlist->nri-1];
1456 nlist->jindex[nlist->nri] = nlist->nrj;
1459 /* For load balancing of the free-energy lists over threads, we set
1460 * the maximum nrj size of an i-entry to 40. This leads to good
1461 * load balancing in the worst case scenario of a single perturbed
1462 * particle on 16 threads, while not introducing significant overhead.
1463 * Note that half of the perturbed pairs will anyhow end up in very small lists,
1464 * since non perturbed i-particles will see few perturbed j-particles).
1466 const int max_nrj_fep = 40;
1468 /* Exclude the perturbed pairs from the Verlet list. This is only done to avoid
1469 * singularities for overlapping particles (0/0), since the charges and
1470 * LJ parameters have been zeroed in the nbnxn data structure.
1471 * Simultaneously make a group pair list for the perturbed pairs.
1473 static void make_fep_list(gmx::ArrayRef<const int> atomIndices,
1474 const nbnxn_atomdata_t *nbat,
1475 NbnxnPairlistCpu *nbl,
1476 gmx_bool bDiagRemoved,
1478 real gmx_unused shx,
1479 real gmx_unused shy,
1480 real gmx_unused shz,
1481 real gmx_unused rlist_fep2,
1486 int ci, cj_ind_start, cj_ind_end, cja, cjr;
1488 int gid_i = 0, gid_j, gid;
1489 int egp_shift, egp_mask;
1491 int ind_i, ind_j, ai, aj;
1493 gmx_bool bFEP_i, bFEP_i_all;
1495 if (nbl_ci->cj_ind_end == nbl_ci->cj_ind_start)
1503 cj_ind_start = nbl_ci->cj_ind_start;
1504 cj_ind_end = nbl_ci->cj_ind_end;
1506 /* In worst case we have alternating energy groups
1507 * and create #atom-pair lists, which means we need the size
1508 * of a cluster pair (na_ci*na_cj) times the number of cj's.
1510 nri_max = nbl->na_ci*nbl->na_cj*(cj_ind_end - cj_ind_start);
1511 if (nlist->nri + nri_max > nlist->maxnri)
1513 nlist->maxnri = over_alloc_large(nlist->nri + nri_max);
1514 reallocate_nblist(nlist);
1517 const int numAtomsJCluster = jGrid.geometry().numAtomsJCluster;
1519 const nbnxn_atomdata_t::Params &nbatParams = nbat->params();
1521 const int ngid = nbatParams.nenergrp;
1523 /* TODO: Consider adding a check in grompp and changing this to an assert */
1524 const int numBitsInEnergyGroupIdsForAtomsInJCluster = sizeof(gid_cj)*8;
1525 if (ngid*numAtomsJCluster > numBitsInEnergyGroupIdsForAtomsInJCluster)
1527 gmx_fatal(FARGS, "The Verlet scheme with %dx%d kernels and free-energy only supports up to %zu energy groups",
1528 iGrid.geometry().numAtomsICluster, numAtomsJCluster,
1529 (sizeof(gid_cj)*8)/numAtomsJCluster);
1532 egp_shift = nbatParams.neg_2log;
1533 egp_mask = (1 << egp_shift) - 1;
1535 /* Loop over the atoms in the i sub-cell */
1537 for (int i = 0; i < nbl->na_ci; i++)
1539 ind_i = ci*nbl->na_ci + i;
1540 ai = atomIndices[ind_i];
1544 nlist->jindex[nri+1] = nlist->jindex[nri];
1545 nlist->iinr[nri] = ai;
1546 /* The actual energy group pair index is set later */
1547 nlist->gid[nri] = 0;
1548 nlist->shift[nri] = nbl_ci->shift & NBNXN_CI_SHIFT;
1550 bFEP_i = iGrid.atomIsPerturbed(ci - iGrid.cellOffset(), i);
1552 bFEP_i_all = bFEP_i_all && bFEP_i;
1554 if (nlist->nrj + (cj_ind_end - cj_ind_start)*nbl->na_cj > nlist->maxnrj)
1556 nlist->maxnrj = over_alloc_small(nlist->nrj + (cj_ind_end - cj_ind_start)*nbl->na_cj);
1557 srenew(nlist->jjnr, nlist->maxnrj);
1558 srenew(nlist->excl_fep, nlist->maxnrj);
1563 gid_i = (nbatParams.energrp[ci] >> (egp_shift*i)) & egp_mask;
1566 for (int cj_ind = cj_ind_start; cj_ind < cj_ind_end; cj_ind++)
1568 unsigned int fep_cj;
1570 cja = nbl->cj[cj_ind].cj;
1572 if (numAtomsJCluster == jGrid.geometry().numAtomsICluster)
1574 cjr = cja - jGrid.cellOffset();
1575 fep_cj = jGrid.fepBits(cjr);
1578 gid_cj = nbatParams.energrp[cja];
1581 else if (2*numAtomsJCluster == jGrid.geometry().numAtomsICluster)
1583 cjr = cja - jGrid.cellOffset()*2;
1584 /* Extract half of the ci fep/energrp mask */
1585 fep_cj = (jGrid.fepBits(cjr >> 1) >> ((cjr & 1)*numAtomsJCluster)) & ((1 << numAtomsJCluster) - 1);
1588 gid_cj = nbatParams.energrp[cja >> 1] >> ((cja & 1)*numAtomsJCluster*egp_shift) & ((1 << (numAtomsJCluster*egp_shift)) - 1);
1593 cjr = cja - (jGrid.cellOffset() >> 1);
1594 /* Combine two ci fep masks/energrp */
1595 fep_cj = jGrid.fepBits(cjr*2) + (jGrid.fepBits(cjr*2 + 1) << jGrid.geometry().numAtomsICluster);
1598 gid_cj = nbatParams.energrp[cja*2] + (nbatParams.energrp[cja*2+1] << (jGrid.geometry().numAtomsICluster*egp_shift));
1602 if (bFEP_i || fep_cj != 0)
1604 for (int j = 0; j < nbl->na_cj; j++)
1606 /* Is this interaction perturbed and not excluded? */
1607 ind_j = cja*nbl->na_cj + j;
1608 aj = atomIndices[ind_j];
1610 (bFEP_i || (fep_cj & (1 << j))) &&
1611 (!bDiagRemoved || ind_j >= ind_i))
1615 gid_j = (gid_cj >> (j*egp_shift)) & egp_mask;
1616 gid = GID(gid_i, gid_j, ngid);
1618 if (nlist->nrj > nlist->jindex[nri] &&
1619 nlist->gid[nri] != gid)
1621 /* Energy group pair changed: new list */
1622 fep_list_new_nri_copy(nlist);
1625 nlist->gid[nri] = gid;
1628 if (nlist->nrj - nlist->jindex[nri] >= max_nrj_fep)
1630 fep_list_new_nri_copy(nlist);
1634 /* Add it to the FEP list */
1635 nlist->jjnr[nlist->nrj] = aj;
1636 nlist->excl_fep[nlist->nrj] = (nbl->cj[cj_ind].excl >> (i*nbl->na_cj + j)) & 1;
1639 /* Exclude it from the normal list.
1640 * Note that the charge has been set to zero,
1641 * but we need to avoid 0/0, as perturbed atoms
1642 * can be on top of each other.
1644 nbl->cj[cj_ind].excl &= ~(1U << (i*nbl->na_cj + j));
1650 if (nlist->nrj > nlist->jindex[nri])
1652 /* Actually add this new, non-empty, list */
1654 nlist->jindex[nlist->nri] = nlist->nrj;
1661 /* All interactions are perturbed, we can skip this entry */
1662 nbl_ci->cj_ind_end = cj_ind_start;
1663 nbl->ncjInUse -= cj_ind_end - cj_ind_start;
1667 /* Return the index of atom a within a cluster */
1668 static inline int cj_mod_cj4(int cj)
1670 return cj & (c_nbnxnGpuJgroupSize - 1);
1673 /* Convert a j-cluster to a cj4 group */
1674 static inline int cj_to_cj4(int cj)
1676 return cj/c_nbnxnGpuJgroupSize;
1679 /* Return the index of an j-atom within a warp */
1680 static inline int a_mod_wj(int a)
1682 return a & (c_nbnxnGpuClusterSize/c_nbnxnGpuClusterpairSplit - 1);
1685 /* As make_fep_list above, but for super/sub lists. */
1686 static void make_fep_list(gmx::ArrayRef<const int> atomIndices,
1687 const nbnxn_atomdata_t *nbat,
1688 NbnxnPairlistGpu *nbl,
1689 gmx_bool bDiagRemoved,
1690 const nbnxn_sci_t *nbl_sci,
1701 int ind_i, ind_j, ai, aj;
1705 const nbnxn_cj4_t *cj4;
1707 const int numJClusterGroups = nbl_sci->numJClusterGroups();
1708 if (numJClusterGroups == 0)
1714 const int sci = nbl_sci->sci;
1716 const int cj4_ind_start = nbl_sci->cj4_ind_start;
1717 const int cj4_ind_end = nbl_sci->cj4_ind_end;
1719 /* Here we process one super-cell, max #atoms na_sc, versus a list
1720 * cj4 entries, each with max c_nbnxnGpuJgroupSize cj's, each
1721 * of size na_cj atoms.
1722 * On the GPU we don't support energy groups (yet).
1723 * So for each of the na_sc i-atoms, we need max one FEP list
1724 * for each max_nrj_fep j-atoms.
1726 nri_max = nbl->na_sc*nbl->na_cj*(1 + (numJClusterGroups*c_nbnxnGpuJgroupSize)/max_nrj_fep);
1727 if (nlist->nri + nri_max > nlist->maxnri)
1729 nlist->maxnri = over_alloc_large(nlist->nri + nri_max);
1730 reallocate_nblist(nlist);
1733 /* Loop over the atoms in the i super-cluster */
1734 for (int c = 0; c < c_gpuNumClusterPerCell; c++)
1736 c_abs = sci*c_gpuNumClusterPerCell + c;
1738 for (int i = 0; i < nbl->na_ci; i++)
1740 ind_i = c_abs*nbl->na_ci + i;
1741 ai = atomIndices[ind_i];
1745 nlist->jindex[nri+1] = nlist->jindex[nri];
1746 nlist->iinr[nri] = ai;
1747 /* With GPUs, energy groups are not supported */
1748 nlist->gid[nri] = 0;
1749 nlist->shift[nri] = nbl_sci->shift & NBNXN_CI_SHIFT;
1751 bFEP_i = iGrid.atomIsPerturbed(c_abs - iGrid.cellOffset()*c_gpuNumClusterPerCell, i);
1753 xi = nbat->x()[ind_i*nbat->xstride+XX] + shx;
1754 yi = nbat->x()[ind_i*nbat->xstride+YY] + shy;
1755 zi = nbat->x()[ind_i*nbat->xstride+ZZ] + shz;
1757 const int nrjMax = nlist->nrj + numJClusterGroups*c_nbnxnGpuJgroupSize*nbl->na_cj;
1758 if (nrjMax > nlist->maxnrj)
1760 nlist->maxnrj = over_alloc_small(nrjMax);
1761 srenew(nlist->jjnr, nlist->maxnrj);
1762 srenew(nlist->excl_fep, nlist->maxnrj);
1765 for (int cj4_ind = cj4_ind_start; cj4_ind < cj4_ind_end; cj4_ind++)
1767 cj4 = &nbl->cj4[cj4_ind];
1769 for (int gcj = 0; gcj < c_nbnxnGpuJgroupSize; gcj++)
1771 if ((cj4->imei[0].imask & (1U << (gcj*c_gpuNumClusterPerCell + c))) == 0)
1773 /* Skip this ci for this cj */
1778 cj4->cj[gcj] - jGrid.cellOffset()*c_gpuNumClusterPerCell;
1780 if (bFEP_i || jGrid.clusterIsPerturbed(cjr))
1782 for (int j = 0; j < nbl->na_cj; j++)
1784 /* Is this interaction perturbed and not excluded? */
1785 ind_j = (jGrid.cellOffset()*c_gpuNumClusterPerCell + cjr)*nbl->na_cj + j;
1786 aj = atomIndices[ind_j];
1788 (bFEP_i || jGrid.atomIsPerturbed(cjr, j)) &&
1789 (!bDiagRemoved || ind_j >= ind_i))
1792 unsigned int excl_bit;
1795 const int jHalf = j/(c_nbnxnGpuClusterSize/c_nbnxnGpuClusterpairSplit);
1796 nbnxn_excl_t *excl =
1797 get_exclusion_mask(nbl, cj4_ind, jHalf);
1799 excl_pair = a_mod_wj(j)*nbl->na_ci + i;
1800 excl_bit = (1U << (gcj*c_gpuNumClusterPerCell + c));
1802 dx = nbat->x()[ind_j*nbat->xstride+XX] - xi;
1803 dy = nbat->x()[ind_j*nbat->xstride+YY] - yi;
1804 dz = nbat->x()[ind_j*nbat->xstride+ZZ] - zi;
1806 /* The unpruned GPU list has more than 2/3
1807 * of the atom pairs beyond rlist. Using
1808 * this list will cause a lot of overhead
1809 * in the CPU FEP kernels, especially
1810 * relative to the fast GPU kernels.
1811 * So we prune the FEP list here.
1813 if (dx*dx + dy*dy + dz*dz < rlist_fep2)
1815 if (nlist->nrj - nlist->jindex[nri] >= max_nrj_fep)
1817 fep_list_new_nri_copy(nlist);
1821 /* Add it to the FEP list */
1822 nlist->jjnr[nlist->nrj] = aj;
1823 nlist->excl_fep[nlist->nrj] = (excl->pair[excl_pair] & excl_bit) ? 1 : 0;
1827 /* Exclude it from the normal list.
1828 * Note that the charge and LJ parameters have
1829 * been set to zero, but we need to avoid 0/0,
1830 * as perturbed atoms can be on top of each other.
1832 excl->pair[excl_pair] &= ~excl_bit;
1836 /* Note that we could mask out this pair in imask
1837 * if all i- and/or all j-particles are perturbed.
1838 * But since the perturbed pairs on the CPU will
1839 * take an order of magnitude more time, the GPU
1840 * will finish before the CPU and there is no gain.
1846 if (nlist->nrj > nlist->jindex[nri])
1848 /* Actually add this new, non-empty, list */
1850 nlist->jindex[nlist->nri] = nlist->nrj;
1857 /* Set all atom-pair exclusions for a GPU type list i-entry
1859 * Sets all atom-pair exclusions from the topology stored in exclusions
1860 * as masks in the pair-list for i-super-cluster list entry iEntry.
1863 setExclusionsForIEntry(const Nbnxm::GridSet &gridSet,
1864 NbnxnPairlistGpu *nbl,
1865 gmx_bool diagRemoved,
1866 int gmx_unused na_cj_2log,
1867 const nbnxn_sci_t &iEntry,
1868 const t_blocka &exclusions)
1870 if (iEntry.numJClusterGroups() == 0)
1876 /* Set the search ranges using start and end j-cluster indices.
1877 * Note that here we can not use cj4_ind_end, since the last cj4
1878 * can be only partially filled, so we use cj_ind.
1880 const JListRanges ranges(iEntry.cj4_ind_start*c_nbnxnGpuJgroupSize,
1882 gmx::makeConstArrayRef(nbl->cj4));
1884 GMX_ASSERT(nbl->na_ci == c_nbnxnGpuClusterSize, "na_ci should match the GPU cluster size");
1885 constexpr int c_clusterSize = c_nbnxnGpuClusterSize;
1886 constexpr int c_superClusterSize = c_nbnxnGpuNumClusterPerSupercluster*c_nbnxnGpuClusterSize;
1888 const int iSuperCluster = iEntry.sci;
1890 gmx::ArrayRef<const int> atomIndices = gridSet.atomIndices();
1891 gmx::ArrayRef<const int> cell = gridSet.cells();
1893 /* Loop over the atoms in the i super-cluster */
1894 for (int i = 0; i < c_superClusterSize; i++)
1896 const int iIndex = iSuperCluster*c_superClusterSize + i;
1897 const int iAtom = atomIndices[iIndex];
1900 const int iCluster = i/c_clusterSize;
1902 /* Loop over the topology-based exclusions for this i-atom */
1903 for (int exclIndex = exclusions.index[iAtom]; exclIndex < exclusions.index[iAtom + 1]; exclIndex++)
1905 const int jAtom = exclusions.a[exclIndex];
1909 /* The self exclusions are already set, save some time */
1913 /* Get the index of the j-atom in the nbnxn atom data */
1914 const int jIndex = cell[jAtom];
1916 /* Without shifts we only calculate interactions j>i
1917 * for one-way pair-lists.
1919 /* NOTE: We would like to use iIndex on the right hand side,
1920 * but that makes this routine 25% slower with gcc6/7.
1921 * Even using c_superClusterSize makes it slower.
1922 * Either of these changes triggers peeling of the exclIndex
1923 * loop, which apparently leads to far less efficient code.
1925 if (diagRemoved && jIndex <= iSuperCluster*nbl->na_sc + i)
1930 const int jCluster = jIndex/c_clusterSize;
1932 /* Check whether the cluster is in our list? */
1933 if (jCluster >= ranges.cjFirst && jCluster <= ranges.cjLast)
1936 findJClusterInJList(jCluster, ranges,
1937 gmx::makeConstArrayRef(nbl->cj4));
1941 /* We found an exclusion, clear the corresponding
1944 const unsigned int pairMask = (1U << (cj_mod_cj4(index)*c_gpuNumClusterPerCell + iCluster));
1945 /* Check if the i-cluster interacts with the j-cluster */
1946 if (nbl_imask0(nbl, index) & pairMask)
1948 const int innerI = (i & (c_clusterSize - 1));
1949 const int innerJ = (jIndex & (c_clusterSize - 1));
1951 /* Determine which j-half (CUDA warp) we are in */
1952 const int jHalf = innerJ/(c_clusterSize/c_nbnxnGpuClusterpairSplit);
1954 nbnxn_excl_t *interactionMask =
1955 get_exclusion_mask(nbl, cj_to_cj4(index), jHalf);
1957 interactionMask->pair[a_mod_wj(innerJ)*c_clusterSize + innerI] &= ~pairMask;
1966 /* Make a new ci entry at the back of nbl->ci */
1967 static void addNewIEntry(NbnxnPairlistCpu *nbl, int ci, int shift, int flags)
1971 ciEntry.shift = shift;
1972 /* Store the interaction flags along with the shift */
1973 ciEntry.shift |= flags;
1974 ciEntry.cj_ind_start = nbl->cj.size();
1975 ciEntry.cj_ind_end = nbl->cj.size();
1976 nbl->ci.push_back(ciEntry);
1979 /* Make a new sci entry at index nbl->nsci */
1980 static void addNewIEntry(NbnxnPairlistGpu *nbl, int sci, int shift, int gmx_unused flags)
1982 nbnxn_sci_t sciEntry;
1984 sciEntry.shift = shift;
1985 sciEntry.cj4_ind_start = nbl->cj4.size();
1986 sciEntry.cj4_ind_end = nbl->cj4.size();
1988 nbl->sci.push_back(sciEntry);
1991 /* Sort the simple j-list cj on exclusions.
1992 * Entries with exclusions will all be sorted to the beginning of the list.
1994 static void sort_cj_excl(nbnxn_cj_t *cj, int ncj,
1995 NbnxnPairlistCpuWork *work)
1997 work->cj.resize(ncj);
1999 /* Make a list of the j-cells involving exclusions */
2001 for (int j = 0; j < ncj; j++)
2003 if (cj[j].excl != NBNXN_INTERACTION_MASK_ALL)
2005 work->cj[jnew++] = cj[j];
2008 /* Check if there are exclusions at all or not just the first entry */
2009 if (!((jnew == 0) ||
2010 (jnew == 1 && cj[0].excl != NBNXN_INTERACTION_MASK_ALL)))
2012 for (int j = 0; j < ncj; j++)
2014 if (cj[j].excl == NBNXN_INTERACTION_MASK_ALL)
2016 work->cj[jnew++] = cj[j];
2019 for (int j = 0; j < ncj; j++)
2021 cj[j] = work->cj[j];
2026 /* Close this simple list i entry */
2027 static void closeIEntry(NbnxnPairlistCpu *nbl,
2028 int gmx_unused sp_max_av,
2029 gmx_bool gmx_unused progBal,
2030 float gmx_unused nsp_tot_est,
2031 int gmx_unused thread,
2032 int gmx_unused nthread)
2034 nbnxn_ci_t &ciEntry = nbl->ci.back();
2036 /* All content of the new ci entry have already been filled correctly,
2037 * we only need to sort and increase counts or remove the entry when empty.
2039 const int jlen = ciEntry.cj_ind_end - ciEntry.cj_ind_start;
2042 sort_cj_excl(nbl->cj.data() + ciEntry.cj_ind_start, jlen, nbl->work.get());
2044 /* The counts below are used for non-bonded pair/flop counts
2045 * and should therefore match the available kernel setups.
2047 if (!(ciEntry.shift & NBNXN_CI_DO_COUL(0)))
2049 nbl->work->ncj_noq += jlen;
2051 else if ((ciEntry.shift & NBNXN_CI_HALF_LJ(0)) ||
2052 !(ciEntry.shift & NBNXN_CI_DO_LJ(0)))
2054 nbl->work->ncj_hlj += jlen;
2059 /* Entry is empty: remove it */
2064 /* Split sci entry for load balancing on the GPU.
2065 * Splitting ensures we have enough lists to fully utilize the whole GPU.
2066 * With progBal we generate progressively smaller lists, which improves
2067 * load balancing. As we only know the current count on our own thread,
2068 * we will need to estimate the current total amount of i-entries.
2069 * As the lists get concatenated later, this estimate depends
2070 * both on nthread and our own thread index.
2072 static void split_sci_entry(NbnxnPairlistGpu *nbl,
2074 gmx_bool progBal, float nsp_tot_est,
2075 int thread, int nthread)
2083 /* Estimate the total numbers of ci's of the nblist combined
2084 * over all threads using the target number of ci's.
2086 nsp_est = (nsp_tot_est*thread)/nthread + nbl->nci_tot;
2088 /* The first ci blocks should be larger, to avoid overhead.
2089 * The last ci blocks should be smaller, to improve load balancing.
2090 * The factor 3/2 makes the first block 3/2 times the target average
2091 * and ensures that the total number of blocks end up equal to
2092 * that of equally sized blocks of size nsp_target_av.
2094 nsp_max = static_cast<int>(nsp_target_av*(nsp_tot_est*1.5/(nsp_est + nsp_tot_est)));
2098 nsp_max = nsp_target_av;
2101 const int cj4_start = nbl->sci.back().cj4_ind_start;
2102 const int cj4_end = nbl->sci.back().cj4_ind_end;
2103 const int j4len = cj4_end - cj4_start;
2105 if (j4len > 1 && j4len*c_gpuNumClusterPerCell*c_nbnxnGpuJgroupSize > nsp_max)
2107 /* Modify the last ci entry and process the cj4's again */
2113 for (int cj4 = cj4_start; cj4 < cj4_end; cj4++)
2115 int nsp_cj4_p = nsp_cj4;
2116 /* Count the number of cluster pairs in this cj4 group */
2118 for (int p = 0; p < c_gpuNumClusterPerCell*c_nbnxnGpuJgroupSize; p++)
2120 nsp_cj4 += (nbl->cj4[cj4].imei[0].imask >> p) & 1;
2123 /* If adding the current cj4 with nsp_cj4 pairs get us further
2124 * away from our target nsp_max, split the list before this cj4.
2126 if (nsp > 0 && nsp_max - nsp < nsp + nsp_cj4 - nsp_max)
2128 /* Split the list at cj4 */
2129 nbl->sci.back().cj4_ind_end = cj4;
2130 /* Create a new sci entry */
2132 sciNew.sci = nbl->sci.back().sci;
2133 sciNew.shift = nbl->sci.back().shift;
2134 sciNew.cj4_ind_start = cj4;
2135 nbl->sci.push_back(sciNew);
2138 nsp_cj4_e = nsp_cj4_p;
2144 /* Put the remaining cj4's in the last sci entry */
2145 nbl->sci.back().cj4_ind_end = cj4_end;
2147 /* Possibly balance out the last two sci's
2148 * by moving the last cj4 of the second last sci.
2150 if (nsp_sci - nsp_cj4_e >= nsp + nsp_cj4_e)
2152 GMX_ASSERT(nbl->sci.size() >= 2, "We expect at least two elements");
2153 nbl->sci[nbl->sci.size() - 2].cj4_ind_end--;
2154 nbl->sci[nbl->sci.size() - 1].cj4_ind_start--;
2159 /* Clost this super/sub list i entry */
2160 static void closeIEntry(NbnxnPairlistGpu *nbl,
2162 gmx_bool progBal, float nsp_tot_est,
2163 int thread, int nthread)
2165 nbnxn_sci_t &sciEntry = *getOpenIEntry(nbl);
2167 /* All content of the new ci entry have already been filled correctly,
2168 * we only need to, potentially, split or remove the entry when empty.
2170 int j4len = sciEntry.numJClusterGroups();
2173 /* We can only have complete blocks of 4 j-entries in a list,
2174 * so round the count up before closing.
2176 int ncj4 = (nbl->work->cj_ind + c_nbnxnGpuJgroupSize - 1)/c_nbnxnGpuJgroupSize;
2177 nbl->work->cj_ind = ncj4*c_nbnxnGpuJgroupSize;
2181 /* Measure the size of the new entry and potentially split it */
2182 split_sci_entry(nbl, nsp_max_av, progBal, nsp_tot_est,
2188 /* Entry is empty: remove it */
2189 nbl->sci.pop_back();
2193 /* Syncs the working array before adding another grid pair to the GPU list */
2194 static void sync_work(NbnxnPairlistCpu gmx_unused *nbl)
2198 /* Syncs the working array before adding another grid pair to the GPU list */
2199 static void sync_work(NbnxnPairlistGpu *nbl)
2201 nbl->work->cj_ind = nbl->cj4.size()*c_nbnxnGpuJgroupSize;
2204 /* Clears an NbnxnPairlistCpu data structure */
2205 static void clear_pairlist(NbnxnPairlistCpu *nbl)
2211 nbl->ciOuter.clear();
2212 nbl->cjOuter.clear();
2214 nbl->work->ncj_noq = 0;
2215 nbl->work->ncj_hlj = 0;
2218 /* Clears an NbnxnPairlistGpu data structure */
2219 static void clear_pairlist(NbnxnPairlistGpu *nbl)
2223 nbl->excl.resize(1);
2227 /* Clears a group scheme pair list */
2228 static void clear_pairlist_fep(t_nblist *nl)
2232 if (nl->jindex == nullptr)
2234 snew(nl->jindex, 1);
2239 /* Sets a simple list i-cell bounding box, including PBC shift */
2240 static inline void set_icell_bb_simple(gmx::ArrayRef<const BoundingBox> bb,
2242 real shx, real shy, real shz,
2245 bb_ci->lower.x = bb[ci].lower.x + shx;
2246 bb_ci->lower.y = bb[ci].lower.y + shy;
2247 bb_ci->lower.z = bb[ci].lower.z + shz;
2248 bb_ci->upper.x = bb[ci].upper.x + shx;
2249 bb_ci->upper.y = bb[ci].upper.y + shy;
2250 bb_ci->upper.z = bb[ci].upper.z + shz;
2253 /* Sets a simple list i-cell bounding box, including PBC shift */
2254 static inline void set_icell_bb(const Grid &iGrid,
2256 real shx, real shy, real shz,
2257 NbnxnPairlistCpuWork *work)
2259 set_icell_bb_simple(iGrid.iBoundingBoxes(), ci, shx, shy, shz,
2260 &work->iClusterData.bb[0]);
2264 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
2265 static void set_icell_bbxxxx_supersub(gmx::ArrayRef<const float> bb,
2267 real shx, real shy, real shz,
2270 constexpr int cellBBStride = packedBoundingBoxesIndex(c_gpuNumClusterPerCell);
2271 constexpr int pbbStride = c_packedBoundingBoxesDimSize;
2272 const int ia = ci*cellBBStride;
2273 for (int m = 0; m < cellBBStride; m += c_packedBoundingBoxesSize)
2275 for (int i = 0; i < pbbStride; i++)
2277 bb_ci[m + 0*pbbStride + i] = bb[ia + m + 0*pbbStride + i] + shx;
2278 bb_ci[m + 1*pbbStride + i] = bb[ia + m + 1*pbbStride + i] + shy;
2279 bb_ci[m + 2*pbbStride + i] = bb[ia + m + 2*pbbStride + i] + shz;
2280 bb_ci[m + 3*pbbStride + i] = bb[ia + m + 3*pbbStride + i] + shx;
2281 bb_ci[m + 4*pbbStride + i] = bb[ia + m + 4*pbbStride + i] + shy;
2282 bb_ci[m + 5*pbbStride + i] = bb[ia + m + 5*pbbStride + i] + shz;
2288 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
2289 gmx_unused static void set_icell_bb_supersub(gmx::ArrayRef<const BoundingBox> bb,
2291 real shx, real shy, real shz,
2294 for (int i = 0; i < c_gpuNumClusterPerCell; i++)
2296 set_icell_bb_simple(bb, ci*c_gpuNumClusterPerCell+i,
2302 /* Sets a super-cell and sub cell bounding boxes, including PBC shift */
2303 gmx_unused static void set_icell_bb(const Grid &iGrid,
2305 real shx, real shy, real shz,
2306 NbnxnPairlistGpuWork *work)
2309 set_icell_bbxxxx_supersub(iGrid.packedBoundingBoxes(), ci, shx, shy, shz,
2310 work->iSuperClusterData.bbPacked.data());
2312 set_icell_bb_supersub(iGrid.iBoundingBoxes(), ci, shx, shy, shz,
2313 work->iSuperClusterData.bb.data());
2317 /* Copies PBC shifted i-cell atom coordinates x,y,z to working array */
2318 static void icell_set_x_simple(int ci,
2319 real shx, real shy, real shz,
2320 int stride, const real *x,
2321 NbnxnPairlistCpuWork::IClusterData *iClusterData)
2323 const int ia = ci*c_nbnxnCpuIClusterSize;
2325 for (int i = 0; i < c_nbnxnCpuIClusterSize; i++)
2327 iClusterData->x[i*STRIDE_XYZ+XX] = x[(ia+i)*stride+XX] + shx;
2328 iClusterData->x[i*STRIDE_XYZ+YY] = x[(ia+i)*stride+YY] + shy;
2329 iClusterData->x[i*STRIDE_XYZ+ZZ] = x[(ia+i)*stride+ZZ] + shz;
2333 static void icell_set_x(int ci,
2334 real shx, real shy, real shz,
2335 int stride, const real *x,
2336 const Nbnxm::KernelType kernelType,
2337 NbnxnPairlistCpuWork *work)
2342 #ifdef GMX_NBNXN_SIMD_4XN
2343 case Nbnxm::KernelType::Cpu4xN_Simd_4xN:
2344 icell_set_x_simd_4xn(ci, shx, shy, shz, stride, x, work);
2347 #ifdef GMX_NBNXN_SIMD_2XNN
2348 case Nbnxm::KernelType::Cpu4xN_Simd_2xNN:
2349 icell_set_x_simd_2xnn(ci, shx, shy, shz, stride, x, work);
2353 case Nbnxm::KernelType::Cpu4x4_PlainC:
2354 icell_set_x_simple(ci, shx, shy, shz, stride, x, &work->iClusterData);
2357 GMX_ASSERT(false, "Unhandled case");
2362 /* Copies PBC shifted super-cell atom coordinates x,y,z to working array */
2363 static void icell_set_x(int ci,
2364 real shx, real shy, real shz,
2365 int stride, const real *x,
2366 Nbnxm::KernelType gmx_unused kernelType,
2367 NbnxnPairlistGpuWork *work)
2369 #if !GMX_SIMD4_HAVE_REAL
2371 real * x_ci = work->iSuperClusterData.x.data();
2373 int ia = ci*c_gpuNumClusterPerCell*c_nbnxnGpuClusterSize;
2374 for (int i = 0; i < c_gpuNumClusterPerCell*c_nbnxnGpuClusterSize; i++)
2376 x_ci[i*DIM + XX] = x[(ia+i)*stride + XX] + shx;
2377 x_ci[i*DIM + YY] = x[(ia+i)*stride + YY] + shy;
2378 x_ci[i*DIM + ZZ] = x[(ia+i)*stride + ZZ] + shz;
2381 #else /* !GMX_SIMD4_HAVE_REAL */
2383 real * x_ci = work->iSuperClusterData.xSimd.data();
2385 for (int si = 0; si < c_gpuNumClusterPerCell; si++)
2387 for (int i = 0; i < c_nbnxnGpuClusterSize; i += GMX_SIMD4_WIDTH)
2389 int io = si*c_nbnxnGpuClusterSize + i;
2390 int ia = ci*c_gpuNumClusterPerCell*c_nbnxnGpuClusterSize + io;
2391 for (int j = 0; j < GMX_SIMD4_WIDTH; j++)
2393 x_ci[io*DIM + j + XX*GMX_SIMD4_WIDTH] = x[(ia + j)*stride + XX] + shx;
2394 x_ci[io*DIM + j + YY*GMX_SIMD4_WIDTH] = x[(ia + j)*stride + YY] + shy;
2395 x_ci[io*DIM + j + ZZ*GMX_SIMD4_WIDTH] = x[(ia + j)*stride + ZZ] + shz;
2400 #endif /* !GMX_SIMD4_HAVE_REAL */
2403 static real minimum_subgrid_size_xy(const Grid &grid)
2405 const Grid::Dimensions &dims = grid.dimensions();
2407 if (grid.geometry().isSimple)
2409 return std::min(dims.cellSize[XX], dims.cellSize[YY]);
2413 return std::min(dims.cellSize[XX]/c_gpuNumClusterPerCellX,
2414 dims.cellSize[YY]/c_gpuNumClusterPerCellY);
2418 static real effective_buffer_1x1_vs_MxN(const Grid &iGrid,
2421 const real eff_1x1_buffer_fac_overest = 0.1;
2423 /* Determine an atom-pair list cut-off buffer size for atom pairs,
2424 * to be added to rlist (including buffer) used for MxN.
2425 * This is for converting an MxN list to a 1x1 list. This means we can't
2426 * use the normal buffer estimate, as we have an MxN list in which
2427 * some atom pairs beyond rlist are missing. We want to capture
2428 * the beneficial effect of buffering by extra pairs just outside rlist,
2429 * while removing the useless pairs that are further away from rlist.
2430 * (Also the buffer could have been set manually not using the estimate.)
2431 * This buffer size is an overestimate.
2432 * We add 10% of the smallest grid sub-cell dimensions.
2433 * Note that the z-size differs per cell and we don't use this,
2434 * so we overestimate.
2435 * With PME, the 10% value gives a buffer that is somewhat larger
2436 * than the effective buffer with a tolerance of 0.005 kJ/mol/ps.
2437 * Smaller tolerances or using RF lead to a smaller effective buffer,
2438 * so 10% gives a safe overestimate.
2440 return eff_1x1_buffer_fac_overest*(minimum_subgrid_size_xy(iGrid) +
2441 minimum_subgrid_size_xy(jGrid));
2444 /* Estimates the interaction volume^2 for non-local interactions */
2445 static real nonlocal_vol2(const struct gmx_domdec_zones_t *zones, const rvec ls, real r)
2453 /* Here we simply add up the volumes of 1, 2 or 3 1D decomposition
2454 * not home interaction volume^2. As these volumes are not additive,
2455 * this is an overestimate, but it would only be significant in the limit
2456 * of small cells, where we anyhow need to split the lists into
2457 * as small parts as possible.
2460 for (int z = 0; z < zones->n; z++)
2462 if (zones->shift[z][XX] + zones->shift[z][YY] + zones->shift[z][ZZ] == 1)
2467 for (int d = 0; d < DIM; d++)
2469 if (zones->shift[z][d] == 0)
2473 za *= zones->size[z].x1[d] - zones->size[z].x0[d];
2477 /* 4 octants of a sphere */
2478 vold_est = 0.25*M_PI*r*r*r*r;
2479 /* 4 quarter pie slices on the edges */
2480 vold_est += 4*cl*M_PI/6.0*r*r*r;
2481 /* One rectangular volume on a face */
2482 vold_est += ca*0.5*r*r;
2484 vol2_est_tot += vold_est*za;
2488 return vol2_est_tot;
2491 /* Estimates the average size of a full j-list for super/sub setup */
2492 static void get_nsubpair_target(const PairSearch &pairSearch,
2493 const InteractionLocality iloc,
2495 const int min_ci_balanced,
2496 int *nsubpair_target,
2497 float *nsubpair_tot_est)
2499 /* The target value of 36 seems to be the optimum for Kepler.
2500 * Maxwell is less sensitive to the exact value.
2502 const int nsubpair_target_min = 36;
2503 real r_eff_sup, vol_est, nsp_est, nsp_est_nl;
2505 const Grid &grid = pairSearch.gridSet().grids()[0];
2507 /* We don't need to balance list sizes if:
2508 * - We didn't request balancing.
2509 * - The number of grid cells >= the number of lists requested,
2510 * since we will always generate at least #cells lists.
2511 * - We don't have any cells, since then there won't be any lists.
2513 if (min_ci_balanced <= 0 || grid.numCells() >= min_ci_balanced || grid.numCells() == 0)
2515 /* nsubpair_target==0 signals no balancing */
2516 *nsubpair_target = 0;
2517 *nsubpair_tot_est = 0;
2523 const int numAtomsCluster = grid.geometry().numAtomsICluster;
2524 const Grid::Dimensions &dims = grid.dimensions();
2526 ls[XX] = dims.cellSize[XX]/c_gpuNumClusterPerCellX;
2527 ls[YY] = dims.cellSize[YY]/c_gpuNumClusterPerCellY;
2528 ls[ZZ] = numAtomsCluster/(dims.atomDensity*ls[XX]*ls[YY]);
2530 /* The formulas below are a heuristic estimate of the average nsj per si*/
2531 r_eff_sup = rlist + nbnxn_get_rlist_effective_inc(numAtomsCluster, ls);
2533 if (!pairSearch.domainSetup().haveDomDec ||
2534 pairSearch.domainSetup().zones->n == 1)
2541 gmx::square(dims.atomDensity/numAtomsCluster)*
2542 nonlocal_vol2(pairSearch.domainSetup().zones, ls, r_eff_sup);
2545 if (iloc == InteractionLocality::Local)
2547 /* Sub-cell interacts with itself */
2548 vol_est = ls[XX]*ls[YY]*ls[ZZ];
2549 /* 6/2 rectangular volume on the faces */
2550 vol_est += (ls[XX]*ls[YY] + ls[XX]*ls[ZZ] + ls[YY]*ls[ZZ])*r_eff_sup;
2551 /* 12/2 quarter pie slices on the edges */
2552 vol_est += 2*(ls[XX] + ls[YY] + ls[ZZ])*0.25*M_PI*gmx::square(r_eff_sup);
2553 /* 4 octants of a sphere */
2554 vol_est += 0.5*4.0/3.0*M_PI*gmx::power3(r_eff_sup);
2556 /* Estimate the number of cluster pairs as the local number of
2557 * clusters times the volume they interact with times the density.
2559 nsp_est = grid.numClusters()*vol_est*dims.atomDensity/numAtomsCluster;
2561 /* Subtract the non-local pair count */
2562 nsp_est -= nsp_est_nl;
2564 /* For small cut-offs nsp_est will be an underesimate.
2565 * With DD nsp_est_nl is an overestimate so nsp_est can get negative.
2566 * So to avoid too small or negative nsp_est we set a minimum of
2567 * all cells interacting with all 3^3 direct neighbors (3^3-1)/2+1=14.
2568 * This might be a slight overestimate for small non-periodic groups of
2569 * atoms as will occur for a local domain with DD, but for small
2570 * groups of atoms we'll anyhow be limited by nsubpair_target_min,
2571 * so this overestimation will not matter.
2573 nsp_est = std::max(nsp_est, grid.numClusters()*14._real);
2577 fprintf(debug, "nsp_est local %5.1f non-local %5.1f\n",
2578 nsp_est, nsp_est_nl);
2583 nsp_est = nsp_est_nl;
2586 /* Thus the (average) maximum j-list size should be as follows.
2587 * Since there is overhead, we shouldn't make the lists too small
2588 * (and we can't chop up j-groups) so we use a minimum target size of 36.
2590 *nsubpair_target = std::max(nsubpair_target_min,
2591 roundToInt(nsp_est/min_ci_balanced));
2592 *nsubpair_tot_est = static_cast<int>(nsp_est);
2596 fprintf(debug, "nbl nsp estimate %.1f, nsubpair_target %d\n",
2597 nsp_est, *nsubpair_target);
2601 /* Debug list print function */
2602 static void print_nblist_ci_cj(FILE *fp,
2603 const NbnxnPairlistCpu &nbl)
2605 for (const nbnxn_ci_t &ciEntry : nbl.ci)
2607 fprintf(fp, "ci %4d shift %2d ncj %3d\n",
2608 ciEntry.ci, ciEntry.shift,
2609 ciEntry.cj_ind_end - ciEntry.cj_ind_start);
2611 for (int j = ciEntry.cj_ind_start; j < ciEntry.cj_ind_end; j++)
2613 fprintf(fp, " cj %5d imask %x\n",
2620 /* Debug list print function */
2621 static void print_nblist_sci_cj(FILE *fp,
2622 const NbnxnPairlistGpu &nbl)
2624 for (const nbnxn_sci_t &sci : nbl.sci)
2626 fprintf(fp, "ci %4d shift %2d ncj4 %2d\n",
2628 sci.numJClusterGroups());
2631 for (int j4 = sci.cj4_ind_start; j4 < sci.cj4_ind_end; j4++)
2633 for (int j = 0; j < c_nbnxnGpuJgroupSize; j++)
2635 fprintf(fp, " sj %5d imask %x\n",
2637 nbl.cj4[j4].imei[0].imask);
2638 for (int si = 0; si < c_gpuNumClusterPerCell; si++)
2640 if (nbl.cj4[j4].imei[0].imask & (1U << (j*c_gpuNumClusterPerCell + si)))
2647 fprintf(fp, "ci %4d shift %2d ncj4 %2d ncp %3d\n",
2649 sci.numJClusterGroups(),
2654 /* Combine pair lists *nbl generated on multiple threads nblc */
2655 static void combine_nblists(gmx::ArrayRef<const NbnxnPairlistGpu> nbls,
2656 NbnxnPairlistGpu *nblc)
2658 int nsci = nblc->sci.size();
2659 int ncj4 = nblc->cj4.size();
2660 int nexcl = nblc->excl.size();
2661 for (auto &nbl : nbls)
2663 nsci += nbl.sci.size();
2664 ncj4 += nbl.cj4.size();
2665 nexcl += nbl.excl.size();
2668 /* Resize with the final, combined size, so we can fill in parallel */
2669 /* NOTE: For better performance we should use default initialization */
2670 nblc->sci.resize(nsci);
2671 nblc->cj4.resize(ncj4);
2672 nblc->excl.resize(nexcl);
2674 /* Each thread should copy its own data to the combined arrays,
2675 * as otherwise data will go back and forth between different caches.
2677 #if GMX_OPENMP && !(defined __clang_analyzer__)
2678 int nthreads = gmx_omp_nthreads_get(emntPairsearch);
2681 #pragma omp parallel for num_threads(nthreads) schedule(static)
2682 for (int n = 0; n < nbls.ssize(); n++)
2686 /* Determine the offset in the combined data for our thread.
2687 * Note that the original sizes in nblc are lost.
2689 int sci_offset = nsci;
2690 int cj4_offset = ncj4;
2691 int excl_offset = nexcl;
2693 for (int i = n; i < nbls.ssize(); i++)
2695 sci_offset -= nbls[i].sci.size();
2696 cj4_offset -= nbls[i].cj4.size();
2697 excl_offset -= nbls[i].excl.size();
2700 const NbnxnPairlistGpu &nbli = nbls[n];
2702 for (size_t i = 0; i < nbli.sci.size(); i++)
2704 nblc->sci[sci_offset + i] = nbli.sci[i];
2705 nblc->sci[sci_offset + i].cj4_ind_start += cj4_offset;
2706 nblc->sci[sci_offset + i].cj4_ind_end += cj4_offset;
2709 for (size_t j4 = 0; j4 < nbli.cj4.size(); j4++)
2711 nblc->cj4[cj4_offset + j4] = nbli.cj4[j4];
2712 nblc->cj4[cj4_offset + j4].imei[0].excl_ind += excl_offset;
2713 nblc->cj4[cj4_offset + j4].imei[1].excl_ind += excl_offset;
2716 for (size_t j4 = 0; j4 < nbli.excl.size(); j4++)
2718 nblc->excl[excl_offset + j4] = nbli.excl[j4];
2721 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
2724 for (auto &nbl : nbls)
2726 nblc->nci_tot += nbl.nci_tot;
2730 static void balance_fep_lists(gmx::ArrayRef<t_nblist *> fepLists,
2731 gmx::ArrayRef<PairsearchWork> work)
2733 const int numLists = fepLists.ssize();
2737 /* Nothing to balance */
2741 /* Count the total i-lists and pairs */
2744 for (auto list : fepLists)
2746 nri_tot += list->nri;
2747 nrj_tot += list->nrj;
2750 const int nrj_target = (nrj_tot + numLists - 1)/numLists;
2752 GMX_ASSERT(gmx_omp_nthreads_get(emntNonbonded) == numLists,
2753 "We should have as many work objects as FEP lists");
2755 #pragma omp parallel for schedule(static) num_threads(numLists)
2756 for (int th = 0; th < numLists; th++)
2760 t_nblist *nbl = work[th].nbl_fep.get();
2762 /* Note that here we allocate for the total size, instead of
2763 * a per-thread esimate (which is hard to obtain).
2765 if (nri_tot > nbl->maxnri)
2767 nbl->maxnri = over_alloc_large(nri_tot);
2768 reallocate_nblist(nbl);
2770 if (nri_tot > nbl->maxnri || nrj_tot > nbl->maxnrj)
2772 nbl->maxnrj = over_alloc_small(nrj_tot);
2773 srenew(nbl->jjnr, nbl->maxnrj);
2774 srenew(nbl->excl_fep, nbl->maxnrj);
2777 clear_pairlist_fep(nbl);
2779 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
2782 /* Loop over the source lists and assign and copy i-entries */
2784 t_nblist *nbld = work[th_dest].nbl_fep.get();
2785 for (int th = 0; th < numLists; th++)
2787 t_nblist *nbls = fepLists[th];
2789 for (int i = 0; i < nbls->nri; i++)
2793 /* The number of pairs in this i-entry */
2794 nrj = nbls->jindex[i+1] - nbls->jindex[i];
2796 /* Decide if list th_dest is too large and we should procede
2797 * to the next destination list.
2799 if (th_dest + 1 < numLists && nbld->nrj > 0 &&
2800 nbld->nrj + nrj - nrj_target > nrj_target - nbld->nrj)
2803 nbld = work[th_dest].nbl_fep.get();
2806 nbld->iinr[nbld->nri] = nbls->iinr[i];
2807 nbld->gid[nbld->nri] = nbls->gid[i];
2808 nbld->shift[nbld->nri] = nbls->shift[i];
2810 for (int j = nbls->jindex[i]; j < nbls->jindex[i+1]; j++)
2812 nbld->jjnr[nbld->nrj] = nbls->jjnr[j];
2813 nbld->excl_fep[nbld->nrj] = nbls->excl_fep[j];
2817 nbld->jindex[nbld->nri] = nbld->nrj;
2821 /* Swap the list pointers */
2822 for (int th = 0; th < numLists; th++)
2824 t_nblist *nbl_tmp = work[th].nbl_fep.release();
2825 work[th].nbl_fep.reset(fepLists[th]);
2826 fepLists[th] = nbl_tmp;
2830 fprintf(debug, "nbl_fep[%d] nri %4d nrj %4d\n",
2838 /* Returns the next ci to be processes by our thread */
2839 static gmx_bool next_ci(const Grid &grid,
2840 int nth, int ci_block,
2841 int *ci_x, int *ci_y,
2847 if (*ci_b == ci_block)
2849 /* Jump to the next block assigned to this task */
2850 *ci += (nth - 1)*ci_block;
2854 if (*ci >= grid.numCells())
2859 while (*ci >= grid.firstCellInColumn(*ci_x*grid.dimensions().numCells[YY] + *ci_y + 1))
2862 if (*ci_y == grid.dimensions().numCells[YY])
2872 /* Returns the distance^2 for which we put cell pairs in the list
2873 * without checking atom pair distances. This is usually < rlist^2.
2875 static float boundingbox_only_distance2(const Grid::Dimensions &iGridDims,
2876 const Grid::Dimensions &jGridDims,
2880 /* If the distance between two sub-cell bounding boxes is less
2881 * than this distance, do not check the distance between
2882 * all particle pairs in the sub-cell, since then it is likely
2883 * that the box pair has atom pairs within the cut-off.
2884 * We use the nblist cut-off minus 0.5 times the average x/y diagonal
2885 * spacing of the sub-cells. Around 40% of the checked pairs are pruned.
2886 * Using more than 0.5 gains at most 0.5%.
2887 * If forces are calculated more than twice, the performance gain
2888 * in the force calculation outweighs the cost of checking.
2889 * Note that with subcell lists, the atom-pair distance check
2890 * is only performed when only 1 out of 8 sub-cells in within range,
2891 * this is because the GPU is much faster than the cpu.
2896 bbx = 0.5*(iGridDims.cellSize[XX] + jGridDims.cellSize[XX]);
2897 bby = 0.5*(iGridDims.cellSize[YY] + jGridDims.cellSize[YY]);
2900 bbx /= c_gpuNumClusterPerCellX;
2901 bby /= c_gpuNumClusterPerCellY;
2904 rbb2 = std::max(0.0, rlist - 0.5*std::sqrt(bbx*bbx + bby*bby));
2910 return (float)((1+GMX_FLOAT_EPS)*rbb2);
2914 static int get_ci_block_size(const Grid &iGrid,
2915 const bool haveDomDec,
2918 const int ci_block_enum = 5;
2919 const int ci_block_denom = 11;
2920 const int ci_block_min_atoms = 16;
2923 /* Here we decide how to distribute the blocks over the threads.
2924 * We use prime numbers to try to avoid that the grid size becomes
2925 * a multiple of the number of threads, which would lead to some
2926 * threads getting "inner" pairs and others getting boundary pairs,
2927 * which in turns will lead to load imbalance between threads.
2928 * Set the block size as 5/11/ntask times the average number of cells
2929 * in a y,z slab. This should ensure a quite uniform distribution
2930 * of the grid parts of the different thread along all three grid
2931 * zone boundaries with 3D domain decomposition. At the same time
2932 * the blocks will not become too small.
2934 GMX_ASSERT(iGrid.dimensions().numCells[XX] > 0, "Grid can't be empty");
2935 GMX_ASSERT(numLists > 0, "We need at least one list");
2936 ci_block = (iGrid.numCells()*ci_block_enum)/(ci_block_denom*iGrid.dimensions().numCells[XX]*numLists);
2938 const int numAtomsPerCell = iGrid.geometry().numAtomsPerCell;
2940 /* Ensure the blocks are not too small: avoids cache invalidation */
2941 if (ci_block*numAtomsPerCell < ci_block_min_atoms)
2943 ci_block = (ci_block_min_atoms + numAtomsPerCell - 1)/numAtomsPerCell;
2946 /* Without domain decomposition
2947 * or with less than 3 blocks per task, divide in nth blocks.
2949 if (!haveDomDec || numLists*3*ci_block > iGrid.numCells())
2951 ci_block = (iGrid.numCells() + numLists - 1)/numLists;
2954 if (ci_block > 1 && (numLists - 1)*ci_block >= iGrid.numCells())
2956 /* Some threads have no work. Although reducing the block size
2957 * does not decrease the block count on the first few threads,
2958 * with GPUs better mixing of "upper" cells that have more empty
2959 * clusters results in a somewhat lower max load over all threads.
2960 * Without GPUs the regime of so few atoms per thread is less
2961 * performance relevant, but with 8-wide SIMD the same reasoning
2962 * applies, since the pair list uses 4 i-atom "sub-clusters".
2970 /* Returns the number of bits to right-shift a cluster index to obtain
2971 * the corresponding force buffer flag index.
2973 static int getBufferFlagShift(int numAtomsPerCluster)
2975 int bufferFlagShift = 0;
2976 while ((numAtomsPerCluster << bufferFlagShift) < NBNXN_BUFFERFLAG_SIZE)
2981 return bufferFlagShift;
2984 static bool pairlistIsSimple(const NbnxnPairlistCpu gmx_unused &pairlist)
2989 static bool pairlistIsSimple(const NbnxnPairlistGpu gmx_unused &pairlist)
2994 static void makeClusterListWrapper(NbnxnPairlistCpu *nbl,
2995 const Grid gmx_unused &iGrid,
2998 const int firstCell,
3000 const bool excludeSubDiagonal,
3001 const nbnxn_atomdata_t *nbat,
3004 const Nbnxm::KernelType kernelType,
3005 int *numDistanceChecks)
3009 case Nbnxm::KernelType::Cpu4x4_PlainC:
3010 makeClusterListSimple(jGrid,
3011 nbl, ci, firstCell, lastCell,
3017 #ifdef GMX_NBNXN_SIMD_4XN
3018 case Nbnxm::KernelType::Cpu4xN_Simd_4xN:
3019 makeClusterListSimd4xn(jGrid,
3020 nbl, ci, firstCell, lastCell,
3027 #ifdef GMX_NBNXN_SIMD_2XNN
3028 case Nbnxm::KernelType::Cpu4xN_Simd_2xNN:
3029 makeClusterListSimd2xnn(jGrid,
3030 nbl, ci, firstCell, lastCell,
3038 GMX_ASSERT(false, "Unhandled kernel type");
3042 static void makeClusterListWrapper(NbnxnPairlistGpu *nbl,
3043 const Grid &gmx_unused iGrid,
3046 const int firstCell,
3048 const bool excludeSubDiagonal,
3049 const nbnxn_atomdata_t *nbat,
3052 Nbnxm::KernelType gmx_unused kernelType,
3053 int *numDistanceChecks)
3055 for (int cj = firstCell; cj <= lastCell; cj++)
3057 make_cluster_list_supersub(iGrid, jGrid,
3060 nbat->xstride, nbat->x().data(),
3066 static int getNumSimpleJClustersInList(const NbnxnPairlistCpu &nbl)
3068 return nbl.cj.size();
3071 static int getNumSimpleJClustersInList(const gmx_unused NbnxnPairlistGpu &nbl)
3076 static void incrementNumSimpleJClustersInList(NbnxnPairlistCpu *nbl,
3079 nbl->ncjInUse += nbl->cj.size() - ncj_old_j;
3082 static void incrementNumSimpleJClustersInList(NbnxnPairlistGpu gmx_unused *nbl,
3083 int gmx_unused ncj_old_j)
3087 static void checkListSizeConsistency(const NbnxnPairlistCpu &nbl,
3088 const bool haveFreeEnergy)
3090 GMX_RELEASE_ASSERT(static_cast<size_t>(nbl.ncjInUse) == nbl.cj.size() || haveFreeEnergy,
3091 "Without free-energy all cj pair-list entries should be in use. "
3092 "Note that subsequent code does not make use of the equality, "
3093 "this check is only here to catch bugs");
3096 static void checkListSizeConsistency(const NbnxnPairlistGpu gmx_unused &nbl,
3097 bool gmx_unused haveFreeEnergy)
3099 /* We currently can not check consistency here */
3102 /* Set the buffer flags for newly added entries in the list */
3103 static void setBufferFlags(const NbnxnPairlistCpu &nbl,
3104 const int ncj_old_j,
3105 const int gridj_flag_shift,
3106 gmx_bitmask_t *gridj_flag,
3109 if (gmx::ssize(nbl.cj) > ncj_old_j)
3111 int cbFirst = nbl.cj[ncj_old_j].cj >> gridj_flag_shift;
3112 int cbLast = nbl.cj.back().cj >> gridj_flag_shift;
3113 for (int cb = cbFirst; cb <= cbLast; cb++)
3115 bitmask_init_bit(&gridj_flag[cb], th);
3120 static void setBufferFlags(const NbnxnPairlistGpu gmx_unused &nbl,
3121 int gmx_unused ncj_old_j,
3122 int gmx_unused gridj_flag_shift,
3123 gmx_bitmask_t gmx_unused *gridj_flag,
3126 GMX_ASSERT(false, "This function should never be called");
3129 /* Generates the part of pair-list nbl assigned to our thread */
3130 template <typename T>
3131 static void nbnxn_make_pairlist_part(const PairSearch &pairSearch,
3134 PairsearchWork *work,
3135 const nbnxn_atomdata_t *nbat,
3136 const t_blocka &exclusions,
3138 const Nbnxm::KernelType kernelType,
3140 gmx_bool bFBufferFlag,
3143 float nsubpair_tot_est,
3152 int ci_b, ci, ci_x, ci_y, ci_xy;
3154 real bx0, bx1, by0, by1, bz0, bz1;
3156 real d2cx, d2z, d2z_cx, d2z_cy, d2zx, d2zxy, d2xy;
3157 int cxf, cxl, cyf, cyf_x, cyl;
3158 int numDistanceChecks;
3159 int gridi_flag_shift = 0, gridj_flag_shift = 0;
3160 gmx_bitmask_t *gridj_flag = nullptr;
3161 int ncj_old_i, ncj_old_j;
3163 if (jGrid.geometry().isSimple != pairlistIsSimple(*nbl) ||
3164 iGrid.geometry().isSimple != pairlistIsSimple(*nbl))
3166 gmx_incons("Grid incompatible with pair-list");
3170 GMX_ASSERT(nbl->na_ci == jGrid.geometry().numAtomsICluster,
3171 "The cluster sizes in the list and grid should match");
3172 nbl->na_cj = Nbnxm::JClusterSizePerKernelType[kernelType];
3173 na_cj_2log = get_2log(nbl->na_cj);
3179 /* Determine conversion of clusters to flag blocks */
3180 gridi_flag_shift = getBufferFlagShift(nbl->na_ci);
3181 gridj_flag_shift = getBufferFlagShift(nbl->na_cj);
3183 gridj_flag = work->buffer_flags.flag;
3186 const Nbnxm::GridSet &gridSet = pairSearch.gridSet();
3188 gridSet.getBox(box);
3190 const bool haveFep = gridSet.haveFep();
3192 const real rlist2 = nbl->rlist*nbl->rlist;
3194 if (haveFep && !pairlistIsSimple(*nbl))
3196 /* Determine an atom-pair list cut-off distance for FEP atom pairs.
3197 * We should not simply use rlist, since then we would not have
3198 * the small, effective buffering of the NxN lists.
3199 * The buffer is on overestimate, but the resulting cost for pairs
3200 * beyond rlist is neglible compared to the FEP pairs within rlist.
3202 rl_fep2 = nbl->rlist + effective_buffer_1x1_vs_MxN(iGrid, jGrid);
3206 fprintf(debug, "nbl_fep atom-pair rlist %f\n", rl_fep2);
3208 rl_fep2 = rl_fep2*rl_fep2;
3211 const Grid::Dimensions &iGridDims = iGrid.dimensions();
3212 const Grid::Dimensions &jGridDims = jGrid.dimensions();
3214 rbb2 = boundingbox_only_distance2(iGridDims, jGridDims, nbl->rlist, pairlistIsSimple(*nbl));
3218 fprintf(debug, "nbl bounding box only distance %f\n", std::sqrt(rbb2));
3221 const bool isIntraGridList = (&iGrid == &jGrid);
3223 /* Set the shift range */
3224 for (int d = 0; d < DIM; d++)
3226 /* Check if we need periodicity shifts.
3227 * Without PBC or with domain decomposition we don't need them.
3229 if (d >= ePBC2npbcdim(pairSearch.domainSetup().ePBC) ||
3230 pairSearch.domainSetup().haveDomDecPerDim[d])
3236 const real listRangeCellToCell =
3237 listRangeForGridCellToGridCell(rlist, iGrid.dimensions(), jGrid.dimensions());
3239 box[XX][XX] - fabs(box[YY][XX]) - fabs(box[ZZ][XX]) < listRangeCellToCell)
3249 const bool bSimple = pairlistIsSimple(*nbl);
3250 gmx::ArrayRef<const BoundingBox> bb_i;
3252 gmx::ArrayRef<const float> pbb_i;
3255 bb_i = iGrid.iBoundingBoxes();
3259 pbb_i = iGrid.packedBoundingBoxes();
3262 /* We use the normal bounding box format for both grid types */
3263 bb_i = iGrid.iBoundingBoxes();
3265 gmx::ArrayRef<const BoundingBox1D> bbcz_i = iGrid.zBoundingBoxes();
3266 gmx::ArrayRef<const int> flags_i = iGrid.clusterFlags();
3267 gmx::ArrayRef<const BoundingBox1D> bbcz_j = jGrid.zBoundingBoxes();
3268 int cell0_i = iGrid.cellOffset();
3272 fprintf(debug, "nbl nc_i %d col.av. %.1f ci_block %d\n",
3273 iGrid.numCells(), iGrid.numCells()/static_cast<double>(iGrid.numColumns()), ci_block);
3276 numDistanceChecks = 0;
3278 const real listRangeBBToJCell2 = gmx::square(listRangeForBoundingBoxToGridCell(rlist, jGrid.dimensions()));
3280 /* Initially ci_b and ci to 1 before where we want them to start,
3281 * as they will both be incremented in next_ci.
3284 ci = th*ci_block - 1;
3287 while (next_ci(iGrid, nth, ci_block, &ci_x, &ci_y, &ci_b, &ci))
3289 if (bSimple && flags_i[ci] == 0)
3294 ncj_old_i = getNumSimpleJClustersInList(*nbl);
3297 if (!isIntraGridList && shp[XX] == 0)
3301 bx1 = bb_i[ci].upper.x;
3305 bx1 = iGridDims.lowerCorner[XX] + (ci_x+1)*iGridDims.cellSize[XX];
3307 if (bx1 < jGridDims.lowerCorner[XX])
3309 d2cx = gmx::square(jGridDims.lowerCorner[XX] - bx1);
3311 if (d2cx >= listRangeBBToJCell2)
3318 ci_xy = ci_x*iGridDims.numCells[YY] + ci_y;
3320 /* Loop over shift vectors in three dimensions */
3321 for (int tz = -shp[ZZ]; tz <= shp[ZZ]; tz++)
3323 const real shz = tz*box[ZZ][ZZ];
3325 bz0 = bbcz_i[ci].lower + shz;
3326 bz1 = bbcz_i[ci].upper + shz;
3334 d2z = gmx::square(bz1);
3338 d2z = gmx::square(bz0 - box[ZZ][ZZ]);
3341 d2z_cx = d2z + d2cx;
3343 if (d2z_cx >= rlist2)
3348 bz1_frac = bz1/iGrid.numCellsInColumn(ci_xy);
3353 /* The check with bz1_frac close to or larger than 1 comes later */
3355 for (int ty = -shp[YY]; ty <= shp[YY]; ty++)
3357 const real shy = ty*box[YY][YY] + tz*box[ZZ][YY];
3361 by0 = bb_i[ci].lower.y + shy;
3362 by1 = bb_i[ci].upper.y + shy;
3366 by0 = iGridDims.lowerCorner[YY] + (ci_y )*iGridDims.cellSize[YY] + shy;
3367 by1 = iGridDims.lowerCorner[YY] + (ci_y + 1)*iGridDims.cellSize[YY] + shy;
3370 get_cell_range<YY>(by0, by1,
3381 if (by1 < jGridDims.lowerCorner[YY])
3383 d2z_cy += gmx::square(jGridDims.lowerCorner[YY] - by1);
3385 else if (by0 > jGridDims.upperCorner[YY])
3387 d2z_cy += gmx::square(by0 - jGridDims.upperCorner[YY]);
3390 for (int tx = -shp[XX]; tx <= shp[XX]; tx++)
3392 const int shift = XYZ2IS(tx, ty, tz);
3394 const bool excludeSubDiagonal = (isIntraGridList && shift == CENTRAL);
3396 if (c_pbcShiftBackward && isIntraGridList && shift > CENTRAL)
3401 const real shx = tx*box[XX][XX] + ty*box[YY][XX] + tz*box[ZZ][XX];
3405 bx0 = bb_i[ci].lower.x + shx;
3406 bx1 = bb_i[ci].upper.x + shx;
3410 bx0 = iGridDims.lowerCorner[XX] + (ci_x )*iGridDims.cellSize[XX] + shx;
3411 bx1 = iGridDims.lowerCorner[XX] + (ci_x+1)*iGridDims.cellSize[XX] + shx;
3414 get_cell_range<XX>(bx0, bx1,
3424 addNewIEntry(nbl, cell0_i+ci, shift, flags_i[ci]);
3426 if ((!c_pbcShiftBackward || excludeSubDiagonal) &&
3429 /* Leave the pairs with i > j.
3430 * x is the major index, so skip half of it.
3435 set_icell_bb(iGrid, ci, shx, shy, shz,
3438 icell_set_x(cell0_i+ci, shx, shy, shz,
3439 nbat->xstride, nbat->x().data(),
3443 for (int cx = cxf; cx <= cxl; cx++)
3446 if (jGridDims.lowerCorner[XX] + cx*jGridDims.cellSize[XX] > bx1)
3448 d2zx += gmx::square(jGridDims.lowerCorner[XX] + cx*jGridDims.cellSize[XX] - bx1);
3450 else if (jGridDims.lowerCorner[XX] + (cx+1)*jGridDims.cellSize[XX] < bx0)
3452 d2zx += gmx::square(jGridDims.lowerCorner[XX] + (cx+1)*jGridDims.cellSize[XX] - bx0);
3455 if (isIntraGridList &&
3457 (!c_pbcShiftBackward || shift == CENTRAL) &&
3460 /* Leave the pairs with i > j.
3461 * Skip half of y when i and j have the same x.
3470 for (int cy = cyf_x; cy <= cyl; cy++)
3472 const int columnStart = jGrid.firstCellInColumn(cx*jGridDims.numCells[YY] + cy);
3473 const int columnEnd = jGrid.firstCellInColumn(cx*jGridDims.numCells[YY] + cy + 1);
3476 if (jGridDims.lowerCorner[YY] + cy*jGridDims.cellSize[YY] > by1)
3478 d2zxy += gmx::square(jGridDims.lowerCorner[YY] + cy*jGridDims.cellSize[YY] - by1);
3480 else if (jGridDims.lowerCorner[YY] + (cy + 1)*jGridDims.cellSize[YY] < by0)
3482 d2zxy += gmx::square(jGridDims.lowerCorner[YY] + (cy + 1)*jGridDims.cellSize[YY] - by0);
3484 if (columnStart < columnEnd && d2zxy < listRangeBBToJCell2)
3486 /* To improve efficiency in the common case
3487 * of a homogeneous particle distribution,
3488 * we estimate the index of the middle cell
3489 * in range (midCell). We search down and up
3490 * starting from this index.
3492 * Note that the bbcz_j array contains bounds
3493 * for i-clusters, thus for clusters of 4 atoms.
3494 * For the common case where the j-cluster size
3495 * is 8, we could step with a stride of 2,
3496 * but we do not do this because it would
3497 * complicate this code even more.
3499 int midCell = columnStart + static_cast<int>(bz1_frac*(columnEnd - columnStart));
3500 if (midCell >= columnEnd)
3502 midCell = columnEnd - 1;
3507 /* Find the lowest cell that can possibly
3509 * Check if we hit the bottom of the grid,
3510 * if the j-cell is below the i-cell and if so,
3511 * if it is within range.
3513 int downTestCell = midCell;
3514 while (downTestCell >= columnStart &&
3515 (bbcz_j[downTestCell].upper >= bz0 ||
3516 d2xy + gmx::square(bbcz_j[downTestCell].upper - bz0) < rlist2))
3520 int firstCell = downTestCell + 1;
3522 /* Find the highest cell that can possibly
3524 * Check if we hit the top of the grid,
3525 * if the j-cell is above the i-cell and if so,
3526 * if it is within range.
3528 int upTestCell = midCell + 1;
3529 while (upTestCell < columnEnd &&
3530 (bbcz_j[upTestCell].lower <= bz1 ||
3531 d2xy + gmx::square(bbcz_j[upTestCell].lower - bz1) < rlist2))
3535 int lastCell = upTestCell - 1;
3537 #define NBNXN_REFCODE 0
3540 /* Simple reference code, for debugging,
3541 * overrides the more complex code above.
3543 firstCell = columnEnd;
3545 for (int k = columnStart; k < columnEnd; k++)
3547 if (d2xy + gmx::square(bbcz_j[k*NNBSBB_D + 1] - bz0) < rlist2 &&
3552 if (d2xy + gmx::square(bbcz_j[k*NNBSBB_D] - bz1) < rlist2 &&
3561 if (isIntraGridList)
3563 /* We want each atom/cell pair only once,
3564 * only use cj >= ci.
3566 if (!c_pbcShiftBackward || shift == CENTRAL)
3568 firstCell = std::max(firstCell, ci);
3572 if (firstCell <= lastCell)
3574 GMX_ASSERT(firstCell >= columnStart && lastCell < columnEnd, "The range should reside within the current grid column");
3576 /* For f buffer flags with simple lists */
3577 ncj_old_j = getNumSimpleJClustersInList(*nbl);
3579 makeClusterListWrapper(nbl,
3581 jGrid, firstCell, lastCell,
3586 &numDistanceChecks);
3590 setBufferFlags(*nbl, ncj_old_j, gridj_flag_shift,
3594 incrementNumSimpleJClustersInList(nbl, ncj_old_j);
3600 /* Set the exclusions for this ci list */
3601 setExclusionsForIEntry(gridSet,
3605 *getOpenIEntry(nbl),
3610 make_fep_list(gridSet.atomIndices(), nbat, nbl,
3615 iGrid, jGrid, nbl_fep);
3618 /* Close this ci list */
3621 progBal, nsubpair_tot_est,
3627 if (bFBufferFlag && getNumSimpleJClustersInList(*nbl) > ncj_old_i)
3629 bitmask_init_bit(&(work->buffer_flags.flag[(iGrid.cellOffset() + ci) >> gridi_flag_shift]), th);
3633 work->ndistc = numDistanceChecks;
3635 checkListSizeConsistency(*nbl, haveFep);
3639 fprintf(debug, "number of distance checks %d\n", numDistanceChecks);
3641 print_nblist_statistics(debug, *nbl, pairSearch, rlist);
3645 fprintf(debug, "nbl FEP list pairs: %d\n", nbl_fep->nrj);
3650 static void reduce_buffer_flags(const PairSearch &pairSearch,
3652 const nbnxn_buffer_flags_t *dest)
3654 for (int s = 0; s < nsrc; s++)
3656 gmx_bitmask_t * flag = pairSearch.work()[s].buffer_flags.flag;
3658 for (int b = 0; b < dest->nflag; b++)
3660 bitmask_union(&(dest->flag[b]), flag[b]);
3665 static void print_reduction_cost(const nbnxn_buffer_flags_t *flags, int nout)
3667 int nelem, nkeep, ncopy, nred, out;
3668 gmx_bitmask_t mask_0;
3674 bitmask_init_bit(&mask_0, 0);
3675 for (int b = 0; b < flags->nflag; b++)
3677 if (bitmask_is_equal(flags->flag[b], mask_0))
3679 /* Only flag 0 is set, no copy of reduction required */
3683 else if (!bitmask_is_zero(flags->flag[b]))
3686 for (out = 0; out < nout; out++)
3688 if (bitmask_is_set(flags->flag[b], out))
3705 fprintf(debug, "nbnxn reduction: #flag %d #list %d elem %4.2f, keep %4.2f copy %4.2f red %4.2f\n",
3707 nelem/static_cast<double>(flags->nflag),
3708 nkeep/static_cast<double>(flags->nflag),
3709 ncopy/static_cast<double>(flags->nflag),
3710 nred/static_cast<double>(flags->nflag));
3713 /* Copies the list entries from src to dest when cjStart <= *cjGlobal < cjEnd.
3714 * *cjGlobal is updated with the cj count in src.
3715 * When setFlags==true, flag bit t is set in flag for all i and j clusters.
3717 template<bool setFlags>
3718 static void copySelectedListRange(const nbnxn_ci_t * gmx_restrict srcCi,
3719 const NbnxnPairlistCpu * gmx_restrict src,
3720 NbnxnPairlistCpu * gmx_restrict dest,
3721 gmx_bitmask_t *flag,
3722 int iFlagShift, int jFlagShift, int t)
3724 const int ncj = srcCi->cj_ind_end - srcCi->cj_ind_start;
3726 dest->ci.push_back(*srcCi);
3727 dest->ci.back().cj_ind_start = dest->cj.size();
3728 dest->ci.back().cj_ind_end = dest->cj.size() + ncj;
3732 bitmask_init_bit(&flag[srcCi->ci >> iFlagShift], t);
3735 for (int j = srcCi->cj_ind_start; j < srcCi->cj_ind_end; j++)
3737 dest->cj.push_back(src->cj[j]);
3741 /* NOTE: This is relatively expensive, since this
3742 * operation is done for all elements in the list,
3743 * whereas at list generation this is done only
3744 * once for each flag entry.
3746 bitmask_init_bit(&flag[src->cj[j].cj >> jFlagShift], t);
3751 /* This routine re-balances the pairlists such that all are nearly equally
3752 * sized. Only whole i-entries are moved between lists. These are moved
3753 * between the ends of the lists, such that the buffer reduction cost should
3754 * not change significantly.
3755 * Note that all original reduction flags are currently kept. This can lead
3756 * to reduction of parts of the force buffer that could be avoided. But since
3757 * the original lists are quite balanced, this will only give minor overhead.
3759 static void rebalanceSimpleLists(gmx::ArrayRef<const NbnxnPairlistCpu> srcSet,
3760 gmx::ArrayRef<NbnxnPairlistCpu> destSet,
3761 gmx::ArrayRef<PairsearchWork> searchWork)
3764 for (auto &src : srcSet)
3766 ncjTotal += src.ncjInUse;
3768 const int numLists = srcSet.ssize();
3769 const int ncjTarget = (ncjTotal + numLists - 1)/numLists;
3771 #pragma omp parallel num_threads(numLists)
3773 int t = gmx_omp_get_thread_num();
3775 int cjStart = ncjTarget* t;
3776 int cjEnd = ncjTarget*(t + 1);
3778 /* The destination pair-list for task/thread t */
3779 NbnxnPairlistCpu &dest = destSet[t];
3781 clear_pairlist(&dest);
3782 dest.na_cj = srcSet[0].na_cj;
3784 /* Note that the flags in the work struct (still) contain flags
3785 * for all entries that are present in srcSet->nbl[t].
3787 gmx_bitmask_t *flag = searchWork[t].buffer_flags.flag;
3789 int iFlagShift = getBufferFlagShift(dest.na_ci);
3790 int jFlagShift = getBufferFlagShift(dest.na_cj);
3793 for (int s = 0; s < numLists && cjGlobal < cjEnd; s++)
3795 const NbnxnPairlistCpu *src = &srcSet[s];
3797 if (cjGlobal + src->ncjInUse > cjStart)
3799 for (gmx::index i = 0; i < gmx::ssize(src->ci) && cjGlobal < cjEnd; i++)
3801 const nbnxn_ci_t *srcCi = &src->ci[i];
3802 int ncj = srcCi->cj_ind_end - srcCi->cj_ind_start;
3803 if (cjGlobal >= cjStart)
3805 /* If the source list is not our own, we need to set
3806 * extra flags (the template bool parameter).
3810 copySelectedListRange
3813 flag, iFlagShift, jFlagShift, t);
3817 copySelectedListRange
3820 &dest, flag, iFlagShift, jFlagShift, t);
3828 cjGlobal += src->ncjInUse;
3832 dest.ncjInUse = dest.cj.size();
3836 int ncjTotalNew = 0;
3837 for (auto &dest : destSet)
3839 ncjTotalNew += dest.ncjInUse;
3841 GMX_RELEASE_ASSERT(ncjTotalNew == ncjTotal, "The total size of the lists before and after rebalancing should match");
3845 /* Returns if the pairlists are so imbalanced that it is worth rebalancing. */
3846 static bool checkRebalanceSimpleLists(gmx::ArrayRef<const NbnxnPairlistCpu> lists)
3848 int numLists = lists.ssize();
3851 for (int s = 0; s < numLists; s++)
3853 ncjMax = std::max(ncjMax, lists[s].ncjInUse);
3854 ncjTotal += lists[s].ncjInUse;
3858 fprintf(debug, "Pair-list ncjMax %d ncjTotal %d\n", ncjMax, ncjTotal);
3860 /* The rebalancing adds 3% extra time to the search. Heuristically we
3861 * determined that under common conditions the non-bonded kernel balance
3862 * improvement will outweigh this when the imbalance is more than 3%.
3863 * But this will, obviously, depend on search vs kernel time and nstlist.
3865 const real rebalanceTolerance = 1.03;
3867 return numLists*ncjMax > ncjTotal*rebalanceTolerance;
3870 /* Perform a count (linear) sort to sort the smaller lists to the end.
3871 * This avoids load imbalance on the GPU, as large lists will be
3872 * scheduled and executed first and the smaller lists later.
3873 * Load balancing between multi-processors only happens at the end
3874 * and there smaller lists lead to more effective load balancing.
3875 * The sorting is done on the cj4 count, not on the actual pair counts.
3876 * Not only does this make the sort faster, but it also results in
3877 * better load balancing than using a list sorted on exact load.
3878 * This function swaps the pointer in the pair list to avoid a copy operation.
3880 static void sort_sci(NbnxnPairlistGpu *nbl)
3882 if (nbl->cj4.size() <= nbl->sci.size())
3884 /* nsci = 0 or all sci have size 1, sorting won't change the order */
3888 NbnxnPairlistGpuWork &work = *nbl->work;
3890 /* We will distinguish differences up to double the average */
3891 const int m = (2*nbl->cj4.size())/nbl->sci.size();
3893 /* Resize work.sci_sort so we can sort into it */
3894 work.sci_sort.resize(nbl->sci.size());
3896 std::vector<int> &sort = work.sortBuffer;
3897 /* Set up m + 1 entries in sort, initialized at 0 */
3899 sort.resize(m + 1, 0);
3900 /* Count the entries of each size */
3901 for (const nbnxn_sci_t &sci : nbl->sci)
3903 int i = std::min(m, sci.numJClusterGroups());
3906 /* Calculate the offset for each count */
3909 for (int i = m - 1; i >= 0; i--)
3912 sort[i] = sort[i + 1] + s0;
3916 /* Sort entries directly into place */
3917 gmx::ArrayRef<nbnxn_sci_t> sci_sort = work.sci_sort;
3918 for (const nbnxn_sci_t &sci : nbl->sci)
3920 int i = std::min(m, sci.numJClusterGroups());
3921 sci_sort[sort[i]++] = sci;
3924 /* Swap the sci pointers so we use the new, sorted list */
3925 std::swap(nbl->sci, work.sci_sort);
3928 //! Prepares CPU lists produced by the search for dynamic pruning
3929 static void prepareListsForDynamicPruning(gmx::ArrayRef<NbnxnPairlistCpu> lists);
3932 PairlistSet::constructPairlists(PairSearch *pairSearch,
3933 nbnxn_atomdata_t *nbat,
3934 const t_blocka *excl,
3935 const Nbnxm::KernelType kernelType,
3936 const int minimumIlistCountForGpuBalancing,
3939 const real rlist = params_.rlistOuter;
3941 int nsubpair_target;
3942 float nsubpair_tot_est;
3945 int np_tot, np_noq, np_hlj, nap;
3947 const int numLists = (isCpuType_ ? cpuLists_.size() : gpuLists_.size());
3951 fprintf(debug, "ns making %d nblists\n", numLists);
3954 nbat->bUseBufferFlags = (nbat->out.size() > 1);
3955 /* We should re-init the flags before making the first list */
3956 if (nbat->bUseBufferFlags && locality_ == InteractionLocality::Local)
3958 init_buffer_flags(&nbat->buffer_flags, nbat->numAtoms());
3962 if (locality_ == InteractionLocality::Local)
3964 /* Only zone (grid) 0 vs 0 */
3969 nzi = pairSearch->domainSetup().zones->nizone;
3972 if (!isCpuType_ && minimumIlistCountForGpuBalancing > 0)
3974 get_nsubpair_target(*pairSearch, locality_, rlist, minimumIlistCountForGpuBalancing,
3975 &nsubpair_target, &nsubpair_tot_est);
3979 nsubpair_target = 0;
3980 nsubpair_tot_est = 0;
3983 /* Clear all pair-lists */
3984 for (int th = 0; th < numLists; th++)
3988 clear_pairlist(&cpuLists_[th]);
3992 clear_pairlist(&gpuLists_[th]);
3995 if (params_.haveFep)
3997 clear_pairlist_fep(fepLists_[th]);
4001 const gmx_domdec_zones_t *ddZones = pairSearch->domainSetup().zones;
4003 for (int zi = 0; zi < nzi; zi++)
4005 const Grid &iGrid = pairSearch->gridSet().grids()[zi];
4009 if (locality_ == InteractionLocality::Local)
4016 zj0 = ddZones->izone[zi].j0;
4017 zj1 = ddZones->izone[zi].j1;
4023 for (int zj = zj0; zj < zj1; zj++)
4025 const Grid &jGrid = pairSearch->gridSet().grids()[zj];
4029 fprintf(debug, "ns search grid %d vs %d\n", zi, zj);
4032 pairSearch->cycleCounting_.start(PairSearch::enbsCCsearch);
4034 ci_block = get_ci_block_size(iGrid, pairSearch->domainSetup().haveDomDec, numLists);
4036 /* With GPU: generate progressively smaller lists for
4037 * load balancing for local only or non-local with 2 zones.
4039 progBal = (locality_ == InteractionLocality::Local || ddZones->n <= 2);
4041 #pragma omp parallel for num_threads(numLists) schedule(static)
4042 for (int th = 0; th < numLists; th++)
4046 /* Re-init the thread-local work flag data before making
4047 * the first list (not an elegant conditional).
4049 if (nbat->bUseBufferFlags && ((zi == 0 && zj == 0)))
4051 init_buffer_flags(&pairSearch->work()[th].buffer_flags, nbat->numAtoms());
4054 if (combineLists_ && th > 0)
4056 GMX_ASSERT(!isCpuType_, "Can only combine GPU lists");
4058 clear_pairlist(&gpuLists_[th]);
4061 PairsearchWork *searchWork = &pairSearch->work()[th];
4063 searchWork->cycleCounter.start();
4065 t_nblist *fepListPtr = (fepLists_.empty() ? nullptr : fepLists_[th]);
4067 /* Divide the i cells equally over the pairlists */
4070 nbnxn_make_pairlist_part(*pairSearch, iGrid, jGrid,
4071 searchWork, nbat, *excl,
4075 nbat->bUseBufferFlags,
4077 progBal, nsubpair_tot_est,
4084 nbnxn_make_pairlist_part(*pairSearch, iGrid, jGrid,
4085 searchWork, nbat, *excl,
4089 nbat->bUseBufferFlags,
4091 progBal, nsubpair_tot_est,
4097 searchWork->cycleCounter.stop();
4099 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
4101 pairSearch->cycleCounting_.stop(PairSearch::enbsCCsearch);
4106 for (int th = 0; th < numLists; th++)
4108 inc_nrnb(nrnb, eNR_NBNXN_DIST2, pairSearch->work()[th].ndistc);
4112 const NbnxnPairlistCpu &nbl = cpuLists_[th];
4113 np_tot += nbl.cj.size();
4114 np_noq += nbl.work->ncj_noq;
4115 np_hlj += nbl.work->ncj_hlj;
4119 const NbnxnPairlistGpu &nbl = gpuLists_[th];
4120 /* This count ignores potential subsequent pair pruning */
4121 np_tot += nbl.nci_tot;
4126 nap = cpuLists_[0].na_ci*cpuLists_[0].na_cj;
4130 nap = gmx::square(gpuLists_[0].na_ci);
4132 natpair_ljq_ = (np_tot - np_noq)*nap - np_hlj*nap/2;
4133 natpair_lj_ = np_noq*nap;
4134 natpair_q_ = np_hlj*nap/2;
4136 if (combineLists_ && numLists > 1)
4138 GMX_ASSERT(!isCpuType_, "Can only combine GPU lists");
4140 pairSearch->cycleCounting_.start(PairSearch::enbsCCcombine);
4142 combine_nblists(gmx::constArrayRefFromArray(&gpuLists_[1], numLists - 1),
4145 pairSearch->cycleCounting_.stop(PairSearch::enbsCCcombine);
4152 if (numLists > 1 && checkRebalanceSimpleLists(cpuLists_))
4154 rebalanceSimpleLists(cpuLists_, cpuListsWork_, pairSearch->work());
4156 /* Swap the sets of pair lists */
4157 cpuLists_.swap(cpuListsWork_);
4162 /* Sort the entries on size, large ones first */
4163 if (combineLists_ || gpuLists_.size() == 1)
4165 sort_sci(&gpuLists_[0]);
4169 #pragma omp parallel for num_threads(numLists) schedule(static)
4170 for (int th = 0; th < numLists; th++)
4174 sort_sci(&gpuLists_[th]);
4176 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
4181 if (nbat->bUseBufferFlags)
4183 reduce_buffer_flags(*pairSearch, numLists, &nbat->buffer_flags);
4186 if (pairSearch->gridSet().haveFep())
4188 /* Balance the free-energy lists over all the threads */
4189 balance_fep_lists(fepLists_, pairSearch->work());
4194 /* This is a fresh list, so not pruned, stored using ci.
4195 * ciOuter is invalid at this point.
4197 GMX_ASSERT(cpuLists_[0].ciOuter.empty(), "ciOuter is invalid so it should be empty");
4200 /* If we have more than one list, they either got rebalancing (CPU)
4201 * or combined (GPU), so we should dump the final result to debug.
4205 if (isCpuType_ && cpuLists_.size() > 1)
4207 for (auto &cpuList : cpuLists_)
4209 print_nblist_statistics(debug, cpuList, *pairSearch, rlist);
4212 else if (!isCpuType_ && gpuLists_.size() > 1)
4214 print_nblist_statistics(debug, gpuLists_[0], *pairSearch, rlist);
4224 for (auto &cpuList : cpuLists_)
4226 print_nblist_ci_cj(debug, cpuList);
4231 print_nblist_sci_cj(debug, gpuLists_[0]);
4235 if (nbat->bUseBufferFlags)
4237 print_reduction_cost(&nbat->buffer_flags, numLists);
4241 if (params_.useDynamicPruning && isCpuType_)
4243 prepareListsForDynamicPruning(cpuLists_);
4248 PairlistSets::construct(const InteractionLocality iLocality,
4249 PairSearch *pairSearch,
4250 nbnxn_atomdata_t *nbat,
4251 const t_blocka *excl,
4252 const Nbnxm::KernelType kernelType,
4256 pairlistSet(iLocality).constructPairlists(pairSearch, nbat, excl, kernelType, minimumIlistCountForGpuBalancing_, nrnb);
4258 if (iLocality == Nbnxm::InteractionLocality::Local)
4260 outerListCreationStep_ = step;
4264 GMX_RELEASE_ASSERT(outerListCreationStep_ == step,
4265 "Outer list should be created at the same step as the inner list");
4268 /* Special performance logging stuff (env.var. GMX_NBNXN_CYCLE) */
4269 if (iLocality == InteractionLocality::Local)
4271 pairSearch->cycleCounting_.searchCount_++;
4273 if (pairSearch->cycleCounting_.recordCycles_ &&
4274 (!pairSearch->domainSetup().haveDomDec || iLocality == InteractionLocality::NonLocal) &&
4275 pairSearch->cycleCounting_.searchCount_ % 100 == 0)
4277 pairSearch->cycleCounting_.printCycles(stderr, pairSearch->work());
4282 nonbonded_verlet_t::constructPairlist(const Nbnxm::InteractionLocality iLocality,
4283 const t_blocka *excl,
4287 pairlistSets_->construct(iLocality, pairSearch_.get(), nbat.get(), excl,
4288 kernelSetup_.kernelType,
4293 /* Launch the transfer of the pairlist to the GPU.
4295 * NOTE: The launch overhead is currently not timed separately
4297 Nbnxm::gpu_init_pairlist(gpu_nbv,
4298 pairlistSets().pairlistSet(iLocality).gpuList(),
4303 static void prepareListsForDynamicPruning(gmx::ArrayRef<NbnxnPairlistCpu> lists)
4305 /* TODO: Restructure the lists so we have actual outer and inner
4306 * list objects so we can set a single pointer instead of
4307 * swapping several pointers.
4310 for (auto &list : lists)
4312 /* The search produced a list in ci/cj.
4313 * Swap the list pointers so we get the outer list is ciOuter,cjOuter
4314 * and we can prune that to get an inner list in ci/cj.
4316 GMX_RELEASE_ASSERT(list.ciOuter.empty() && list.cjOuter.empty(),
4317 "The outer lists should be empty before preparation");
4319 std::swap(list.ci, list.ciOuter);
4320 std::swap(list.cj, list.cjOuter);