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