xref: /petsc/src/sys/objects/device/impls/sycl/sycldevice.sycl.cxx (revision daa037dfd3c3bec8dc8659548d2b20b07c1dc6de)
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   PetscErrorCode ierr;
131 
132   PetscFunctionBegin;
133   if (initialized_) PetscFunctionReturn(0);
134   initialized_ = true;
135   PetscCall(PetscRegisterFinalize(finalize_));
136 
137   ierr = PetscOptionsBegin(comm,nullptr,"PetscDevice SYCL Options","Sys");PetscCall(ierr);
138   PetscCall(PetscOptionsEList("-device_enable_sycl","How (or whether) to initialize a device","SyclDevice::initialize()",PetscDeviceInitTypes,3,PetscDeviceInitTypes[initType],&initType,nullptr));
139   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()));
140   PetscCall(PetscOptionsBool("-device_view_sycl","Display device information and assignments (forces eager initialization)",nullptr,view,&view,&flg));
141   ierr = PetscOptionsEnd();PetscCall(ierr);
142 
143   // post-process the options and lay the groundwork for initialization if needs be
144   std::vector<sycl::device> gpu_devices = sycl::device::get_devices(sycl::info::device_type::gpu);
145   ngpus = static_cast<PetscInt>(gpu_devices.size());
146   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);
147   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);
148 
149   if (initType == PETSC_DEVICE_INIT_NONE) id = PETSC_SYCL_DEVICE_NONE; /* user wants to disable all sycl devices */
150   else {
151     PetscCall(PetscDeviceCheckDeviceCount_Internal(ngpus));
152     if (id == PETSC_DECIDE) { /* petsc will choose a GPU device if any, otherwise a CPU device */
153       if (ngpus) {
154         PetscMPIInt rank;
155         PetscCallMPI(MPI_Comm_rank(comm,&rank));
156         id   = rank % ngpus;
157       } else id = PETSC_SYCL_DEVICE_HOST;
158     }
159     view = static_cast<decltype(view)>(view && flg);
160     if (view) initType = PETSC_DEVICE_INIT_EAGER;
161   }
162 
163   if (id == -2) id = PETSC_SYCL_DEVICE_HOST; // user passed in '-device_select_sycl -2'. We transform it into canonical form
164 
165   defaultDevice_ = static_cast<decltype(defaultDevice_)>(id);
166   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");
167 
168   if (initType == PETSC_DEVICE_INIT_EAGER) {
169     devices_[defaultDevice_] = new DeviceInternal(defaultDevice_);
170     PetscCall(devices_[defaultDevice_]->initialize());
171     if (view) {
172       PetscViewer viewer;
173       PetscCall(PetscLogInitialize());
174       PetscCall(PetscViewerASCIIGetStdout(comm,&viewer));
175       PetscCall(devices_[defaultDevice_]->view(viewer));
176     }
177   }
178 
179   // record the results of the initialization
180   *defaultInitType = static_cast<PetscDeviceInitType>(initType);
181   *defaultDeviceId = id;
182   PetscFunctionReturn(0);
183 }
184 
185 PetscErrorCode Device::finalize_() noexcept
186 {
187   PetscFunctionBegin;
188   if (!initialized_) PetscFunctionReturn(0);
189   for (auto&& devPtr : devices_array_) delete devPtr;
190   defaultDevice_ = PETSC_SYCL_DEVICE_NONE;  // disabled by default
191   initialized_   = false;
192   PetscFunctionReturn(0);
193 }
194 
195 PetscErrorCode Device::getDevice(PetscDevice device, PetscInt id) const noexcept
196 {
197   PetscFunctionBegin;
198   PetscCheckFalse(defaultDevice_ == PETSC_SYCL_DEVICE_NONE,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Trying to retrieve a SYCL PetscDevice when it has been disabled");
199   if (id == PETSC_DECIDE) id = defaultDevice_;
200   PetscCheckFalse((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);
201   if (devices_[id]) {
202     PetscCheckFalse(id != devices_[id]->id(),PETSC_COMM_SELF,PETSC_ERR_PLIB,"Entry %" PetscInt_FMT " contains device with mismatching id %" PetscInt_FMT,id,devices_[id]->id());
203   } else devices_[id] = new DeviceInternal(id);
204   PetscCall(devices_[id]->initialize());
205   device->deviceId           = devices_[id]->id(); // technically id = devices_[id]->id_ here
206   device->ops->createcontext = create_;
207   device->ops->configure     = this->configureDevice;
208   device->ops->view          = this->viewDevice;
209   PetscFunctionReturn(0);
210 }
211 
212 PetscErrorCode Device::configureDevice(PetscDevice device) noexcept
213 {
214   PetscFunctionBegin;
215   // Nothing for now
216   PetscFunctionReturn(0);
217 }
218 
219 PetscErrorCode Device::viewDevice(PetscDevice device, PetscViewer viewer) noexcept
220 {
221   PetscFunctionBegin;
222   PetscCall(devices_[device->deviceId]->view(viewer));
223   PetscFunctionReturn(0);
224 }
225 
226 } // namespace SYCL
227 
228 } // namespace Device
229 
230 } // namespace Petsc
231