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 // forces cuda < 5.0 to initialize a context 60 PetscCallCUPM(cupmFree(nullptr)); 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)) { 181 // if a segv was triggered in the MPI_Allreduce below, it is very likely due to MPI not 182 // being GPU-aware 183 184 // control flow up until this point: 185 // 1. CUPMDevice<T>::CUPMDeviceInternal::MPICUPMAware__() 186 // 2. MPI_Allreduce 187 // 3. SIGSEGV 188 // 4. PetscSignalHandler_Private 189 // 5. cupmSignalHandler (lambda function) 190 // 6. here 191 // PetscSignalHandler_Private starts with PetscFunctionBegin and is pushed onto the stack 192 // so we must undo this. This would be most naturally done in cupmSignalHandler, however 193 // the C/C++ standard dictates: 194 // 195 // After invoking longjmp(), non-volatile-qualified local objects should not be accessed if 196 // their values could have changed since the invocation of setjmp(). Their value in this 197 // case is considered indeterminate, and accessing them is undefined behavior. 198 // 199 // so for safety (since we don't know what PetscStackPop may try to read/declare) we do it 200 // outside of the longjmp control flow 201 PetscStackPop; 202 } else if (!MPI_Allreduce(dbuf, dbuf + 1, 1, MPI_INT, MPI_SUM, PETSC_COMM_SELF)) *awareness = true; 203 cupmMPIAwareJumpBufferSet = false; 204 PetscCall(PetscPopSignalHandler()); 205 PetscCallCUPM(cupmFree(dbuf)); 206 PetscFunctionReturn(0); 207 } 208 209 template <DeviceType T> 210 PetscErrorCode Device<T>::finalize_() noexcept { 211 PetscFunctionBegin; 212 if (PetscUnlikely(!initialized_)) PetscFunctionReturn(0); 213 for (auto &&device : devices_) device.reset(); 214 defaultDevice_ = PETSC_CUPM_DEVICE_NONE; // disabled by default 215 initialized_ = false; 216 PetscFunctionReturn(0); 217 } 218 219 template <DeviceType T> 220 PETSC_CXX_COMPAT_DECL(PETSC_CONSTEXPR_14 const char *CUPM_VISIBLE_DEVICES()) { 221 switch (T) { 222 case DeviceType::CUDA: return "CUDA_VISIBLE_DEVICES"; 223 case DeviceType::HIP: return "HIP_VISIBLE_DEVICES"; 224 } 225 PetscUnreachable(); 226 return "PETSC_ERROR_PLIB"; 227 } 228 229 template <DeviceType T> 230 PetscErrorCode Device<T>::initialize(MPI_Comm comm, PetscInt *defaultDeviceId, PetscBool *defaultView, PetscDeviceInitType *defaultInitType) noexcept { 231 auto initId = std::make_pair(*defaultDeviceId, PETSC_FALSE); 232 auto initView = std::make_pair(*defaultView, PETSC_FALSE); 233 auto initType = std::make_pair(*defaultInitType, PETSC_FALSE); 234 int ndev = 0; 235 236 PetscFunctionBegin; 237 if (initialized_) PetscFunctionReturn(0); 238 initialized_ = true; 239 PetscCall(PetscRegisterFinalize(finalize_)); 240 PetscCall(base_type::PetscOptionDeviceAll(comm, initType, initId, initView)); 241 242 if (initType.first == PETSC_DEVICE_INIT_NONE) { 243 initId.first = PETSC_CUPM_DEVICE_NONE; 244 } else if (const auto cerr = cupmGetDeviceCount(&ndev)) { 245 auto PETSC_UNUSED ignored = cupmGetLastError(); 246 // we won't be initializing anything anyways 247 initType.first = PETSC_DEVICE_INIT_NONE; 248 // save the error code for later 249 initId.first = -static_cast<decltype(initId.first)>(cerr); 250 251 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)); 252 } 253 254 // check again for init type, since the device count may have changed it 255 if (initType.first == PETSC_DEVICE_INIT_NONE) { 256 // id < 0 (excluding PETSC_DECIDE) indicates an error has occurred during setup 257 if ((initId.first > 0) || (initId.first == PETSC_DECIDE)) initId.first = PETSC_CUPM_DEVICE_NONE; 258 // initType overrides initView 259 initView.first = PETSC_FALSE; 260 } else { 261 PetscCall(PetscDeviceCheckDeviceCount_Internal(ndev)); 262 if (initId.first == PETSC_DECIDE) { 263 if (ndev) { 264 PetscMPIInt rank; 265 266 PetscCallMPI(MPI_Comm_rank(comm, &rank)); 267 initId.first = rank % ndev; 268 } else initId.first = 0; 269 } 270 if (initView.first) initType.first = PETSC_DEVICE_INIT_EAGER; 271 } 272 273 static_assert(std::is_same<PetscMPIInt, decltype(defaultDevice_)>::value, ""); 274 // initId.first is PetscInt, _defaultDevice is int 275 PetscCall(PetscMPIIntCast(initId.first, &defaultDevice_)); 276 // record the results of the initialization 277 *defaultDeviceId = initId.first; 278 *defaultView = initView.first; 279 *defaultInitType = initType.first; 280 PetscFunctionReturn(0); 281 } 282 283 template <DeviceType T> 284 PetscErrorCode Device<T>::init_device_id_(PetscInt *inid) const noexcept { 285 const auto id = *inid == PETSC_DECIDE ? defaultDevice_ : *inid; 286 const auto cerr = static_cast<cupmError_t>(-defaultDevice_); 287 288 PetscFunctionBegin; 289 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()); 290 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)); 291 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); 292 293 if (!devices_[id]) devices_[id] = util::make_unique<DeviceInternal>(id); 294 PetscAssert(id == devices_[id]->id(), PETSC_COMM_SELF, PETSC_ERR_PLIB, "Entry %" PetscInt_FMT " contains device with mismatching id %d", id, devices_[id]->id()); 295 PetscCall(devices_[id]->initialize()); 296 *inid = id; 297 PetscFunctionReturn(0); 298 } 299 300 template <DeviceType T> 301 PetscErrorCode Device<T>::configure_device_(PetscDevice device) noexcept { 302 PetscFunctionBegin; 303 PetscCall(devices_[device->deviceId]->configure()); 304 PetscFunctionReturn(0); 305 } 306 307 template <DeviceType T> 308 PetscErrorCode Device<T>::view_device_(PetscDevice device, PetscViewer viewer) noexcept { 309 PetscFunctionBegin; 310 // now this __shouldn't__ reconfigure the device, but there is a petscinfo call to indicate 311 // it is being reconfigured 312 PetscCall(devices_[device->deviceId]->configure()); 313 PetscCall(devices_[device->deviceId]->view(viewer)); 314 PetscFunctionReturn(0); 315 } 316 317 template <DeviceType T> 318 PetscErrorCode Device<T>::get_attribute_(PetscInt id, PetscDeviceAttribute attr, void *value) noexcept { 319 PetscFunctionBegin; 320 PetscCall(devices_[id]->getattribute(attr, value)); 321 PetscFunctionReturn(0); 322 } 323 324 // explicitly instantiate the classes 325 #if PetscDefined(HAVE_CUDA) 326 template class Device<DeviceType::CUDA>; 327 #endif 328 #if PetscDefined(HAVE_HIP) 329 template class Device<DeviceType::HIP>; 330 #endif 331 332 } // namespace cupm 333 334 } // namespace device 335 336 } // namespace Petsc 337