xref: /petsc/src/sys/objects/device/impls/sycl/sycldevice.sycl.cxx (revision d2522c19e8fa9bca20aaca277941d9a63e71db6a)
1 #include "../../interface/sycldevice.hpp"
2 #include <csetjmp> // for MPI sycl device awareness
3 #include <csignal> // SIGSEGV
4 #include <vector>
5 #include <CL/sycl.hpp>
6 
7 #if PetscDefined(USE_LOG)
8 PETSC_INTERN PetscErrorCode PetscLogInitialize(void);
9 #else
10 #define PetscLogInitialize() 0
11 #endif
12 
13 namespace Petsc {
14 
15 namespace Device {
16 
17 namespace SYCL {
18 
19 // definition for static
20 std::array<Device::DeviceInternal *, PETSC_DEVICE_MAX_DEVICES> Device::devices_array_ = {};
21 Device::DeviceInternal                                       **Device::devices_       = &Device::devices_array_[1];
22 int                                                            Device::defaultDevice_ = PETSC_SYCL_DEVICE_NONE;
23 bool                                                           Device::initialized_   = false;
24 
25 static std::jmp_buf MPISyclAwareJumpBuffer;
26 static bool         MPISyclAwareJumpBufferSet;
27 
28 // internal "impls" class for SyclDevice. Each instance represents a single sycl device
29 class PETSC_NODISCARD Device::DeviceInternal {
30   const int          id_; // -1 for the host device; 0 and up for gpu devices
31   bool               devInitialized_;
32   const sycl::device syclDevice_;
33 
34 public:
35   // default constructor
36   DeviceInternal(int id) noexcept : id_(id), devInitialized_(false), syclDevice_(chooseSYCLDevice_(id)) { }
37   int  id() const { return id_; }
38   bool initialized() const { return devInitialized_; }
39 
40   PETSC_NODISCARD PetscErrorCode initialize() noexcept {
41     PetscFunctionBegin;
42     if (devInitialized_) PetscFunctionReturn(0);
43     if (syclDevice_.is_gpu() && use_gpu_aware_mpi) {
44       if (!isMPISyclAware_()) {
45         (*PetscErrorPrintf)("PETSc is configured with sycl support, but your MPI is not aware of sycl GPU devices. For better performance, please use a sycl GPU-aware MPI.\n");
46         (*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");
47         PETSCABORT(PETSC_COMM_SELF, PETSC_ERR_LIB);
48       }
49     }
50     devInitialized_ = true;
51     PetscFunctionReturn(0);
52   }
53 
54   PETSC_NODISCARD PetscErrorCode view(PetscViewer viewer) const noexcept {
55     MPI_Comm    comm;
56     PetscMPIInt rank;
57     PetscBool   iascii;
58 
59     PetscFunctionBegin;
60     PetscCheck(devInitialized_, PETSC_COMM_SELF, PETSC_ERR_COR, "Device %d being viewed before it was initialized or configured", id_);
61     PetscCall(PetscObjectTypeCompare(reinterpret_cast<PetscObject>(viewer), PETSCVIEWERASCII, &iascii));
62     PetscCall(PetscObjectGetComm(reinterpret_cast<PetscObject>(viewer), &comm));
63     if (iascii) {
64       PetscViewer sviewer;
65 
66       PetscCallMPI(MPI_Comm_rank(comm, &rank));
67       PetscCall(PetscViewerGetSubViewer(viewer, PETSC_COMM_SELF, &sviewer));
68       PetscCall(PetscViewerASCIIPrintf(sviewer, "[%d] device: %s\n", rank, syclDevice_.get_info<sycl::info::device::name>().c_str()));
69       PetscCall(PetscViewerASCIIPushTab(sviewer));
70       PetscCall(PetscViewerASCIIPrintf(sviewer, "-> Device vendor: %s\n", syclDevice_.get_info<sycl::info::device::vendor>().c_str()));
71       PetscCall(PetscViewerASCIIPopTab(sviewer));
72       PetscCall(PetscViewerFlush(sviewer));
73       PetscCall(PetscViewerRestoreSubViewer(viewer, PETSC_COMM_SELF, &sviewer));
74       PetscCall(PetscViewerFlush(viewer));
75     }
76     PetscFunctionReturn(0);
77   }
78 
79 private:
80   static sycl::device chooseSYCLDevice_(int id) {
81     if (id == PETSC_SYCL_DEVICE_HOST) {
82       return sycl::device(sycl::host_selector());
83     } else {
84       return sycl::device::get_devices(sycl::info::device_type::gpu)[id];
85     }
86   }
87 
88   // Is the underlying MPI aware of sycl (GPU) devices?
89   bool isMPISyclAware_() noexcept {
90     const int  bufSize           = 2;
91     const int  hbuf[bufSize]     = {1, 0};
92     int       *dbuf              = nullptr;
93     bool       awareness         = false;
94     const auto SyclSignalHandler = [](int signal, void *ptr) -> PetscErrorCode {
95       if ((signal == SIGSEGV) && MPISyclAwareJumpBufferSet) std::longjmp(MPISyclAwareJumpBuffer, 1);
96       return PetscSignalHandlerDefault(signal, ptr);
97     };
98 
99     PetscFunctionBegin;
100     auto Q = sycl::queue(syclDevice_);
101     dbuf   = sycl::malloc_device<int>(bufSize, Q);
102     Q.memcpy(dbuf, hbuf, sizeof(int) * bufSize).wait();
103     PetscCallAbort(PETSC_COMM_SELF, PetscPushSignalHandler(SyclSignalHandler, nullptr));
104     MPISyclAwareJumpBufferSet = true;
105     if (setjmp(MPISyclAwareJumpBuffer)) {
106       // if a segv was triggered in the MPI_Allreduce below, it is very likely due to MPI not being GPU-aware
107       awareness = false;
108       PetscStackPop;
109     } else if (!MPI_Allreduce(dbuf, dbuf + 1, 1, MPI_INT, MPI_SUM, PETSC_COMM_SELF)) awareness = true;
110     MPISyclAwareJumpBufferSet = false;
111     PetscCallAbort(PETSC_COMM_SELF, PetscPopSignalHandler());
112     sycl::free(dbuf, Q);
113     PetscFunctionReturn(awareness);
114   }
115 };
116 
117 PetscErrorCode Device::initialize(MPI_Comm comm, PetscInt *defaultDeviceId, PetscDeviceInitType *defaultInitType) noexcept {
118   PetscInt  initType = *defaultInitType, id = *defaultDeviceId;
119   PetscBool view = PETSC_FALSE, flg;
120   PetscInt  ngpus;
121 
122   PetscFunctionBegin;
123   if (initialized_) PetscFunctionReturn(0);
124   initialized_ = true;
125   PetscCall(PetscRegisterFinalize(finalize_));
126 
127   PetscOptionsBegin(comm, nullptr, "PetscDevice SYCL Options", "Sys");
128   PetscCall(PetscOptionsEList("-device_enable_sycl", "How (or whether) to initialize a device", "SyclDevice::initialize()", PetscDeviceInitTypes, 3, PetscDeviceInitTypes[initType], &initType, nullptr));
129   PetscCall(PetscOptionsRangeInt("-device_select_sycl", "Which sycl device to use? Pass -2 for host, PETSC_DECIDE (-1) to let PETSc decide, 0 and up for GPUs", "PetscDeviceCreate", id, &id, nullptr, -2, std::numeric_limits<decltype(ngpus)>::max()));
130   PetscCall(PetscOptionsBool("-device_view_sycl", "Display device information and assignments (forces eager initialization)", nullptr, view, &view, &flg));
131   PetscOptionsEnd();
132 
133   // post-process the options and lay the groundwork for initialization if needs be
134   std::vector<sycl::device> gpu_devices = sycl::device::get_devices(sycl::info::device_type::gpu);
135   ngpus                                 = static_cast<PetscInt>(gpu_devices.size());
136   PetscCheck(ngpus || id < 0, comm, PETSC_ERR_USER_INPUT, "You specified a sycl gpu device with -device_select_sycl %d but there is no GPU", (int)id);
137   PetscCheck(ngpus <= 0 || id < ngpus, comm, PETSC_ERR_USER_INPUT, "You specified a sycl gpu device with -device_select_sycl %d but there are only %d GPU", (int)id, (int)ngpus);
138 
139   if (initType == PETSC_DEVICE_INIT_NONE) id = PETSC_SYCL_DEVICE_NONE; /* user wants to disable all sycl devices */
140   else {
141     PetscCall(PetscDeviceCheckDeviceCount_Internal(ngpus));
142     if (id == PETSC_DECIDE) { /* petsc will choose a GPU device if any, otherwise a CPU device */
143       if (ngpus) {
144         PetscMPIInt rank;
145         PetscCallMPI(MPI_Comm_rank(comm, &rank));
146         id = rank % ngpus;
147       } else id = PETSC_SYCL_DEVICE_HOST;
148     }
149     view = static_cast<decltype(view)>(view && flg);
150     if (view) initType = PETSC_DEVICE_INIT_EAGER;
151   }
152 
153   if (id == -2) id = PETSC_SYCL_DEVICE_HOST; // user passed in '-device_select_sycl -2'. We transform it into canonical form
154 
155   defaultDevice_ = static_cast<decltype(defaultDevice_)>(id);
156   PetscCheck(initType != PETSC_DEVICE_INIT_EAGER || id != PETSC_SYCL_DEVICE_NONE, comm, PETSC_ERR_USER_INPUT, "Cannot eagerly initialize sycl devices as you disabled them by -device_enable_sycl none");
157 
158   if (initType == PETSC_DEVICE_INIT_EAGER) {
159     devices_[defaultDevice_] = new DeviceInternal(defaultDevice_);
160     PetscCall(devices_[defaultDevice_]->initialize());
161     if (view) {
162       PetscViewer viewer;
163       PetscCall(PetscLogInitialize());
164       PetscCall(PetscViewerASCIIGetStdout(comm, &viewer));
165       PetscCall(devices_[defaultDevice_]->view(viewer));
166     }
167   }
168 
169   // record the results of the initialization
170   *defaultInitType = static_cast<PetscDeviceInitType>(initType);
171   *defaultDeviceId = id;
172   PetscFunctionReturn(0);
173 }
174 
175 PetscErrorCode Device::finalize_() noexcept {
176   PetscFunctionBegin;
177   if (!initialized_) PetscFunctionReturn(0);
178   for (auto &&devPtr : devices_array_) delete devPtr;
179   defaultDevice_ = PETSC_SYCL_DEVICE_NONE; // disabled by default
180   initialized_   = false;
181   PetscFunctionReturn(0);
182 }
183 
184 PetscErrorCode Device::getDevice(PetscDevice device, PetscInt id) const noexcept {
185   PetscFunctionBegin;
186   PetscCheck(defaultDevice_ != PETSC_SYCL_DEVICE_NONE, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Trying to retrieve a SYCL PetscDevice when it has been disabled");
187   if (id == PETSC_DECIDE) id = defaultDevice_;
188   PetscCheck(!(id < PETSC_SYCL_DEVICE_HOST) && !(id - PETSC_SYCL_DEVICE_HOST >= PETSC_DEVICE_MAX_DEVICES), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Only supports %zu number of devices but trying to get device with id %" PetscInt_FMT,
189              devices_array_.size(), id);
190   if (devices_[id]) {
191     PetscCheck(id == devices_[id]->id(), PETSC_COMM_SELF, PETSC_ERR_PLIB, "Entry %" PetscInt_FMT " contains device with mismatching id %" PetscInt_FMT, id, devices_[id]->id());
192   } else devices_[id] = new DeviceInternal(id);
193   PetscCall(devices_[id]->initialize());
194   device->deviceId           = devices_[id]->id(); // technically id = devices_[id]->id_ here
195   device->ops->createcontext = create_;
196   device->ops->configure     = this->configureDevice;
197   device->ops->view          = this->viewDevice;
198   PetscFunctionReturn(0);
199 }
200 
201 PetscErrorCode Device::configureDevice(PetscDevice device) noexcept {
202   PetscFunctionBegin;
203   // Nothing for now
204   PetscFunctionReturn(0);
205 }
206 
207 PetscErrorCode Device::viewDevice(PetscDevice device, PetscViewer viewer) noexcept {
208   PetscFunctionBegin;
209   PetscCall(devices_[device->deviceId]->view(viewer));
210   PetscFunctionReturn(0);
211 }
212 
213 } // namespace SYCL
214 
215 } // namespace Device
216 
217 } // namespace Petsc
218