xref: /petsc/src/sys/objects/kokkos/kinit.kokkos.cxx (revision 5e81a9049f99b3e299d3dfd50df0d9eed5e5e59b)
1 #include <petsc/private/deviceimpl.h>
2 #include <Kokkos_Core.hpp>
3 
4 PetscBool PetscKokkosInitialized = PETSC_FALSE;
5 
6 PetscErrorCode PetscKokkosFinalize_Private(void)
7 {
8   PetscFunctionBegin;
9   Kokkos::finalize();
10   PetscFunctionReturn(0);
11 }
12 
13 PetscErrorCode PetscKokkosIsInitialized_Private(PetscBool *isInitialized)
14 {
15   PetscFunctionBegin;
16   *isInitialized = Kokkos::is_initialized() ? PETSC_TRUE : PETSC_FALSE;
17   PetscFunctionReturn(0);
18 }
19 
20 /* Initialize Kokkos if not yet */
21 PetscErrorCode PetscKokkosInitializeCheck(void)
22 {
23   PetscFunctionBegin;
24   if (!Kokkos::is_initialized()) {
25     auto args = Kokkos::InitArguments{}; /* use default constructor */
26 
27 #if (defined(KOKKOS_ENABLE_CUDA) && PetscDefined(HAVE_CUDA)) || (defined(KOKKOS_ENABLE_HIP) && PetscDefined(HAVE_HIP)) || (defined(KOKKOS_ENABLE_SYCL) && PetscDefined(HAVE_SYCL))
28     /* Kokkos does not support CUDA and HIP at the same time (but we do :)) */
29     PetscDeviceContext dctx;
30     PetscErrorCode     ierr;
31 
32     ierr = PetscDeviceContextGetCurrentContext(&dctx);CHKERRQ(ierr);
33     ierr = PetscMPIIntCast(dctx->device->deviceId,&args.device_id);CHKERRQ(ierr);
34 #endif
35 
36     args.disable_warnings = !PetscDefined(HAVE_KOKKOS_INIT_WARNINGS);
37 
38     /* To use PetscNumOMPThreads, one has to configure petsc --with-openmp.
39        Otherwise, let's keep the default value (-1) of args.num_threads.
40     */
41 #if defined(KOKKOS_ENABLE_OPENMP) && PetscDefined(HAVE_OPENMP)
42     args.num_threads = PetscNumOMPThreads;
43 #endif
44 
45     Kokkos::initialize(args);
46     PetscBeganKokkos = PETSC_TRUE;
47   }
48   PetscKokkosInitialized = PETSC_TRUE;
49   PetscFunctionReturn(0);
50 }
51