b1bacbeebef17ec1f17ac28d37d811c0f4123aff
[alexxy/gromacs.git] / src / gromacs / hardware / detecthardware.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014,2015,2016 by the GROMACS development team.
5  * Copyright (c) 2017,2018,2019,2020, 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.
9  *
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.
14  *
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.
19  *
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.
24  *
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.
32  *
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.
35  */
36 #include "gmxpre.h"
37
38 #include "detecthardware.h"
39
40 #include "config.h"
41
42 #include <algorithm>
43 #include <array>
44 #include <chrono>
45 #include <memory>
46 #include <string>
47 #include <thread>
48 #include <vector>
49
50 #include "gromacs/compat/pointers.h"
51 #include "gromacs/hardware/cpuinfo.h"
52 #include "gromacs/hardware/device_management.h"
53 #include "gromacs/hardware/hardwaretopology.h"
54 #include "gromacs/hardware/hw_info.h"
55 #include "gromacs/simd/support.h"
56 #include "gromacs/utility/basedefinitions.h"
57 #include "gromacs/utility/basenetwork.h"
58 #include "gromacs/utility/baseversion.h"
59 #include "gromacs/utility/cstringutil.h"
60 #include "gromacs/utility/exceptions.h"
61 #include "gromacs/utility/fatalerror.h"
62 #include "gromacs/utility/gmxassert.h"
63 #include "gromacs/utility/inmemoryserializer.h"
64 #include "gromacs/utility/logger.h"
65 #include "gromacs/utility/mutex.h"
66 #include "gromacs/utility/physicalnodecommunicator.h"
67
68 #include "architecture.h"
69 #include "device_information.h"
70
71 #ifdef HAVE_UNISTD_H
72 #    include <unistd.h> // sysconf()
73 #endif
74
75 gmx_hw_info_t::gmx_hw_info_t(std::unique_ptr<gmx::CpuInfo>          cpuInfo,
76                              std::unique_ptr<gmx::HardwareTopology> hardwareTopology) :
77     cpuInfo(std::move(cpuInfo)),
78     hardwareTopology(std::move(hardwareTopology))
79 {
80 }
81
82 gmx_hw_info_t::~gmx_hw_info_t() = default;
83
84 namespace gmx
85 {
86
87 //! Convenience macro to help us avoid ifdefs each time we use sysconf
88 #if !defined(_SC_NPROCESSORS_ONLN) && defined(_SC_NPROC_ONLN)
89 #    define _SC_NPROCESSORS_ONLN _SC_NPROC_ONLN
90 #endif
91
92 //! Convenience macro to help us avoid ifdefs each time we use sysconf
93 #if !defined(_SC_NPROCESSORS_CONF) && defined(_SC_NPROC_CONF)
94 #    define _SC_NPROCESSORS_CONF _SC_NPROC_CONF
95 #endif
96
97 /*! \brief Information about the hardware of all nodes (common to all threads in this process).
98  *
99  * This information is constructed only when required, but thereafter
100  * its lifetime is that of the whole process, potentially across
101  * multiple successive simulation parts. It's wise to ensure that only
102  * one thread can create the information, but thereafter they can all
103  * read it without e.g. needing a std::shared_ptr to ensure its
104  * lifetime exceeds that of the thread. */
105 static std::unique_ptr<gmx_hw_info_t> g_hardwareInfo;
106 //! A mutex to protect the hwinfo structure
107 static Mutex g_hardwareInfoMutex;
108
109 //! Detect GPUs, if that makes sense to attempt.
110 static void gmx_detect_gpus(const gmx::MDLogger&             mdlog,
111                             const PhysicalNodeCommunicator&  physicalNodeComm,
112                             compat::not_null<gmx_hw_info_t*> hardwareInfo)
113 {
114     if (!isDeviceDetectionEnabled())
115     {
116         return;
117     }
118
119     std::string errorMessage;
120
121     bool isMasterRankOfPhysicalNode = true;
122 #if GMX_LIB_MPI
123     isMasterRankOfPhysicalNode = (physicalNodeComm.rank_ == 0);
124 #else
125     // We choose to run the detection only once with thread-MPI and
126     // use a mutex to enforce it.
127     GMX_UNUSED_VALUE(physicalNodeComm);
128     isMasterRankOfPhysicalNode = true;
129 #endif
130
131     /* The OpenCL support requires us to run detection on all ranks.
132      * With CUDA we don't need to, and prefer to detect on one rank
133      * and send the information to the other ranks over MPI. */
134     constexpr bool allRanksMustDetectGpus = (GMX_GPU_OPENCL != 0);
135     bool           gpusCanBeDetected      = false;
136     if (isMasterRankOfPhysicalNode || allRanksMustDetectGpus)
137     {
138         std::string errorMessage;
139         gpusCanBeDetected = isDeviceDetectionFunctional(&errorMessage);
140         if (!gpusCanBeDetected)
141         {
142             GMX_LOG(mdlog.warning)
143                     .asParagraph()
144                     .appendTextFormatted(
145                             "NOTE: Detection of GPUs failed. The API reported:\n"
146                             "      %s\n"
147                             "      GROMACS cannot run tasks on a GPU.",
148                             errorMessage.c_str());
149         }
150     }
151
152     if (gpusCanBeDetected)
153     {
154         hardwareInfo->deviceInfoList = findDevices();
155         // No need to tell the user anything at this point, they get a
156         // hardware report later.
157     }
158
159 #if GMX_LIB_MPI
160     if (!allRanksMustDetectGpus && (physicalNodeComm.size_ > 1))
161     {
162         // Master rank must serialize the device information list and
163         // send it to the other ranks on this node.
164         std::vector<char> buffer;
165         int               sizeOfBuffer;
166         if (isMasterRankOfPhysicalNode)
167         {
168             gmx::InMemorySerializer writer;
169             serializeDeviceInformations(hardwareInfo->deviceInfoList, &writer);
170             buffer       = writer.finishAndGetBuffer();
171             sizeOfBuffer = buffer.size();
172         }
173         // Ensure all ranks agree on the size of list to be sent
174         MPI_Bcast(&sizeOfBuffer, 1, MPI_INT, 0, physicalNodeComm.comm_);
175         buffer.resize(sizeOfBuffer);
176         if (!buffer.empty())
177         {
178             // Send the list and deserialize it
179             MPI_Bcast(buffer.data(), buffer.size(), MPI_BYTE, 0, physicalNodeComm.comm_);
180             if (!isMasterRankOfPhysicalNode)
181             {
182                 gmx::InMemoryDeserializer reader(buffer, false);
183                 hardwareInfo->deviceInfoList = deserializeDeviceInformations(&reader);
184             }
185         }
186     }
187 #endif
188 }
189
190 //! Reduce the locally collected \p hardwareInfo over MPI ranks
191 static void gmx_collect_hardware_mpi(const gmx::CpuInfo&              cpuInfo,
192                                      const PhysicalNodeCommunicator&  physicalNodeComm,
193                                      compat::not_null<gmx_hw_info_t*> hardwareInfo)
194 {
195     const int ncore = hardwareInfo->hardwareTopology->numberOfCores();
196     /* Zen1 is assumed for:
197      * - family=23 with the below listed models;
198      * - Hygon as vendor.
199      */
200     const bool cpuIsAmdZen1 = ((cpuInfo.vendor() == CpuInfo::Vendor::Amd && cpuInfo.family() == 23
201                                 && (cpuInfo.model() == 1 || cpuInfo.model() == 17
202                                     || cpuInfo.model() == 8 || cpuInfo.model() == 24))
203                                || cpuInfo.vendor() == CpuInfo::Vendor::Hygon);
204
205     int numCompatibleDevices = getCompatibleDevices(hardwareInfo->deviceInfoList).size();
206 #if GMX_LIB_MPI
207     int nhwthread;
208     int gpu_hash;
209
210     nhwthread = hardwareInfo->nthreads_hw_avail;
211     /* Create a unique hash of the GPU type(s) in this node */
212     gpu_hash = 0;
213     /* Here it might be better to only loop over the compatible GPU, but we
214      * don't have that information available and it would also require
215      * removing the device ID from the device info string.
216      */
217     for (const auto& deviceInfo : hardwareInfo->deviceInfoList)
218     {
219         /* Since the device ID is incorporated in the hash, the order of
220          * the GPUs affects the hash. Also two identical GPUs won't give
221          * a gpu_hash of zero after XORing.
222          */
223         std::string deviceInfoString = getDeviceInformationString(*deviceInfo);
224         gpu_hash ^= gmx_string_fullhash_func(deviceInfoString.c_str(), gmx_string_hash_init);
225     }
226
227     constexpr int                      numElementsCounts = 4;
228     std::array<int, numElementsCounts> countsReduced;
229     {
230         std::array<int, numElementsCounts> countsLocal = { { 0 } };
231         // Organize to sum values from only one rank within each node,
232         // so we get the sum over all nodes.
233         bool isMasterRankOfPhysicalNode = (physicalNodeComm.rank_ == 0);
234         if (isMasterRankOfPhysicalNode)
235         {
236             countsLocal[0] = 1;
237             countsLocal[1] = ncore;
238             countsLocal[2] = nhwthread;
239             countsLocal[3] = numCompatibleDevices;
240         }
241
242         MPI_Allreduce(countsLocal.data(), countsReduced.data(), countsLocal.size(), MPI_INT,
243                       MPI_SUM, MPI_COMM_WORLD);
244     }
245
246     constexpr int                   numElementsMax = 11;
247     std::array<int, numElementsMax> maxMinReduced;
248     {
249         std::array<int, numElementsMax> maxMinLocal;
250         /* Store + and - values for all ranks,
251          * so we can get max+min with one MPI call.
252          */
253         maxMinLocal[0]  = ncore;
254         maxMinLocal[1]  = nhwthread;
255         maxMinLocal[2]  = numCompatibleDevices;
256         maxMinLocal[3]  = static_cast<int>(gmx::simdSuggested(cpuInfo));
257         maxMinLocal[4]  = gpu_hash;
258         maxMinLocal[5]  = -maxMinLocal[0];
259         maxMinLocal[6]  = -maxMinLocal[1];
260         maxMinLocal[7]  = -maxMinLocal[2];
261         maxMinLocal[8]  = -maxMinLocal[3];
262         maxMinLocal[9]  = -maxMinLocal[4];
263         maxMinLocal[10] = (cpuIsAmdZen1 ? 1 : 0);
264
265         MPI_Allreduce(maxMinLocal.data(), maxMinReduced.data(), maxMinLocal.size(), MPI_INT,
266                       MPI_MAX, MPI_COMM_WORLD);
267     }
268
269     hardwareInfo->nphysicalnode       = countsReduced[0];
270     hardwareInfo->ncore_tot           = countsReduced[1];
271     hardwareInfo->ncore_min           = -maxMinReduced[5];
272     hardwareInfo->ncore_max           = maxMinReduced[0];
273     hardwareInfo->nhwthread_tot       = countsReduced[2];
274     hardwareInfo->nhwthread_min       = -maxMinReduced[6];
275     hardwareInfo->nhwthread_max       = maxMinReduced[1];
276     hardwareInfo->ngpu_compatible_tot = countsReduced[3];
277     hardwareInfo->ngpu_compatible_min = -maxMinReduced[7];
278     hardwareInfo->ngpu_compatible_max = maxMinReduced[2];
279     hardwareInfo->simd_suggest_min    = -maxMinReduced[8];
280     hardwareInfo->simd_suggest_max    = maxMinReduced[3];
281     hardwareInfo->bIdenticalGPUs      = (maxMinReduced[4] == -maxMinReduced[9]);
282     hardwareInfo->haveAmdZen1Cpu      = (maxMinReduced[10] > 0);
283 #else
284     /* All ranks use the same pointer, protected by a mutex in the caller */
285     hardwareInfo->nphysicalnode       = 1;
286     hardwareInfo->ncore_tot           = ncore;
287     hardwareInfo->ncore_min           = ncore;
288     hardwareInfo->ncore_max           = ncore;
289     hardwareInfo->nhwthread_tot       = hardwareInfo->nthreads_hw_avail;
290     hardwareInfo->nhwthread_min       = hardwareInfo->nthreads_hw_avail;
291     hardwareInfo->nhwthread_max       = hardwareInfo->nthreads_hw_avail;
292     hardwareInfo->ngpu_compatible_tot = numCompatibleDevices;
293     hardwareInfo->ngpu_compatible_min = numCompatibleDevices;
294     hardwareInfo->ngpu_compatible_max = numCompatibleDevices;
295     hardwareInfo->simd_suggest_min    = static_cast<int>(simdSuggested(cpuInfo));
296     hardwareInfo->simd_suggest_max    = static_cast<int>(simdSuggested(cpuInfo));
297     hardwareInfo->bIdenticalGPUs      = TRUE;
298     hardwareInfo->haveAmdZen1Cpu      = cpuIsAmdZen1;
299     GMX_UNUSED_VALUE(physicalNodeComm);
300 #endif
301 }
302
303 /*! \brief Utility that does dummy computing for max 2 seconds to spin up cores
304  *
305  *  This routine will check the number of cores configured and online
306  *  (using sysconf), and the spins doing dummy compute operations for up to
307  *  2 seconds, or until all cores have come online. This can be used prior to
308  *  hardware detection for platforms that take unused processors offline.
309  *
310  *  This routine will not throw exceptions. In principle it should be
311  *  declared noexcept, but at least icc 19.1 and 21-beta08 with the
312  *  libstdc++-7.5 has difficulty implementing a std::vector of
313  *  std::thread started with this function when declared noexcept. It
314  *  is not clear whether the problem is the compiler or the standard
315  *  library. Fortunately, this function is not performance sensitive,
316  *  and only runs on platforms other than x86 and POWER (ie ARM),
317  *  so the possible overhead introduced by omitting noexcept is not
318  *  important.
319  */
320 static void spinUpCore()
321 {
322 #if defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_CONF) && defined(_SC_NPROCESSORS_ONLN)
323     float dummy           = 0.1;
324     int   countConfigured = sysconf(_SC_NPROCESSORS_CONF);    // noexcept
325     auto  start           = std::chrono::steady_clock::now(); // noexcept
326
327     while (sysconf(_SC_NPROCESSORS_ONLN) < countConfigured
328            && std::chrono::steady_clock::now() - start < std::chrono::seconds(2))
329     {
330         for (int i = 1; i < 10000; i++)
331         {
332             dummy /= i;
333         }
334     }
335
336     if (dummy < 0)
337     {
338         printf("This cannot happen, but prevents loop from being optimized away.");
339     }
340 #endif
341 }
342
343 /*! \brief Prepare the system before hardware topology detection
344  *
345  * This routine should perform any actions we want to put the system in a state
346  * where we want it to be before detecting the hardware topology. For most
347  * processors there is nothing to do, but some architectures (in particular ARM)
348  * have support for taking configured cores offline, which will make them disappear
349  * from the online processor count.
350  *
351  * This routine checks if there is a mismatch between the number of cores
352  * configured and online, and in that case we issue a small workload that
353  * attempts to wake sleeping cores before doing the actual detection.
354  *
355  * This type of mismatch can also occur for x86 or PowerPC on Linux, if SMT has only
356  * been disabled in the kernel (rather than bios). Since those cores will never
357  * come online automatically, we currently skip this test for x86 & PowerPC to
358  * avoid wasting 2 seconds. We also skip the test if there is no thread support.
359  *
360  * \note Cores will sleep relatively quickly again, so it's important to issue
361  *       the real detection code directly after this routine.
362  */
363 static void hardwareTopologyPrepareDetection()
364 {
365 #if defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_CONF) \
366         && (defined(THREAD_PTHREADS) || defined(THREAD_WINDOWS))
367
368     // Modify this conditional when/if x86 or PowerPC starts to sleep some cores
369     if (c_architecture != Architecture::X86 && c_architecture != Architecture::PowerPC)
370     {
371         int                      countConfigured = sysconf(_SC_NPROCESSORS_CONF);
372         std::vector<std::thread> workThreads(countConfigured);
373
374         for (auto& t : workThreads)
375         {
376             t = std::thread(spinUpCore);
377         }
378
379         for (auto& t : workThreads)
380         {
381             t.join();
382         }
383     }
384 #endif
385 }
386
387 /*! \brief Sanity check hardware topology and print some notes to log
388  *
389  *  \param mdlog            Logger.
390  *  \param hardwareTopology Reference to hardwareTopology object.
391  */
392 static void hardwareTopologyDoubleCheckDetection(const gmx::MDLogger gmx_unused& mdlog,
393                                                  const gmx::HardwareTopology gmx_unused& hardwareTopology)
394 {
395 #if defined HAVE_SYSCONF && defined(_SC_NPROCESSORS_CONF)
396     if (hardwareTopology.supportLevel() < gmx::HardwareTopology::SupportLevel::LogicalProcessorCount)
397     {
398         return;
399     }
400
401     int countFromDetection = hardwareTopology.machine().logicalProcessorCount;
402     int countConfigured    = sysconf(_SC_NPROCESSORS_CONF);
403
404     /* BIOS, kernel or user actions can take physical processors
405      * offline. We already cater for the some of the cases inside the hardwareToplogy
406      * by trying to spin up cores just before we detect, but there could be other
407      * cases where it is worthwhile to hint that there might be more resources available.
408      */
409     if (countConfigured >= 0 && countConfigured != countFromDetection)
410     {
411         GMX_LOG(mdlog.info)
412                 .appendTextFormatted(
413                         "Note: %d CPUs configured, but only %d were detected to be online.\n",
414                         countConfigured, countFromDetection);
415
416         if (c_architecture == Architecture::X86 && countConfigured == 2 * countFromDetection)
417         {
418             GMX_LOG(mdlog.info)
419                     .appendText(
420                             "      X86 Hyperthreading is likely disabled; enable it for better "
421                             "performance.");
422         }
423         // For PowerPC (likely Power8) it is possible to set SMT to either 2,4, or 8-way hardware threads.
424         // We only warn if it is completely disabled since default performance drops with SMT8.
425         if (c_architecture == Architecture::PowerPC && countConfigured == 8 * countFromDetection)
426         {
427             GMX_LOG(mdlog.info)
428                     .appendText(
429                             "      PowerPC SMT is likely disabled; enable SMT2/SMT4 for better "
430                             "performance.");
431         }
432     }
433 #endif
434 }
435
436 gmx_hw_info_t* gmx_detect_hardware(const gmx::MDLogger& mdlog, const PhysicalNodeCommunicator& physicalNodeComm)
437 {
438     // By construction, only one thread ever runs hardware detection,
439     // but we may as well prevent issues arising if that would change.
440     // Taking the lock early ensures that exactly one thread can
441     // attempt to construct g_hardwareInfo.
442     lock_guard<Mutex> lock(g_hardwareInfoMutex);
443
444     // If we already have the information, just return a handle to it.
445     if (g_hardwareInfo != nullptr)
446     {
447         return g_hardwareInfo.get();
448     }
449
450     // Make the new hardwareInfo in a temporary.
451     hardwareTopologyPrepareDetection();
452
453     // TODO: We should also do CPU hardware detection only once on each
454     // physical node and broadcast it, instead of doing it on every MPI rank.
455     auto hardwareInfo = std::make_unique<gmx_hw_info_t>(
456             std::make_unique<CpuInfo>(CpuInfo::detect()),
457             std::make_unique<HardwareTopology>(HardwareTopology::detect()));
458
459     // If we detected the topology on this system, double-check that it makes sense
460     if (hardwareInfo->hardwareTopology->isThisSystem())
461     {
462         hardwareTopologyDoubleCheckDetection(mdlog, *hardwareInfo->hardwareTopology);
463     }
464
465     // TODO: Get rid of this altogether.
466     hardwareInfo->nthreads_hw_avail = hardwareInfo->hardwareTopology->machine().logicalProcessorCount;
467
468     // Detect GPUs
469     gmx_detect_gpus(mdlog, physicalNodeComm, compat::make_not_null(hardwareInfo));
470     gmx_collect_hardware_mpi(*hardwareInfo->cpuInfo, physicalNodeComm, compat::make_not_null(hardwareInfo));
471
472     // Now that the temporary is fully constructed, swap it to become
473     // the real thing.
474     g_hardwareInfo.swap(hardwareInfo);
475
476     return g_hardwareInfo.get();
477 }
478
479 } // namespace gmx