xref: /petsc/src/sys/objects/device/impls/sycl/sycldevice.sycl.cxx (revision 5e81a9049f99b3e299d3dfd50df0d9eed5e5e59b)
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     PetscErrorCode ierr;
62     MPI_Comm       comm;
63     PetscMPIInt    rank;
64     PetscBool      iascii;
65 
66     PetscFunctionBegin;
67     if (PetscUnlikely(!devInitialized_)) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_COR,"Device %d being viewed before it was initialized or configured",id_);
68     ierr = PetscObjectTypeCompare(reinterpret_cast<PetscObject>(viewer),PETSCVIEWERASCII,&iascii);CHKERRQ(ierr);
69     ierr = PetscObjectGetComm(reinterpret_cast<PetscObject>(viewer),&comm);CHKERRQ(ierr);
70     if (iascii) {
71       ierr = MPI_Comm_rank(comm,&rank);CHKERRMPI(ierr);
72       ierr = PetscViewerASCIIPushSynchronized(viewer);CHKERRQ(ierr);
73       ierr = PetscViewerASCIISynchronizedPrintf(viewer,"[%d] device: %s\n",rank,syclDevice_.get_info<sycl::info::device::name>().c_str());CHKERRQ(ierr);
74       // flush the assignment information
75       ierr = PetscViewerFlush(viewer);CHKERRQ(ierr);
76       ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
77       ierr = PetscViewerASCIISynchronizedPrintf(viewer,"-> Device vendor: %s\n",syclDevice_.get_info<sycl::info::device::vendor>().c_str());CHKERRQ(ierr);
78       ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
79       ierr = PetscViewerFlush(viewer);CHKERRQ(ierr);
80       ierr = PetscViewerASCIIPopSynchronized(viewer);CHKERRQ(ierr);
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     PetscErrorCode ierr;
99     const int      bufSize = 2;
100     const int      hbuf[bufSize] = {1,0};
101     int            *dbuf = nullptr;
102     bool           awareness = false;
103     const auto     SyclSignalHandler = [](int signal, void *ptr) -> PetscErrorCode {
104       if ((signal == SIGSEGV) && MPISyclAwareJumpBufferSet) std::longjmp(MPISyclAwareJumpBuffer,1);
105       return PetscSignalHandlerDefault(signal,ptr);
106     };
107 
108     PetscFunctionBegin;
109     auto Q = sycl::queue(syclDevice_);
110     dbuf   = sycl::malloc_device<int>(bufSize,Q);
111     Q.memcpy(dbuf,hbuf,sizeof(int)*bufSize).wait();
112     ierr = PetscPushSignalHandler(SyclSignalHandler,nullptr);CHKERRABORT(PETSC_COMM_SELF,ierr);
113     MPISyclAwareJumpBufferSet = true;
114     if (setjmp(MPISyclAwareJumpBuffer)) {
115       // if a segv was triggered in the MPI_Allreduce below, it is very likely due to MPI not being GPU-aware
116       awareness = false;
117       PetscStackPop;
118     } else if (!MPI_Allreduce(dbuf,dbuf+1,1,MPI_INT,MPI_SUM,PETSC_COMM_SELF)) awareness = true;
119     MPISyclAwareJumpBufferSet = false;
120     ierr = PetscPopSignalHandler();CHKERRABORT(PETSC_COMM_SELF,ierr);
121     sycl::free(dbuf,Q);
122     PetscFunctionReturn(awareness);
123   }
124 };
125 
126 PetscErrorCode Device::initialize(MPI_Comm comm, PetscInt *defaultDeviceId, PetscDeviceInitType *defaultInitType) noexcept
127 {
128   PetscInt       initType = *defaultInitType,id = *defaultDeviceId;
129   PetscBool      view = PETSC_FALSE,flg;
130   PetscInt       ngpus;
131   PetscErrorCode ierr;
132 
133   PetscFunctionBegin;
134   if (initialized_) PetscFunctionReturn(0);
135   initialized_ = true;
136   ierr = PetscRegisterFinalize(finalize_);CHKERRQ(ierr);
137 
138   ierr = PetscOptionsBegin(comm,nullptr,"PetscDevice SYCL Options","Sys");CHKERRQ(ierr);
139   ierr = PetscOptionsEList("-device_enable_sycl","How (or whether) to initialize a device","SyclDevice::initialize()",PetscDeviceInitTypes,3,PetscDeviceInitTypes[initType],&initType,nullptr);CHKERRQ(ierr);
140   ierr = 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());CHKERRQ(ierr);
141   ierr = PetscOptionsBool("-device_view_sycl","Display device information and assignments (forces eager initialization)",nullptr,view,&view,&flg);CHKERRQ(ierr);
142   ierr = PetscOptionsEnd();CHKERRQ(ierr);
143 
144   // post-process the options and lay the groundwork for initialization if needs be
145   std::vector<sycl::device> gpu_devices = sycl::device::get_devices(sycl::info::device_type::gpu);
146   ngpus = static_cast<PetscInt>(gpu_devices.size());
147   if (PetscUnlikely(ngpus == 0 && id >= 0)) SETERRQ1(comm,PETSC_ERR_USER_INPUT,"You specified a sycl gpu device with -device_select_sycl %d but there is no GPU", (int)id);
148   if (PetscUnlikely(ngpus > 0 && id >= ngpus)) SETERRQ2(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);
149 
150   if (initType == PETSC_DEVICE_INIT_NONE) id = PETSC_SYCL_DEVICE_NONE; /* user wants to disable all sycl devices */
151   else {
152     ierr = PetscDeviceCheckDeviceCount_Internal(ngpus);CHKERRQ(ierr);
153     if (id == PETSC_DECIDE) { /* petsc will choose a GPU device if any, otherwise a CPU device */
154       if (ngpus) {
155         PetscMPIInt rank;
156         ierr = MPI_Comm_rank(comm,&rank);CHKERRMPI(ierr);
157         id   = rank % ngpus;
158       } else id = PETSC_SYCL_DEVICE_HOST;
159     }
160     view = static_cast<decltype(view)>(view && flg);
161     if (view) initType = PETSC_DEVICE_INIT_EAGER;
162   }
163 
164   if (id == -2) id = PETSC_SYCL_DEVICE_HOST; // user passed in '-device_select_sycl -2'. We transform it into canonical form
165 
166   defaultDevice_ = static_cast<decltype(defaultDevice_)>(id);
167   if (PetscUnlikely(initType == PETSC_DEVICE_INIT_EAGER && id == PETSC_SYCL_DEVICE_NONE)) SETERRQ(comm,PETSC_ERR_USER_INPUT,"Cannot eagerly initialize sycl devices as you disabled them by -device_enable_sycl none");
168 
169   if (initType == PETSC_DEVICE_INIT_EAGER) {
170     devices_[defaultDevice_] = new DeviceInternal(defaultDevice_);
171     ierr = devices_[defaultDevice_]->initialize();CHKERRQ(ierr);
172     if (view) {
173       PetscViewer viewer;
174       ierr = PetscLogInitialize();CHKERRQ(ierr);
175       ierr = PetscViewerASCIIGetStdout(comm,&viewer);CHKERRQ(ierr);
176       ierr = devices_[defaultDevice_]->view(viewer);CHKERRQ(ierr);
177     }
178   }
179 
180   // record the results of the initialization
181   *defaultInitType = static_cast<PetscDeviceInitType>(initType);
182   *defaultDeviceId = id;
183   PetscFunctionReturn(0);
184 }
185 
186 PetscErrorCode Device::finalize_() noexcept
187 {
188   PetscFunctionBegin;
189   if (!initialized_) PetscFunctionReturn(0);
190   for (auto&& devPtr : devices_array_) delete devPtr;
191   defaultDevice_ = PETSC_SYCL_DEVICE_NONE;  // disabled by default
192   initialized_   = false;
193   PetscFunctionReturn(0);
194 }
195 
196 PetscErrorCode Device::getDevice(PetscDevice device, PetscInt id) const noexcept
197 {
198   PetscErrorCode ierr;
199 
200   PetscFunctionBegin;
201   if (PetscUnlikely(defaultDevice_ == PETSC_SYCL_DEVICE_NONE)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Trying to retrieve a SYCL PetscDevice when it has been disabled");
202   if (id == PETSC_DECIDE) id = defaultDevice_;
203   if ((id < PETSC_SYCL_DEVICE_HOST) || (id-PETSC_SYCL_DEVICE_HOST >= PETSC_DEVICE_MAX_DEVICES)) SETERRQ2(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);
204   if (devices_[id]) {
205     if (id != devices_[id]->id()) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Entry %" PetscInt_FMT " contains device with mismatching id %" PetscInt_FMT,id,devices_[id]->id());
206   } else devices_[id] = new DeviceInternal(id);
207   ierr = devices_[id]->initialize();CHKERRQ(ierr);
208   device->deviceId           = devices_[id]->id(); // technically id = devices_[id]->id_ here
209   device->ops->createcontext = create_;
210   device->ops->configure     = this->configureDevice;
211   device->ops->view          = this->viewDevice;
212   PetscFunctionReturn(0);
213 }
214 
215 PetscErrorCode Device::configureDevice(PetscDevice device) noexcept
216 {
217   PetscFunctionBegin;
218   // Nothing for now
219   PetscFunctionReturn(0);
220 }
221 
222 PetscErrorCode Device::viewDevice(PetscDevice device, PetscViewer viewer) noexcept
223 {
224   PetscErrorCode ierr;
225 
226   PetscFunctionBegin;
227   ierr = devices_[device->deviceId]->view(viewer);CHKERRQ(ierr);
228   PetscFunctionReturn(0);
229 }
230 
231 } // namespace SYCL
232 
233 } // namespace Device
234 
235 } // namespace Petsc
236