1 #include <petscdevice.h> 2 #include <petsc/private/petscimpl.h> 3 #include <Kokkos_Core.hpp> 4 5 PetscBool PetscKokkosInitialized = PETSC_FALSE; 6 7 PetscErrorCode PetscKokkosFinalize_Private(void) 8 { 9 PetscFunctionBegin; 10 Kokkos::finalize(); 11 PetscFunctionReturn(0); 12 } 13 14 PetscErrorCode PetscKokkosIsInitialized_Private(PetscBool *isInitialized) 15 { 16 PetscFunctionBegin; 17 *isInitialized = Kokkos::is_initialized() ? PETSC_TRUE : PETSC_FALSE; 18 PetscFunctionReturn(0); 19 } 20 21 /* Initialize Kokkos if not yet */ 22 PetscErrorCode PetscKokkosInitializeCheck(void) 23 { 24 #if defined(KOKKOS_ENABLE_CUDA) || defined(KOKKOS_ENABLE_HIP) 25 PetscErrorCode ierr; 26 #endif 27 Kokkos::InitArguments args; 28 int devId = -1; 29 30 PetscFunctionBegin; 31 if (!Kokkos::is_initialized()) { 32 args.num_threads = -1; /* Kokkos default value of each parameter is -1 */ 33 args.num_numa = -1; 34 args.device_id = -1; 35 args.ndevices = -1; 36 args.skip_device = -1; 37 args.disable_warnings = false; 38 #if defined(KOKKOS_ENABLE_CUDA) 39 cudaError_t cerr; 40 41 ierr = PetscCUDAInitializeCheck();CHKERRQ(ierr); 42 cerr = cudaGetDevice(&devId);CHKERRCUDA(cerr); 43 #elif defined(KOKKOS_ENABLE_HIP) /* Kokkos does not support CUDA and HIP at the same time */ 44 hipError_t herr; 45 46 ierr = PetscHIPInitializeCheck();CHKERRQ(ierr); 47 herr = hipGetDevice(&devId);CHKERRHIP(herr); 48 #endif 49 50 /* To use PetscNumOMPThreads, one has to configure petsc --with-openmp. 51 Otherwise, let's keep the default value (-1) of args.num_threads. 52 */ 53 #if defined(KOKKOS_ENABLE_OPENMP) && defined(PETSC_HAVE_OPENMP) 54 args.num_threads = PetscNumOMPThreads; 55 #endif 56 57 args.device_id = devId; 58 Kokkos::initialize(args); 59 PetscBeganKokkos = PETSC_TRUE; 60 } 61 PetscKokkosInitialized = PETSC_TRUE; 62 PetscFunctionReturn(0); 63 } 64