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