2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2016,2017,2018,2019,2020 by the GROMACS development team.
5 * Copyright (c) 2021, by the GROMACS development team, led by
6 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7 * and including many others, as listed in the AUTHORS file in the
8 * top-level source directory and at http://www.gromacs.org.
10 * GROMACS is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public License
12 * as published by the Free Software Foundation; either version 2.1
13 * of the License, or (at your option) any later version.
15 * GROMACS is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with GROMACS; if not, see
22 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 * If you want to redistribute modifications to GROMACS, please
26 * consider that scientific software is very special. Version
27 * control is crucial - bugs must be traceable. We will be happy to
28 * consider code for inclusion in the official distribution, but
29 * derived work must not be called official GROMACS. Details are found
30 * in the README & COPYING files - if they are missing, get the
31 * official version at http://www.gromacs.org.
33 * To help us fund GROMACS development, we humbly ask that you cite
34 * the research papers on the package. Check out http://www.gromacs.org.
38 * Implements common routines for PME tests.
40 * \author Aleksei Iupinov <a.yupinov@gmail.com>
41 * \ingroup module_ewald
45 #include "pmetestcommon.h"
51 #include "gromacs/domdec/domdec.h"
52 #include "gromacs/ewald/pme_gather.h"
53 #include "gromacs/ewald/pme_gpu_calculate_splines.h"
54 #include "gromacs/ewald/pme_gpu_constants.h"
55 #include "gromacs/ewald/pme_gpu_internal.h"
56 #include "gromacs/ewald/pme_gpu_staging.h"
57 #include "gromacs/ewald/pme_grid.h"
58 #include "gromacs/ewald/pme_internal.h"
59 #include "gromacs/ewald/pme_redistribute.h"
60 #include "gromacs/ewald/pme_solve.h"
61 #include "gromacs/ewald/pme_spread.h"
62 #include "gromacs/fft/parallel_3dfft.h"
63 #include "gromacs/gpu_utils/gpu_utils.h"
64 #include "gromacs/hardware/device_management.h"
65 #include "gromacs/math/invertmatrix.h"
66 #include "gromacs/mdtypes/commrec.h"
67 #include "gromacs/pbcutil/pbc.h"
68 #include "gromacs/topology/topology.h"
69 #include "gromacs/utility/exceptions.h"
70 #include "gromacs/utility/gmxassert.h"
71 #include "gromacs/utility/logger.h"
72 #include "gromacs/utility/stringutil.h"
73 #include "gromacs/ewald/pme_coordinate_receiver_gpu.h"
75 #include "testutils/test_hardware_environment.h"
76 #include "testutils/testasserts.h"
85 //! A couple of valid inputs for boxes.
86 const std::map<std::string, Matrix3x3> c_inputBoxes = {
87 { "rect", { { 8.0F, 0.0F, 0.0F, 0.0F, 3.4F, 0.0F, 0.0F, 0.0F, 2.0F } } },
88 { "tric", { { 7.0F, 0.0F, 0.0F, 0.0F, 4.1F, 0.0F, 3.5F, 2.0F, 12.2F } } },
91 //! Valid PME orders for testing
92 std::vector<int> c_inputPmeOrders{ 3, 4, 5 };
94 bool pmeSupportsInputForMode(const gmx_hw_info_t& hwinfo, const t_inputrec* inputRec, CodePath mode)
99 case CodePath::CPU: implemented = true; break;
102 implemented = (pme_gpu_supports_build(nullptr) && pme_gpu_supports_hardware(hwinfo, nullptr)
103 && pme_gpu_supports_input(*inputRec, nullptr));
106 default: GMX_THROW(InternalError("Test not implemented for this mode"));
111 uint64_t getSplineModuliDoublePrecisionUlps(int splineOrder)
113 /* Arbitrary ulp tolerance for sine/cosine implementation. It's
114 * hard to know what to pick without testing lots of
115 * implementations. */
116 const uint64_t sineUlps = 10;
117 return 4 * (splineOrder - 2) + 2 * sineUlps * splineOrder;
120 //! PME initialization
121 PmeSafePointer pmeInitWrapper(const t_inputrec* inputRec,
123 const DeviceContext* deviceContext,
124 const DeviceStream* deviceStream,
125 const PmeGpuProgram* pmeGpuProgram,
126 const Matrix3x3& box,
127 const real ewaldCoeff_q,
128 const real ewaldCoeff_lj)
130 const MDLogger dummyLogger;
131 const auto runMode = (mode == CodePath::CPU) ? PmeRunMode::CPU : PmeRunMode::Mixed;
132 t_commrec dummyCommrec = { 0 };
133 NumPmeDomains numPmeDomains = { 1, 1 };
134 gmx_pme_t* pmeDataRaw = gmx_pme_init(&dummyCommrec,
149 PmeSafePointer pme(pmeDataRaw); // taking ownership
151 // TODO get rid of this with proper matrix type
153 for (int i = 0; i < DIM; i++)
155 for (int j = 0; j < DIM; j++)
157 boxTemp[i][j] = box[i * DIM + j];
160 const char* boxError = check_box(PbcType::Unset, boxTemp);
161 GMX_RELEASE_ASSERT(boxError == nullptr, boxError);
165 case CodePath::CPU: invertBoxMatrix(boxTemp, pme->recipbox); break;
168 pme_gpu_set_testing(pme->gpu, true);
169 pme_gpu_update_input_box(pme->gpu, boxTemp);
172 default: GMX_THROW(InternalError("Test not implemented for this mode"));
178 PmeSafePointer pmeInitEmpty(const t_inputrec* inputRec)
180 const Matrix3x3 defaultBox = { { 1.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 1.0F } };
181 return pmeInitWrapper(inputRec, CodePath::CPU, nullptr, nullptr, nullptr, defaultBox, 0.0F, 0.0F);
184 //! Make a GPU state-propagator manager
185 std::unique_ptr<StatePropagatorDataGpu> makeStatePropagatorDataGpu(const gmx_pme_t& pme,
186 const DeviceContext* deviceContext,
187 const DeviceStream* deviceStream)
189 // TODO: Pin the host buffer and use async memory copies
190 // TODO: Special constructor for PME-only rank / PME-tests is used here. There should be a mechanism to
191 // restrict one from using other constructor here.
192 return std::make_unique<StatePropagatorDataGpu>(
193 deviceStream, *deviceContext, GpuApiCallBehavior::Sync, pme_gpu_get_block_size(&pme), nullptr);
196 //! PME initialization with atom data
197 void pmeInitAtoms(gmx_pme_t* pme,
198 StatePropagatorDataGpu* stateGpu,
200 const CoordinatesVector& coordinates,
201 const ChargesVector& charges)
203 const index atomCount = coordinates.size();
204 GMX_RELEASE_ASSERT(atomCount == gmx::ssize(charges), "Mismatch in atom data");
205 PmeAtomComm* atc = nullptr;
210 atc = &(pme->atc[0]);
211 atc->x = coordinates;
212 atc->coefficient = charges;
213 gmx_pme_reinit_atoms(pme, atomCount, charges, {});
214 /* With decomposition there would be more boilerplate atc code here, e.g. do_redist_pos_coeffs */
218 // TODO: Avoid use of atc in the GPU code path
219 atc = &(pme->atc[0]);
220 // We need to set atc->n for passing the size in the tests
221 atc->setNumAtoms(atomCount);
222 gmx_pme_reinit_atoms(pme, atomCount, charges, {});
224 stateGpu->reinit(atomCount, atomCount);
225 stateGpu->copyCoordinatesToGpu(arrayRefFromArray(coordinates.data(), coordinates.size()),
226 gmx::AtomLocality::Local);
227 pme_gpu_set_kernelparam_coordinates(pme->gpu, stateGpu->getCoordinates());
231 default: GMX_THROW(InternalError("Test not implemented for this mode"));
235 //! Getting local PME real grid pointer for test I/O
236 static real* pmeGetRealGridInternal(const gmx_pme_t* pme)
238 const size_t gridIndex = 0;
239 return pme->fftgrid[gridIndex];
242 //! Getting local PME real grid dimensions
243 static void pmeGetRealGridSizesInternal(const gmx_pme_t* pme,
245 IVec& gridSize, //NOLINT(google-runtime-references)
246 IVec& paddedGridSize) //NOLINT(google-runtime-references)
248 const size_t gridIndex = 0;
249 IVec gridOffsetUnused;
253 gmx_parallel_3dfft_real_limits(
254 pme->pfft_setup[gridIndex], gridSize, gridOffsetUnused, paddedGridSize);
258 pme_gpu_get_real_grid_sizes(pme->gpu, &gridSize, &paddedGridSize);
261 default: GMX_THROW(InternalError("Test not implemented for this mode"));
265 //! Getting local PME complex grid pointer for test I/O
266 static t_complex* pmeGetComplexGridInternal(const gmx_pme_t* pme)
268 const size_t gridIndex = 0;
269 return pme->cfftgrid[gridIndex];
272 //! Getting local PME complex grid dimensions
273 static void pmeGetComplexGridSizesInternal(const gmx_pme_t* pme,
274 IVec& gridSize, //NOLINT(google-runtime-references)
275 IVec& paddedGridSize) //NOLINT(google-runtime-references)
277 const size_t gridIndex = 0;
278 IVec gridOffsetUnused, complexOrderUnused;
279 gmx_parallel_3dfft_complex_limits(
280 pme->pfft_setup[gridIndex], complexOrderUnused, gridSize, gridOffsetUnused, paddedGridSize); // TODO: what about YZX ordering?
283 //! Getting the PME grid memory buffer and its sizes - template definition
284 template<typename ValueType>
285 static void pmeGetGridAndSizesInternal(const gmx_pme_t* /*unused*/,
287 ValueType*& /*unused*/, //NOLINT(google-runtime-references)
288 IVec& /*unused*/, //NOLINT(google-runtime-references)
289 IVec& /*unused*/) //NOLINT(google-runtime-references)
291 GMX_THROW(InternalError("Deleted function call"));
292 // explicitly deleting general template does not compile in clang, see https://llvm.org/bugs/show_bug.cgi?id=17537
295 //! Getting the PME real grid memory buffer and its sizes
297 void pmeGetGridAndSizesInternal<real>(const gmx_pme_t* pme, CodePath mode, real*& grid, IVec& gridSize, IVec& paddedGridSize)
299 grid = pmeGetRealGridInternal(pme);
300 pmeGetRealGridSizesInternal(pme, mode, gridSize, paddedGridSize);
303 //! Getting the PME complex grid memory buffer and its sizes
305 void pmeGetGridAndSizesInternal<t_complex>(const gmx_pme_t* pme,
309 IVec& paddedGridSize)
311 grid = pmeGetComplexGridInternal(pme);
312 pmeGetComplexGridSizesInternal(pme, gridSize, paddedGridSize);
315 //! PME spline calculation and charge spreading
316 void pmePerformSplineAndSpread(gmx_pme_t* pme,
317 CodePath mode, // TODO const qualifiers elsewhere
321 GMX_RELEASE_ASSERT(pme != nullptr, "PME data is not initialized");
322 PmeAtomComm* atc = &(pme->atc[0]);
323 const size_t gridIndex = 0;
324 const bool computeSplinesForZeroCharges = true;
325 real** fftgrid = spreadCharges ? pme->fftgrid : nullptr;
326 real* pmegrid = pme->pmegrid[gridIndex].grid.grid;
333 &pme->pmegrid[gridIndex],
336 fftgrid != nullptr ? fftgrid[gridIndex] : nullptr,
337 computeSplinesForZeroCharges,
339 if (spreadCharges && !pme->bUseThreads)
341 wrap_periodic_pmegrid(pme, pmegrid);
342 copy_pmegrid_to_fftgrid(
343 pme, pmegrid, fftgrid != nullptr ? fftgrid[gridIndex] : nullptr, gridIndex);
347 /* The compiler will complain about passing fftgrid (converting double ** to float **) if using
348 * double precision. GPUs are not used with double precision anyhow. */
352 const real lambdaQ = 1.0;
353 // no synchronization needed as x is transferred in the PME stream
354 GpuEventSynchronizer* xReadyOnDevice = nullptr;
356 bool useGpuDirectComm = false;
357 gmx::PmeCoordinateReceiverGpu* pmeCoordinateReceiverGpu = nullptr;
359 pme_gpu_spread(pme->gpu,
366 pmeCoordinateReceiverGpu);
371 default: GMX_THROW(InternalError("Test not implemented for this mode"));
375 //! Getting the internal spline data buffer pointer
376 static real* pmeGetSplineDataInternal(const gmx_pme_t* pme, PmeSplineDataType type, int dimIndex)
378 GMX_ASSERT((0 <= dimIndex) && (dimIndex < DIM), "Invalid dimension index");
379 const PmeAtomComm* atc = &(pme->atc[0]);
380 const size_t threadIndex = 0;
381 real* splineBuffer = nullptr;
384 case PmeSplineDataType::Values:
385 splineBuffer = atc->spline[threadIndex].theta.coefficients[dimIndex];
388 case PmeSplineDataType::Derivatives:
389 splineBuffer = atc->spline[threadIndex].dtheta.coefficients[dimIndex];
392 default: GMX_THROW(InternalError("Unknown spline data type"));
398 void pmePerformSolve(const gmx_pme_t* pme,
400 PmeSolveAlgorithm method,
402 GridOrdering gridOrdering,
403 bool computeEnergyAndVirial)
405 t_complex* h_grid = pmeGetComplexGridInternal(pme);
406 const bool useLorentzBerthelot = false;
407 const size_t threadIndex = 0;
408 const size_t gridIndex = 0;
412 if (gridOrdering != GridOrdering::YZX)
414 GMX_THROW(InternalError("Test not implemented for this mode"));
418 case PmeSolveAlgorithm::Coulomb:
419 solve_pme_yzx(pme, h_grid, cellVolume, computeEnergyAndVirial, pme->nthread, threadIndex);
422 case PmeSolveAlgorithm::LennardJones:
423 solve_pme_lj_yzx(pme,
427 computeEnergyAndVirial,
432 default: GMX_THROW(InternalError("Test not implemented for this mode"));
439 case PmeSolveAlgorithm::Coulomb:
440 pme_gpu_solve(pme->gpu, gridIndex, h_grid, gridOrdering, computeEnergyAndVirial);
443 default: GMX_THROW(InternalError("Test not implemented for this mode"));
447 default: GMX_THROW(InternalError("Test not implemented for this mode"));
451 //! PME force gathering
452 void pmePerformGather(gmx_pme_t* pme, CodePath mode, ForcesVector& forces)
454 PmeAtomComm* atc = &(pme->atc[0]);
455 const index atomCount = atc->numAtoms();
456 GMX_RELEASE_ASSERT(forces.ssize() == atomCount, "Invalid force buffer size");
457 const real scale = 1.0;
458 const size_t threadIndex = 0;
459 const size_t gridIndex = 0;
460 real* pmegrid = pme->pmegrid[gridIndex].grid.grid;
461 real** fftgrid = pme->fftgrid;
467 if (atc->nthread == 1)
469 // something which is normally done in serial spline computation (make_thread_local_ind())
470 atc->spline[threadIndex].n = atomCount;
472 copy_fftgrid_to_pmegrid(pme, fftgrid[gridIndex], pmegrid, gridIndex, pme->nthread, threadIndex);
473 unwrap_periodic_pmegrid(pme, pmegrid);
474 gather_f_bsplines(pme, pmegrid, true, atc, &atc->spline[threadIndex], scale);
477 /* The compiler will complain about passing fftgrid (converting double ** to float **) if using
478 * double precision. GPUs are not used with double precision anyhow. */
482 // Variable initialization needs a non-switch scope
483 const bool computeEnergyAndVirial = false;
484 const real lambdaQ = 1.0;
485 PmeOutput output = pme_gpu_getOutput(*pme, computeEnergyAndVirial, lambdaQ);
486 GMX_ASSERT(forces.size() == output.forces_.size(),
487 "Size of force buffers did not match");
488 pme_gpu_gather(pme->gpu, fftgrid, lambdaQ);
489 std::copy(std::begin(output.forces_), std::end(output.forces_), std::begin(forces));
494 default: GMX_THROW(InternalError("Test not implemented for this mode"));
498 //! PME test finalization before fetching the outputs
499 void pmeFinalizeTest(const gmx_pme_t* pme, CodePath mode)
503 case CodePath::CPU: break;
505 case CodePath::GPU: pme_gpu_synchronize(pme->gpu); break;
507 default: GMX_THROW(InternalError("Test not implemented for this mode"));
511 //! A binary enum for spline data layout transformation
512 enum class PmeLayoutTransform
518 /*! \brief Gets a unique index to an element in a spline parameter buffer.
520 * These theta/dtheta buffers are laid out for GPU spread/gather
521 * kernels. The index is wrt the execution block, in range(0,
522 * atomsPerBlock * order * DIM).
524 * This is a wrapper, only used in unit tests.
525 * \param[in] order PME order
526 * \param[in] splineIndex Spline contribution index (from 0 to \p order - 1)
527 * \param[in] dimIndex Dimension index (from 0 to 2)
528 * \param[in] atomIndex Atom index wrt the block.
529 * \param[in] atomsPerWarp Number of atoms processed by a warp.
531 * \returns Index into theta or dtheta array using GPU layout.
533 static int getSplineParamFullIndex(int order, int splineIndex, int dimIndex, int atomIndex, int atomsPerWarp)
535 if (order != c_pmeGpuOrder)
539 constexpr int fixedOrder = c_pmeGpuOrder;
540 GMX_UNUSED_VALUE(fixedOrder);
542 const int atomWarpIndex = atomIndex % atomsPerWarp;
543 const int warpIndex = atomIndex / atomsPerWarp;
544 int indexBase, result;
545 switch (atomsPerWarp)
548 indexBase = getSplineParamIndexBase<fixedOrder, 1>(warpIndex, atomWarpIndex);
549 result = getSplineParamIndex<fixedOrder, 1>(indexBase, dimIndex, splineIndex);
553 indexBase = getSplineParamIndexBase<fixedOrder, 2>(warpIndex, atomWarpIndex);
554 result = getSplineParamIndex<fixedOrder, 2>(indexBase, dimIndex, splineIndex);
558 indexBase = getSplineParamIndexBase<fixedOrder, 4>(warpIndex, atomWarpIndex);
559 result = getSplineParamIndex<fixedOrder, 4>(indexBase, dimIndex, splineIndex);
563 indexBase = getSplineParamIndexBase<fixedOrder, 8>(warpIndex, atomWarpIndex);
564 result = getSplineParamIndex<fixedOrder, 8>(indexBase, dimIndex, splineIndex);
568 GMX_THROW(NotImplementedError(
569 formatString("Test function call not unrolled for atomsPerWarp = %d in "
570 "getSplineParamFullIndex",
576 /*!\brief Return the number of atoms per warp */
577 static int pme_gpu_get_atoms_per_warp(const PmeGpu* pmeGpu)
579 const int order = pmeGpu->common->pme_order;
580 const int threadsPerAtom =
581 (pmeGpu->settings.threadsPerAtom == ThreadsPerAtom::Order ? order : order * order);
582 return pmeGpu->programHandle_->warpSize() / threadsPerAtom;
585 /*! \brief Rearranges the atom spline data between the GPU and host layouts.
586 * Only used for test purposes so far, likely to be horribly slow.
588 * \param[in] pmeGpu The PME GPU structure.
589 * \param[out] atc The PME CPU atom data structure (with a single-threaded layout).
590 * \param[in] type The spline data type (values or derivatives).
591 * \param[in] dimIndex Dimension index.
592 * \param[in] transform Layout transform type
594 static void pme_gpu_transform_spline_atom_data(const PmeGpu* pmeGpu,
595 const PmeAtomComm* atc,
596 PmeSplineDataType type,
598 PmeLayoutTransform transform)
600 // The GPU atom spline data is laid out in a different way currently than the CPU one.
601 // This function converts the data from GPU to CPU layout (in the host memory).
602 // It is only intended for testing purposes so far.
603 // Ideally we should use similar layouts on CPU and GPU if we care about mixed modes and their
604 // performance (e.g. spreading on GPU, gathering on CPU).
605 GMX_RELEASE_ASSERT(atc->nthread == 1, "Only the serial PME data layout is supported");
606 const uintmax_t threadIndex = 0;
607 const auto atomCount = atc->numAtoms();
608 const auto atomsPerWarp = pme_gpu_get_atoms_per_warp(pmeGpu);
609 const auto pmeOrder = pmeGpu->common->pme_order;
610 GMX_ASSERT(pmeOrder == c_pmeGpuOrder, "Only PME order 4 is implemented");
612 real* cpuSplineBuffer;
613 float* h_splineBuffer;
616 case PmeSplineDataType::Values:
617 cpuSplineBuffer = atc->spline[threadIndex].theta.coefficients[dimIndex];
618 h_splineBuffer = pmeGpu->staging.h_theta;
621 case PmeSplineDataType::Derivatives:
622 cpuSplineBuffer = atc->spline[threadIndex].dtheta.coefficients[dimIndex];
623 h_splineBuffer = pmeGpu->staging.h_dtheta;
626 default: GMX_THROW(InternalError("Unknown spline data type"));
629 for (auto atomIndex = 0; atomIndex < atomCount; atomIndex++)
631 for (auto orderIndex = 0; orderIndex < pmeOrder; orderIndex++)
633 const auto gpuValueIndex =
634 getSplineParamFullIndex(pmeOrder, orderIndex, dimIndex, atomIndex, atomsPerWarp);
635 const auto cpuValueIndex = atomIndex * pmeOrder + orderIndex;
636 GMX_ASSERT(cpuValueIndex < atomCount * pmeOrder,
637 "Atom spline data index out of bounds (while transforming GPU data layout "
641 case PmeLayoutTransform::GpuToHost:
642 cpuSplineBuffer[cpuValueIndex] = h_splineBuffer[gpuValueIndex];
645 case PmeLayoutTransform::HostToGpu:
646 h_splineBuffer[gpuValueIndex] = cpuSplineBuffer[cpuValueIndex];
649 default: GMX_THROW(InternalError("Unknown layout transform"));
655 //! Setting atom spline values/derivatives to be used in spread/gather
656 void pmeSetSplineData(const gmx_pme_t* pme,
658 const SplineParamsDimVector& splineValues,
659 PmeSplineDataType type,
662 const PmeAtomComm* atc = &(pme->atc[0]);
663 const index atomCount = atc->numAtoms();
664 const index pmeOrder = pme->pme_order;
665 const index dimSize = pmeOrder * atomCount;
666 GMX_RELEASE_ASSERT(dimSize == splineValues.ssize(), "Mismatch in spline data");
667 real* splineBuffer = pmeGetSplineDataInternal(pme, type, dimIndex);
672 std::copy(splineValues.begin(), splineValues.end(), splineBuffer);
676 std::copy(splineValues.begin(), splineValues.end(), splineBuffer);
677 pme_gpu_transform_spline_atom_data(pme->gpu, atc, type, dimIndex, PmeLayoutTransform::HostToGpu);
680 default: GMX_THROW(InternalError("Test not implemented for this mode"));
684 //! Setting gridline indices to be used in spread/gather
685 void pmeSetGridLineIndices(gmx_pme_t* pme, CodePath mode, const GridLineIndicesVector& gridLineIndices)
687 PmeAtomComm* atc = &(pme->atc[0]);
688 const index atomCount = atc->numAtoms();
689 GMX_RELEASE_ASSERT(atomCount == ssize(gridLineIndices), "Mismatch in gridline indices size");
691 IVec paddedGridSizeUnused, gridSize(0, 0, 0);
692 pmeGetRealGridSizesInternal(pme, mode, gridSize, paddedGridSizeUnused);
694 for (const auto& index : gridLineIndices)
696 for (int i = 0; i < DIM; i++)
698 GMX_RELEASE_ASSERT((0 <= index[i]) && (index[i] < gridSize[i]),
699 "Invalid gridline index");
706 memcpy(pme_gpu_staging(pme->gpu).h_gridlineIndices,
707 gridLineIndices.data(),
708 atomCount * sizeof(gridLineIndices[0]));
712 atc->idx.resize(gridLineIndices.size());
713 std::copy(gridLineIndices.begin(), gridLineIndices.end(), atc->idx.begin());
715 default: GMX_THROW(InternalError("Test not implemented for this mode"));
719 //! Getting plain index into the complex 3d grid
720 inline size_t pmeGetGridPlainIndexInternal(const IVec& index, const IVec& paddedGridSize, GridOrdering gridOrdering)
723 switch (gridOrdering)
725 case GridOrdering::YZX:
726 result = (index[YY] * paddedGridSize[ZZ] + index[ZZ]) * paddedGridSize[XX] + index[XX];
729 case GridOrdering::XYZ:
730 result = (index[XX] * paddedGridSize[YY] + index[YY]) * paddedGridSize[ZZ] + index[ZZ];
733 default: GMX_THROW(InternalError("Test not implemented for this mode"));
738 //! Setting real or complex grid
739 template<typename ValueType>
740 static void pmeSetGridInternal(const gmx_pme_t* pme,
742 GridOrdering gridOrdering,
743 const SparseGridValuesInput<ValueType>& gridValues)
745 IVec gridSize(0, 0, 0), paddedGridSize(0, 0, 0);
747 pmeGetGridAndSizesInternal<ValueType>(pme, mode, grid, gridSize, paddedGridSize);
751 case CodePath::GPU: // intentional absence of break, the grid will be copied from the host buffer in testing mode
753 std::memset(grid, 0, paddedGridSize[XX] * paddedGridSize[YY] * paddedGridSize[ZZ] * sizeof(ValueType));
754 for (const auto& gridValue : gridValues)
756 for (int i = 0; i < DIM; i++)
758 GMX_RELEASE_ASSERT((0 <= gridValue.first[i]) && (gridValue.first[i] < gridSize[i]),
759 "Invalid grid value index");
761 const size_t gridValueIndex =
762 pmeGetGridPlainIndexInternal(gridValue.first, paddedGridSize, gridOrdering);
763 grid[gridValueIndex] = gridValue.second;
767 default: GMX_THROW(InternalError("Test not implemented for this mode"));
771 //! Setting real grid to be used in gather
772 void pmeSetRealGrid(const gmx_pme_t* pme, CodePath mode, const SparseRealGridValuesInput& gridValues)
774 pmeSetGridInternal<real>(pme, mode, GridOrdering::XYZ, gridValues);
777 //! Setting complex grid to be used in solve
778 void pmeSetComplexGrid(const gmx_pme_t* pme,
780 GridOrdering gridOrdering,
781 const SparseComplexGridValuesInput& gridValues)
783 pmeSetGridInternal<t_complex>(pme, mode, gridOrdering, gridValues);
786 //! Getting the single dimension's spline values or derivatives
787 SplineParamsDimVector pmeGetSplineData(const gmx_pme_t* pme, CodePath mode, PmeSplineDataType type, int dimIndex)
789 GMX_RELEASE_ASSERT(pme != nullptr, "PME data is not initialized");
790 const PmeAtomComm* atc = &(pme->atc[0]);
791 const size_t atomCount = atc->numAtoms();
792 const size_t pmeOrder = pme->pme_order;
793 const size_t dimSize = pmeOrder * atomCount;
795 real* sourceBuffer = pmeGetSplineDataInternal(pme, type, dimIndex);
796 SplineParamsDimVector result;
800 pme_gpu_transform_spline_atom_data(pme->gpu, atc, type, dimIndex, PmeLayoutTransform::GpuToHost);
801 result = arrayRefFromArray(sourceBuffer, dimSize);
804 case CodePath::CPU: result = arrayRefFromArray(sourceBuffer, dimSize); break;
806 default: GMX_THROW(InternalError("Test not implemented for this mode"));
811 //! Getting the gridline indices
812 GridLineIndicesVector pmeGetGridlineIndices(const gmx_pme_t* pme, CodePath mode)
814 GMX_RELEASE_ASSERT(pme != nullptr, "PME data is not initialized");
815 const PmeAtomComm* atc = &(pme->atc[0]);
816 const size_t atomCount = atc->numAtoms();
818 GridLineIndicesVector gridLineIndices;
823 auto* gridlineIndicesAsIVec =
824 reinterpret_cast<IVec*>(pme_gpu_staging(pme->gpu).h_gridlineIndices);
825 ArrayRef<IVec> gridlineIndicesArrayRef = arrayRefFromArray(gridlineIndicesAsIVec, atomCount);
826 gridLineIndices = { gridlineIndicesArrayRef.begin(), gridlineIndicesArrayRef.end() };
830 case CodePath::CPU: gridLineIndices = { atc->idx.begin(), atc->idx.end() }; break;
832 default: GMX_THROW(InternalError("Test not implemented for this mode"));
834 return gridLineIndices;
837 //! Getting real or complex grid - only non zero values
838 template<typename ValueType>
839 static SparseGridValuesOutput<ValueType> pmeGetGridInternal(const gmx_pme_t* pme,
841 GridOrdering gridOrdering)
843 IVec gridSize(0, 0, 0), paddedGridSize(0, 0, 0);
845 pmeGetGridAndSizesInternal<ValueType>(pme, mode, grid, gridSize, paddedGridSize);
846 SparseGridValuesOutput<ValueType> gridValues;
849 case CodePath::GPU: // intentional absence of break
852 for (int ix = 0; ix < gridSize[XX]; ix++)
854 for (int iy = 0; iy < gridSize[YY]; iy++)
856 for (int iz = 0; iz < gridSize[ZZ]; iz++)
858 IVec temp(ix, iy, iz);
859 const size_t gridValueIndex =
860 pmeGetGridPlainIndexInternal(temp, paddedGridSize, gridOrdering);
861 const ValueType value = grid[gridValueIndex];
862 if (value != ValueType{})
864 auto key = formatString("Cell %d %d %d", ix, iy, iz);
865 gridValues[key] = value;
872 default: GMX_THROW(InternalError("Test not implemented for this mode"));
877 //! Getting the real grid (spreading output of pmePerformSplineAndSpread())
878 SparseRealGridValuesOutput pmeGetRealGrid(const gmx_pme_t* pme, CodePath mode)
880 return pmeGetGridInternal<real>(pme, mode, GridOrdering::XYZ);
883 //! Getting the complex grid output of pmePerformSolve()
884 SparseComplexGridValuesOutput pmeGetComplexGrid(const gmx_pme_t* pme, CodePath mode, GridOrdering gridOrdering)
886 return pmeGetGridInternal<t_complex>(pme, mode, gridOrdering);
889 //! Getting the reciprocal energy and virial
890 PmeOutput pmeGetReciprocalEnergyAndVirial(const gmx_pme_t* pme, CodePath mode, PmeSolveAlgorithm method)
893 const real lambdaQ = 1.0;
899 case PmeSolveAlgorithm::Coulomb:
900 get_pme_ener_vir_q(pme->solve_work, pme->nthread, &output);
903 case PmeSolveAlgorithm::LennardJones:
904 get_pme_ener_vir_lj(pme->solve_work, pme->nthread, &output);
907 default: GMX_THROW(InternalError("Test not implemented for this mode"));
913 case PmeSolveAlgorithm::Coulomb:
914 pme_gpu_getEnergyAndVirial(*pme, lambdaQ, &output);
917 default: GMX_THROW(InternalError("Test not implemented for this mode"));
921 default: GMX_THROW(InternalError("Test not implemented for this mode"));
926 PmeTestHardwareContext::PmeTestHardwareContext() : codePath_(CodePath::CPU) {}
928 PmeTestHardwareContext::PmeTestHardwareContext(TestDevice* testDevice) :
929 codePath_(CodePath::GPU), testDevice_(testDevice)
931 setActiveDevice(testDevice_->deviceInfo());
932 pmeGpuProgram_ = buildPmeGpuProgram(testDevice_->deviceContext());
935 //! Returns a human-readable context description line
936 std::string PmeTestHardwareContext::description() const
940 case CodePath::CPU: return "CPU";
941 case CodePath::GPU: return "GPU (" + testDevice_->description() + ")";
942 default: return "Unknown code path.";
946 void PmeTestHardwareContext::activate() const
948 if (codePath_ == CodePath::GPU)
950 setActiveDevice(testDevice_->deviceInfo());
954 std::vector<std::unique_ptr<PmeTestHardwareContext>> createPmeTestHardwareContextList()
956 std::vector<std::unique_ptr<PmeTestHardwareContext>> pmeTestHardwareContextList;
958 pmeTestHardwareContextList.emplace_back(std::make_unique<PmeTestHardwareContext>());
960 const auto& testDeviceList = getTestHardwareEnvironment()->getTestDeviceList();
961 for (const auto& testDevice : testDeviceList)
963 pmeTestHardwareContextList.emplace_back(std::make_unique<PmeTestHardwareContext>(testDevice.get()));
965 return pmeTestHardwareContextList;