xref: /petsc/src/sys/objects/device/impls/cupm/cupmdevice.cxx (revision 6524c165f7ddaf30fd7457737f668f984c8ababf)
1 #include <petsc/private/cpp/memory.hpp> // make_unique
2 
3 #include "cupmdevice.hpp"
4 
5 #include <algorithm>
6 #include <csetjmp> // for cuda mpi awareness
7 #include <csignal> // SIGSEGV
8 #include <iterator>
9 #include <type_traits>
10 
11 namespace Petsc {
12 
13 namespace device {
14 
15 namespace cupm {
16 
17 // internal "impls" class for CUPMDevice. Each instance represents a single cupm device
18 template <DeviceType T>
19 class Device<T>::DeviceInternal {
20   const int        id_;
21   bool             devInitialized_ = false;
22   cupmDeviceProp_t dprop_{}; // cudaDeviceProp appears to be an actual struct, i.e. you can't
23                              // initialize it with nullptr or NULL (i've tried)
24 
25   PETSC_CXX_COMPAT_DECL(PetscErrorCode CUPMAwareMPI_(bool *));
26 
27 public:
28   // default constructor
29   explicit constexpr DeviceInternal(int dev) noexcept : id_(dev) { }
30 
31   // gather all relevant information for a particular device, a cupmDeviceProp_t is
32   // usually sufficient here
33   PETSC_NODISCARD PetscErrorCode initialize() noexcept;
34   PETSC_NODISCARD PetscErrorCode configure() noexcept;
35   PETSC_NODISCARD PetscErrorCode view(PetscViewer) const noexcept;
36   PETSC_NODISCARD PetscErrorCode getattribute(PetscDeviceAttribute, void *) const noexcept;
37 
38   PETSC_NODISCARD auto id() const -> decltype(id_) { return id_; }
39   PETSC_NODISCARD auto initialized() const -> decltype(devInitialized_) { return devInitialized_; }
40   PETSC_NODISCARD auto prop() const -> const decltype(dprop_) & { return dprop_; }
41 };
42 
43 // the goal here is simply to get the cupm backend to create its context, not to do any type of
44 // modification of it, or create objects (since these may be affected by subsequent
45 // configuration changes)
46 template <DeviceType T>
47 PetscErrorCode Device<T>::DeviceInternal::initialize() noexcept {
48   PetscFunctionBegin;
49   if (initialized()) PetscFunctionReturn(0);
50   devInitialized_ = true;
51   // need to do this BEFORE device has been set, although if the user
52   // has already done this then we just ignore it
53   if (cupmSetDeviceFlags(cupmDeviceMapHost) == cupmErrorSetOnActiveProcess) {
54     // reset the error if it was cupmErrorSetOnActiveProcess
55     const auto PETSC_UNUSED unused = cupmGetLastError();
56   } else PetscCallCUPM(cupmGetLastError());
57   // cuda 5.0+ will create a context when cupmSetDevice is called
58   if (cupmSetDevice(id()) != cupmErrorDeviceAlreadyInUse) PetscCallCUPM(cupmGetLastError());
59   // and in case it doesn't, explicitly call init here
60   PetscCallCUPM(cupmInit(0));
61   // where is this variable defined and when is it set? who knows! but it is defined and set
62   // at this point. either way, each device must make this check since I guess MPI might not be
63   // aware of all of them?
64   if (use_gpu_aware_mpi) {
65     bool aware;
66 
67     PetscCall(CUPMAwareMPI_(&aware));
68     // For OpenMPI, we could do a compile time check with
69     // "defined(PETSC_HAVE_OMPI_MAJOR_VERSION) && defined(MPIX_CUDA_AWARE_SUPPORT) &&
70     // MPIX_CUDA_AWARE_SUPPORT" to see if it is CUDA-aware. However, recent versions of IBM
71     // Spectrum MPI (e.g., 10.3.1) on Summit meet above conditions, but one has to use jsrun
72     // --smpiargs=-gpu to really enable GPU-aware MPI. So we do the check at runtime with a
73     // code that works only with GPU-aware MPI.
74     if (PetscUnlikely(!aware)) {
75       (*PetscErrorPrintf)("PETSc is configured with GPU support, but your MPI is not GPU-aware. For better performance, please use a GPU-aware MPI.\n");
76       (*PetscErrorPrintf)("If you do not care, add option -use_gpu_aware_mpi 0. To not see the message again, add the option to your .petscrc, OR add it to the env var PETSC_OPTIONS.\n");
77       (*PetscErrorPrintf)("If you do care, for IBM Spectrum MPI on OLCF Summit, you may need jsrun --smpiargs=-gpu.\n");
78       (*PetscErrorPrintf)("For OpenMPI, you need to configure it --with-cuda (https://www.open-mpi.org/faq/?category=buildcuda)\n");
79       (*PetscErrorPrintf)("For MVAPICH2-GDR, you need to set MV2_USE_CUDA=1 (http://mvapich.cse.ohio-state.edu/userguide/gdr/)\n");
80       (*PetscErrorPrintf)("For Cray-MPICH, you need to set MPICH_RDMA_ENABLED_CUDA=1 (https://www.olcf.ornl.gov/tutorials/gpudirect-mpich-enabled-cuda/)\n");
81       PETSCABORT(PETSC_COMM_SELF, PETSC_ERR_LIB);
82     }
83   }
84   PetscFunctionReturn(0);
85 }
86 
87 template <DeviceType T>
88 PetscErrorCode Device<T>::DeviceInternal::configure() noexcept {
89   PetscFunctionBegin;
90   PetscAssert(initialized(), PETSC_COMM_SELF, PETSC_ERR_COR, "Device %d being configured before it was initialized", id());
91   // why on EARTH nvidia insists on making otherwise informational states into
92   // fully-fledged error codes is beyond me. Why couldn't a pointer to bool argument have
93   // sufficed?!?!?!
94   if (cupmSetDevice(id_) != cupmErrorDeviceAlreadyInUse) PetscCallCUPM(cupmGetLastError());
95   // need to update the device properties
96   PetscCallCUPM(cupmGetDeviceProperties(&dprop_, id_));
97   PetscCall(PetscInfo(nullptr, "Configured device %d\n", id_));
98   PetscFunctionReturn(0);
99 }
100 
101 template <DeviceType T>
102 PetscErrorCode Device<T>::DeviceInternal::view(PetscViewer viewer) const noexcept {
103   PetscBool iascii;
104 
105   PetscFunctionBegin;
106   PetscAssert(initialized(), PETSC_COMM_SELF, PETSC_ERR_COR, "Device %d being viewed before it was initialized or configured", id());
107   // we don't print device-specific info in CI-mode
108   if (PetscUnlikely(PetscCIEnabled)) PetscFunctionReturn(0);
109   PetscCall(PetscObjectTypeCompare(PetscObjectCast(viewer), PETSCVIEWERASCII, &iascii));
110   if (iascii) {
111     MPI_Comm    comm;
112     PetscMPIInt rank;
113     PetscViewer sviewer;
114 
115     PetscCall(PetscObjectGetComm(PetscObjectCast(viewer), &comm));
116     PetscCallMPI(MPI_Comm_rank(comm, &rank));
117     PetscCall(PetscViewerGetSubViewer(viewer, PETSC_COMM_SELF, &sviewer));
118     PetscCall(PetscViewerASCIIPrintf(sviewer, "[%d] name: %s\n", rank, dprop_.name));
119     PetscCall(PetscViewerASCIIPushTab(sviewer));
120     PetscCall(PetscViewerASCIIPrintf(sviewer, "Compute capability: %d.%d\n", dprop_.major, dprop_.minor));
121     PetscCall(PetscViewerASCIIPrintf(sviewer, "Multiprocessor Count: %d\n", dprop_.multiProcessorCount));
122     PetscCall(PetscViewerASCIIPrintf(sviewer, "Maximum Grid Dimensions: %d x %d x %d\n", dprop_.maxGridSize[0], dprop_.maxGridSize[1], dprop_.maxGridSize[2]));
123     PetscCall(PetscViewerASCIIPrintf(sviewer, "Maximum Block Dimensions: %d x %d x %d\n", dprop_.maxThreadsDim[0], dprop_.maxThreadsDim[1], dprop_.maxThreadsDim[2]));
124     PetscCall(PetscViewerASCIIPrintf(sviewer, "Maximum Threads Per Block: %d\n", dprop_.maxThreadsPerBlock));
125     PetscCall(PetscViewerASCIIPrintf(sviewer, "Warp Size: %d\n", dprop_.warpSize));
126     PetscCall(PetscViewerASCIIPrintf(sviewer, "Total Global Memory (bytes): %zu\n", dprop_.totalGlobalMem));
127     PetscCall(PetscViewerASCIIPrintf(sviewer, "Total Constant Memory (bytes): %zu\n", dprop_.totalConstMem));
128     PetscCall(PetscViewerASCIIPrintf(sviewer, "Shared Memory Per Block (bytes): %zu\n", dprop_.sharedMemPerBlock));
129     PetscCall(PetscViewerASCIIPrintf(sviewer, "Multiprocessor Clock Rate (KHz): %d\n", dprop_.clockRate));
130     PetscCall(PetscViewerASCIIPrintf(sviewer, "Memory Clock Rate (KHz): %d\n", dprop_.memoryClockRate));
131     PetscCall(PetscViewerASCIIPrintf(sviewer, "Memory Bus Width (bits): %d\n", dprop_.memoryBusWidth));
132     PetscCall(PetscViewerASCIIPrintf(sviewer, "Peak Memory Bandwidth (GB/s): %f\n", 2.0 * dprop_.memoryClockRate * (dprop_.memoryBusWidth / 8) / 1.0e6));
133     PetscCall(PetscViewerASCIIPrintf(sviewer, "Can map host memory: %s\n", dprop_.canMapHostMemory ? "PETSC_TRUE" : "PETSC_FALSE"));
134     PetscCall(PetscViewerASCIIPrintf(sviewer, "Can execute multiple kernels concurrently: %s\n", dprop_.concurrentKernels ? "PETSC_TRUE" : "PETSC_FALSE"));
135     PetscCall(PetscViewerASCIIPopTab(sviewer));
136     PetscCall(PetscViewerRestoreSubViewer(viewer, PETSC_COMM_SELF, &sviewer));
137     PetscCall(PetscViewerFlush(viewer));
138   }
139   PetscFunctionReturn(0);
140 }
141 
142 template <DeviceType T>
143 PetscErrorCode Device<T>::DeviceInternal::getattribute(PetscDeviceAttribute attr, void *value) const noexcept {
144   PetscFunctionBegin;
145   PetscAssert(initialized(), PETSC_COMM_SELF, PETSC_ERR_COR, "Device %d was not initialized", id());
146   switch (attr) {
147   case PETSC_DEVICE_ATTR_SIZE_T_SHARED_MEM_PER_BLOCK: *static_cast<std::size_t *>(value) = prop().sharedMemPerBlock;
148   case PETSC_DEVICE_ATTR_MAX: break;
149   }
150   PetscFunctionReturn(0);
151 }
152 
153 static std::jmp_buf cupmMPIAwareJumpBuffer;
154 static bool         cupmMPIAwareJumpBufferSet;
155 
156 // godspeed to anyone that attempts to call this function
157 void SilenceVariableIsNotNeededAndWillNotBeEmittedWarning_ThisFunctionShouldNeverBeCalled() {
158   PETSCABORT(MPI_COMM_NULL, INT_MAX);
159   if (cupmMPIAwareJumpBufferSet) (void)cupmMPIAwareJumpBuffer;
160 }
161 
162 template <DeviceType T>
163 PETSC_CXX_COMPAT_DEFN(PetscErrorCode Device<T>::DeviceInternal::CUPMAwareMPI_(bool *awareness)) {
164   constexpr int  bufSize           = 2;
165   constexpr int  hbuf[bufSize]     = {1, 0};
166   int           *dbuf              = nullptr;
167   constexpr auto bytes             = bufSize * sizeof(*dbuf);
168   const auto     cupmSignalHandler = [](int signal, void *ptr) -> PetscErrorCode {
169     if ((signal == SIGSEGV) && cupmMPIAwareJumpBufferSet) std::longjmp(cupmMPIAwareJumpBuffer, 1);
170     return PetscSignalHandlerDefault(signal, ptr);
171   };
172 
173   PetscFunctionBegin;
174   *awareness = false;
175   PetscCallCUPM(cupmMalloc(reinterpret_cast<void **>(&dbuf), bytes));
176   PetscCallCUPM(cupmMemcpy(dbuf, hbuf, bytes, cupmMemcpyHostToDevice));
177   PetscCallCUPM(cupmDeviceSynchronize());
178   PetscCall(PetscPushSignalHandler(cupmSignalHandler, nullptr));
179   cupmMPIAwareJumpBufferSet = true;
180   if (!setjmp(cupmMPIAwareJumpBuffer) && !MPI_Allreduce(dbuf, dbuf + 1, 1, MPI_INT, MPI_SUM, PETSC_COMM_SELF)) *awareness = true;
181   cupmMPIAwareJumpBufferSet = false;
182   PetscCall(PetscPopSignalHandler());
183   PetscCallCUPM(cupmFree(dbuf));
184   PetscFunctionReturn(0);
185 }
186 
187 template <DeviceType T>
188 PetscErrorCode Device<T>::finalize_() noexcept {
189   PetscFunctionBegin;
190   if (PetscUnlikely(!initialized_)) PetscFunctionReturn(0);
191   for (auto &&device : devices_) device.reset();
192   defaultDevice_ = PETSC_CUPM_DEVICE_NONE; // disabled by default
193   initialized_   = false;
194   PetscFunctionReturn(0);
195 }
196 
197 template <DeviceType T>
198 PETSC_CXX_COMPAT_DECL(PETSC_CONSTEXPR_14 const char *CUPM_VISIBLE_DEVICES()) {
199   switch (T) {
200   case DeviceType::CUDA: return "CUDA_VISIBLE_DEVICES";
201   case DeviceType::HIP: return "HIP_VISIBLE_DEVICES";
202   }
203   PetscUnreachable();
204   return "PETSC_ERROR_PLIB";
205 }
206 
207 template <DeviceType T>
208 PetscErrorCode Device<T>::initialize(MPI_Comm comm, PetscInt *defaultDeviceId, PetscBool *defaultView, PetscDeviceInitType *defaultInitType) noexcept {
209   auto initId   = std::make_pair(*defaultDeviceId, PETSC_FALSE);
210   auto initView = std::make_pair(*defaultView, PETSC_FALSE);
211   auto initType = std::make_pair(*defaultInitType, PETSC_FALSE);
212   int  ndev     = 0;
213 
214   PetscFunctionBegin;
215   if (initialized_) PetscFunctionReturn(0);
216   initialized_ = true;
217   PetscCall(PetscRegisterFinalize(finalize_));
218   PetscCall(base_type::PetscOptionDeviceAll(comm, initType, initId, initView));
219 
220   if (initType.first == PETSC_DEVICE_INIT_NONE) {
221     initId.first = PETSC_CUPM_DEVICE_NONE;
222   } else if (const auto cerr = cupmGetDeviceCount(&ndev)) {
223     auto PETSC_UNUSED ignored = cupmGetLastError();
224     // we won't be initializing anything anyways
225     initType.first            = PETSC_DEVICE_INIT_NONE;
226     // save the error code for later
227     initId.first              = -static_cast<decltype(initId.first)>(cerr);
228 
229     PetscCheck((initType.first != PETSC_DEVICE_INIT_EAGER) && !initView.first, comm, PETSC_ERR_USER_INPUT, "Cannot eagerly initialize %s, as doing so results in %s error %d (%s) : %s", cupmName(), cupmName(), static_cast<PetscErrorCode>(cerr), cupmGetErrorName(cerr), cupmGetErrorString(cerr));
230   }
231 
232   // check again for init type, since the device count may have changed it
233   if (initType.first == PETSC_DEVICE_INIT_NONE) {
234     // id < 0 (excluding PETSC_DECIDE) indicates an error has occurred during setup
235     if ((initId.first > 0) || (initId.first == PETSC_DECIDE)) initId.first = PETSC_CUPM_DEVICE_NONE;
236     // initType overrides initView
237     initView.first = PETSC_FALSE;
238   } else {
239     PetscCall(PetscDeviceCheckDeviceCount_Internal(ndev));
240     if (initId.first == PETSC_DECIDE) {
241       if (ndev) {
242         PetscMPIInt rank;
243 
244         PetscCallMPI(MPI_Comm_rank(comm, &rank));
245         initId.first = rank % ndev;
246       } else initId.first = 0;
247     }
248     if (initView.first) initType.first = PETSC_DEVICE_INIT_EAGER;
249   }
250 
251   static_assert(std::is_same<PetscMPIInt, decltype(defaultDevice_)>::value, "");
252   // initId.first is PetscInt, _defaultDevice is int
253   PetscCall(PetscMPIIntCast(initId.first, &defaultDevice_));
254   // record the results of the initialization
255   *defaultDeviceId = initId.first;
256   *defaultView     = initView.first;
257   *defaultInitType = initType.first;
258   PetscFunctionReturn(0);
259 }
260 
261 template <DeviceType T>
262 PetscErrorCode Device<T>::init_device_id_(PetscInt *inid) const noexcept {
263   const auto id   = *inid == PETSC_DECIDE ? defaultDevice_ : *inid;
264   const auto cerr = static_cast<cupmError_t>(-defaultDevice_);
265 
266   PetscFunctionBegin;
267   PetscCheck(defaultDevice_ != PETSC_CUPM_DEVICE_NONE, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Trying to retrieve a %s PetscDevice when it has been disabled", cupmName());
268   PetscCheck(defaultDevice_ >= 0, PETSC_COMM_SELF, PETSC_ERR_GPU, "Cannot lazily initialize PetscDevice: %s error %d (%s) : %s", cupmName(), static_cast<PetscErrorCode>(cerr), cupmGetErrorName(cerr), cupmGetErrorString(cerr));
269   PetscAssert(static_cast<decltype(devices_.size())>(id) < devices_.size(), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Only supports %zu number of devices but trying to get device with id %" PetscInt_FMT, devices_.size(), id);
270 
271   if (!devices_[id]) devices_[id] = util::make_unique<DeviceInternal>(id);
272   PetscAssert(id == devices_[id]->id(), PETSC_COMM_SELF, PETSC_ERR_PLIB, "Entry %" PetscInt_FMT " contains device with mismatching id %d", id, devices_[id]->id());
273   PetscCall(devices_[id]->initialize());
274   *inid = id;
275   PetscFunctionReturn(0);
276 }
277 
278 template <DeviceType T>
279 PetscErrorCode Device<T>::configure_device_(PetscDevice device) noexcept {
280   PetscFunctionBegin;
281   PetscCall(devices_[device->deviceId]->configure());
282   PetscFunctionReturn(0);
283 }
284 
285 template <DeviceType T>
286 PetscErrorCode Device<T>::view_device_(PetscDevice device, PetscViewer viewer) noexcept {
287   PetscFunctionBegin;
288   // now this __shouldn't__ reconfigure the device, but there is a petscinfo call to indicate
289   // it is being reconfigured
290   PetscCall(devices_[device->deviceId]->configure());
291   PetscCall(devices_[device->deviceId]->view(viewer));
292   PetscFunctionReturn(0);
293 }
294 
295 template <DeviceType T>
296 PetscErrorCode Device<T>::get_attribute_(PetscInt id, PetscDeviceAttribute attr, void *value) noexcept {
297   PetscFunctionBegin;
298   PetscCall(devices_[id]->getattribute(attr, value));
299   PetscFunctionReturn(0);
300 }
301 
302 // explicitly instantiate the classes
303 #if PetscDefined(HAVE_CUDA)
304 template class Device<DeviceType::CUDA>;
305 #endif
306 #if PetscDefined(HAVE_HIP)
307 template class Device<DeviceType::HIP>;
308 #endif
309 
310 } // namespace cupm
311 
312 } // namespace device
313 
314 } // namespace Petsc
315