SYCL: Avoid using no_init read accessor in rocFFT
[alexxy/gromacs.git] / src / gromacs / taskassignment / usergpuids.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2017,2018,2019,2020,2021, 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.
8  *
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.
13  *
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.
18  *
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.
23  *
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.
31  *
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.
34  */
35 /*! \internal \file
36  * \brief Defines routines for handling user-specified GPU IDs.
37  *
38  * \author Mark Abraham <mark.j.abraham@gmail.com>
39  * \ingroup module_taskassignment
40  */
41 #include "gmxpre.h"
42
43 #include "usergpuids.h"
44
45 #include <cctype>
46
47 #include <algorithm>
48 #include <sstream>
49 #include <string>
50 #include <vector>
51
52 #include "gromacs/hardware/device_management.h"
53 #include "gromacs/hardware/hw_info.h"
54 #include "gromacs/utility/exceptions.h"
55 #include "gromacs/utility/stringutil.h"
56
57 namespace gmx
58 {
59
60 /*! \brief Parse a GPU ID specifier string into a container.
61  *
62  * \param[in]   gpuIdString  String like "013" or "0,1,3" typically
63  *                           supplied by the user.
64  *                           Must contain only unique decimal digits, or only decimal
65  *                           digits separated by comma delimiters. A terminal
66  *                           comma is accceptable (and required to specify a
67  *                           single ID that is larger than 9).
68  *
69  * \returns  A vector of numeric IDs extracted from \c gpuIdString.
70  *
71  * \throws   std::bad_alloc     If out of memory.
72  *           InvalidInputError  If an invalid character is found (ie not a digit or ',').
73  */
74 static std::vector<int> parseGpuDeviceIdentifierList(const std::string& gpuIdString)
75 {
76     std::vector<int> digits;
77     auto             foundCommaDelimiters = gpuIdString.find(',') != std::string::npos;
78     if (!foundCommaDelimiters)
79     {
80         for (const auto& c : gpuIdString)
81         {
82             if (std::isdigit(c) == 0)
83             {
84                 GMX_THROW(InvalidInputError(
85                         formatString("Invalid character in GPU ID string: \"%c\"\n", c)));
86             }
87             // Convert each character in the token to an integer
88             digits.push_back(c - '0');
89         }
90     }
91     else
92     {
93         if (gpuIdString[0] == ',')
94         {
95             GMX_THROW(InvalidInputError("Invalid use of leading comma in GPU ID string"));
96         }
97         std::istringstream ss(gpuIdString);
98         std::string        token;
99         digits.reserve(gpuIdString.length());
100         token.reserve(gpuIdString.length());
101         while (std::getline(ss, token, ','))
102         {
103             // Convert the whole token to an integer
104             if (token.empty())
105             {
106                 GMX_THROW(InvalidInputError("Invalid use of comma in GPU ID string"));
107             }
108             digits.push_back(std::stoi(token));
109         }
110     }
111     return digits;
112 }
113
114 std::vector<int> parseUserGpuIdString(const std::string& gpuIdString)
115 {
116     // An optional comma is used to separate GPU IDs assigned to the
117     // same type of task, which will be useful for any nodes that have
118     // more than ten GPUs.
119
120     auto digits = parseGpuDeviceIdentifierList(gpuIdString);
121
122     // Check and enforce that no duplicate IDs are allowed
123     for (size_t i = 0; i != digits.size(); ++i)
124     {
125         for (size_t j = i + 1; j != digits.size(); ++j)
126         {
127             if (digits[i] == digits[j])
128             {
129                 GMX_THROW(
130                         InvalidInputError(formatString("The string of available GPU device IDs "
131                                                        "'%s' may not contain duplicate device IDs",
132                                                        gpuIdString.c_str())));
133             }
134         }
135     }
136     return digits;
137 }
138
139 std::vector<int> makeListOfAvailableDevices(gmx::ArrayRef<const std::unique_ptr<DeviceInformation>> deviceInfoList,
140                                             const std::string& devicesSelectedByUserString)
141 {
142     std::vector<int> devicesSelectedByUser = parseUserGpuIdString(devicesSelectedByUserString);
143
144     if (devicesSelectedByUser.empty())
145     {
146         // The user didn't restrict the choice, so we use all compatible devices.
147         return getCompatibleDeviceIds(deviceInfoList);
148     }
149
150     std::vector<int> availableDevices;
151     availableDevices.reserve(devicesSelectedByUser.size());
152     std::vector<int> incompatibleDevicesSelectedByUser;
153     for (const int& selectedDeviceId : devicesSelectedByUser)
154     {
155         if (deviceIdIsCompatible(deviceInfoList, selectedDeviceId))
156         {
157             availableDevices.push_back(selectedDeviceId);
158         }
159         else
160         {
161             // Prepare data for an error message about all incompatible devices that were selected by the user.
162             incompatibleDevicesSelectedByUser.push_back(selectedDeviceId);
163         }
164     }
165     if (!incompatibleDevicesSelectedByUser.empty())
166     {
167         auto message = "You requested mdrun to use GPU devices with IDs " + devicesSelectedByUserString
168                        + ", but that includes the following incompatible devices: "
169                        + formatAndJoin(incompatibleDevicesSelectedByUser, ",", StringFormatter("%d"))
170                        + ". Request only compatible devices.";
171         GMX_THROW(InvalidInputError(message));
172     }
173     return availableDevices;
174 }
175
176 std::vector<int> parseUserTaskAssignmentString(const std::string& gpuIdString)
177 {
178     // Implement any additional constraints here that need to be imposed
179
180     return parseGpuDeviceIdentifierList(gpuIdString);
181 }
182
183 std::vector<int> makeGpuIds(ArrayRef<const int> compatibleGpus, size_t numGpuTasks)
184 {
185     std::vector<int> gpuIdsToUse;
186
187     gpuIdsToUse.reserve(numGpuTasks);
188
189     auto currentGpuId = compatibleGpus.begin();
190     for (size_t i = 0; i != numGpuTasks; ++i)
191     {
192         GMX_ASSERT(!compatibleGpus.empty(),
193                    "Must have compatible GPUs from which to build a list of GPU IDs to use");
194         gpuIdsToUse.push_back(*currentGpuId);
195         ++currentGpuId;
196         if (currentGpuId == compatibleGpus.end())
197         {
198             // Wrap around and assign tasks again.
199             currentGpuId = compatibleGpus.begin();
200         }
201     }
202     std::sort(gpuIdsToUse.begin(), gpuIdsToUse.end());
203     return gpuIdsToUse;
204 }
205
206 std::string makeGpuIdString(const std::vector<int>& gpuIds, int totalNumberOfTasks)
207 {
208     auto resultGpuIds = makeGpuIds(gpuIds, totalNumberOfTasks);
209     return formatAndJoin(resultGpuIds, ",", StringFormatter("%d"));
210 }
211
212 void checkUserGpuIds(const ArrayRef<const std::unique_ptr<DeviceInformation>> deviceInfoList,
213                      const ArrayRef<const int>                                compatibleGpus,
214                      const ArrayRef<const int>                                gpuIds)
215 {
216     bool        foundIncompatibleGpuIds = false;
217     std::string message =
218             "Some of the requested GPUs do not exist, behave strangely, or are not compatible:\n";
219
220     for (const auto& gpuId : gpuIds)
221     {
222         if (std::find(compatibleGpus.begin(), compatibleGpus.end(), gpuId) == compatibleGpus.end())
223         {
224             foundIncompatibleGpuIds = true;
225             message += gmx::formatString("    GPU #%d: %s\n",
226                                          gpuId,
227                                          getDeviceCompatibilityDescription(deviceInfoList, gpuId).c_str());
228         }
229     }
230     if (foundIncompatibleGpuIds)
231     {
232         GMX_THROW(InconsistentInputError(message));
233     }
234 }
235
236 } // namespace gmx