diff --git a/AGENTS.md b/AGENTS.md index 8345fe2..5f6e4c2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,14 +74,15 @@ the studio, and as the starting point of new campaigns. a file of the physics recompiles the kernels of that model at its next run (about 10 s per kernel, `physics/jit.py`; about 1 min more the first time for a compiler and Kokkos). -canoP runs on the host (Kokkos backend OpenMP) or on a GPU (Cuda, with the architecture of the GPU, -e.g. `kokkos_arch_gpu = AMPERE80` for an A100). canoP builds its shared Kokkos (at the first +canoP runs on the host (Kokkos backend OpenMP) or on a GPU (Cuda for NVIDIA, HIP for AMD, with the +architecture of the GPU, e.g. `kokkos_arch_gpu = AMPERE80` for an A100, `AMD_GFX90A` for an MI250X). +canoP builds its shared Kokkos (at the first configuration of a build directory, a few minutes), pykokkos-base and pykokkos (submodule `external/pykokkos`). Each backend has its own environment, CMake options and Slurm lines of the -runs (user only, switched with `kokkos_backend`); the environment gives a python3, from which canoP +runs (user only, switched with `kokkos_backend`, as is the GPU architecture); the environment gives a python3, from which canoP makes its venv `.local/python` (numpy, h5py, pybind11 3.1.0) when it lacks them. -`build_launcher = sbatch` compiles on a compute node (a Slurm job of `build_jobs` cores; Cuda needs -no GPU to compile). On a GPU the kernels of the physics are compiled by the first run on a GPU node +`build_launcher = sbatch` compiles on a compute node (a Slurm job of `build_jobs` cores; Cuda and HIP +need no GPU to compile). On a GPU the kernels of the physics are compiled by the first run on a GPU node (20 to 45 s each), not on a login node. ## Developing canoP studio itself diff --git a/CHANGELOG.md b/CHANGELOG.md index dee015a..cd8d3c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,12 @@ The user-visible changes of canoP, by version (see `CONTRIBUTING.md` for the ver installation, the canoP icon and Claude Code (proxy of the Claude API); `open_studio` of the MCP bridge recognises a Remote-SSH window and points to the canoP icon or the Ports panel of VS Code instead of an ssh tunnel. +- HIP backend for AMD GPUs (e.g. MI250X, MI300A): the shared Kokkos, pykokkos-base and the kernels of + the physics are compiled with hipcc. canoP studio offers HIP in its Kokkos backends, keeps the GPU + architecture per backend, and pre-fills the modules and Slurm constraints of Adastra (CINES) for + OpenMP and HIP. +- canoP studio: GPUs can also be requested with `--gpus-per-node` (Slurm request `gpus-per-node`), as + Adastra requires. - canoP studio in English or in French: a FR/EN switch in the top bar, saved in the settings. New installations start in English; studios set up before keep French. - Tutorial of canoP studio in the documentation: the build, a run of the blast example, and a diff --git a/Readme.md b/Readme.md index dc315ac..42dbd44 100644 --- a/Readme.md +++ b/Readme.md @@ -75,7 +75,7 @@ its build settings. ## Quick start from the command line Dependencies: a C++17 compiler, CMake, MPI, HDF5 and Python 3.11 to 3.14 (numpy and pybind11 3.1.0 -are installed in a venv when missing); the CUDA toolkit for GPUs. +are installed in a venv when missing); the CUDA toolkit or ROCm for GPUs. ```bash git clone --recurse-submodules https://github.com/canoPdev/canoP.git diff --git a/cmake/build_or_find_kalypsso_core.cmake b/cmake/build_or_find_kalypsso_core.cmake index 94fe92b..b8d8836 100644 --- a/cmake/build_or_find_kalypsso_core.cmake +++ b/cmake/build_or_find_kalypsso_core.cmake @@ -38,30 +38,55 @@ if(CANOP_KALYPSSO_CORE_BUILD) GIT_REPOSITORY https://github.com/kalypsso-dev/kalypsso-core.git GIT_TAG main) else() - # Cuda with the shared Kokkos of canoP (cmake/pykokkos.cmake): no relocatable device code, so the - # device functions of kalypsso-core must be in its headers; the patch moves them there. + # Cuda or HIP with the shared Kokkos of canoP (cmake/pykokkos.cmake): no relocatable device code, + # so the device functions of kalypsso-core must be in its headers. The patches move them there: + # a series applied in order, the first for Cuda, the second (on top of it) for HIP too. A series + # applied further than needed is kept (it changes nothing for the other backends). + set(_canop_patches ${PROJECT_SOURCE_DIR}/cmake/patches/kalypsso-core-cuda-device-code-in-headers.patch + ${PROJECT_SOURCE_DIR}/cmake/patches/kalypsso-core-hip-device-code-in-headers.patch) if(KALYPSSO_CORE_KOKKOS_BACKEND STREQUAL "Cuda") - set(CANOP_KALYPSSO_CORE_PATCH - ${PROJECT_SOURCE_DIR}/cmake/patches/kalypsso-core-cuda-device-code-in-headers.patch) + set(_canop_patches_needed 1) + elseif(KALYPSSO_CORE_KOKKOS_BACKEND STREQUAL "HIP") + set(_canop_patches_needed 2) + else() + set(_canop_patches_needed 0) + endif() + if(_canop_patches_needed GREATER 0) find_package(Git REQUIRED) - execute_process( - COMMAND ${GIT_EXECUTABLE} apply --reverse --check ${CANOP_KALYPSSO_CORE_PATCH} - WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/external/kalypsso-core - RESULT_VARIABLE CANOP_KALYPSSO_CORE_PATCHED - OUTPUT_QUIET ERROR_QUIET) - if(NOT CANOP_KALYPSSO_CORE_PATCHED EQUAL 0) + # the number of patches of the series already applied: the last one that can be reverted + set(_canop_patches_applied 0) + list(LENGTH _canop_patches _canop_n) + foreach(_i RANGE ${_canop_n}) + if(_i EQUAL 0) + continue() + endif() + math(EXPR _k "${_canop_n} - ${_i}") + list(GET _canop_patches ${_k} _canop_patch) + execute_process( + COMMAND ${GIT_EXECUTABLE} apply --reverse --check ${_canop_patch} + WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/external/kalypsso-core + RESULT_VARIABLE _canop_result + OUTPUT_QUIET ERROR_QUIET) + if(_canop_result EQUAL 0) + math(EXPR _canop_patches_applied "${_k} + 1") + break() + endif() + endforeach() + while(_canop_patches_applied LESS _canop_patches_needed) + list(GET _canop_patches ${_canop_patches_applied} _canop_patch) execute_process( - COMMAND ${GIT_EXECUTABLE} apply ${CANOP_KALYPSSO_CORE_PATCH} + COMMAND ${GIT_EXECUTABLE} apply ${_canop_patch} WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/external/kalypsso-core - RESULT_VARIABLE CANOP_KALYPSSO_CORE_PATCH_RESULT) - if(NOT CANOP_KALYPSSO_CORE_PATCH_RESULT EQUAL 0) + RESULT_VARIABLE _canop_result) + if(NOT _canop_result EQUAL 0) message( FATAL_ERROR - "[canoP / kalypsso-core] cannot apply ${CANOP_KALYPSSO_CORE_PATCH} to external/kalypsso-core " - "(needed by Cuda with a shared Kokkos): has kalypsso-core changed?") + "[canoP / kalypsso-core] cannot apply ${_canop_patch} to external/kalypsso-core " + "(needed by ${KALYPSSO_CORE_KOKKOS_BACKEND} with a shared Kokkos): has kalypsso-core changed?") endif() - message("[canoP / kalypsso-core] applied ${CANOP_KALYPSSO_CORE_PATCH} (Cuda, shared Kokkos)") - endif() + message("[canoP / kalypsso-core] applied ${_canop_patch} (${KALYPSSO_CORE_KOKKOS_BACKEND}, shared Kokkos)") + math(EXPR _canop_patches_applied "${_canop_patches_applied} + 1") + endwhile() endif() FetchContent_Declare(kalypsso_core_external SYSTEM SOURCE_DIR ${PROJECT_SOURCE_DIR}/external/kalypsso-core) diff --git a/cmake/patches/kalypsso-core-hip-device-code-in-headers.patch b/cmake/patches/kalypsso-core-hip-device-code-in-headers.patch new file mode 100644 index 0000000..dcd971b --- /dev/null +++ b/cmake/patches/kalypsso-core-hip-device-code-in-headers.patch @@ -0,0 +1,354 @@ +kalypsso-core: HIP build with the shared Kokkos of canoP + +Applied on top of kalypsso-core-cuda-device-code-in-headers.patch, which moves the device functions +that kalypsso-core calls across translation units into headers for Cuda without relocatable device +code (RDC). For HIP (hipcc, clang): + +- HIP with the shared Kokkos of canoP has no RDC either (Kokkos_ENABLE_HIP_RELOCATABLE_DEVICE_CODE + is OFF): KALYPSSO_CORE_DEVICE_CODE_IN_HEADERS is defined for it too (kokkos_shared.h); +- the device timer of the profiling regions had no HIP version: HIPAsyncTimer.h is CudaAsyncTimer.h + with the HIP events (same API); +- the operator() of ComputeDataSliceAlongLine are KOKKOS_FUNCTION at their definitions too (clang + refuses a host definition of a host-device declaration, nvcc accepts it); +- the virtual destructors of MeshGhostsExchanger(MultiVar) are no longer defaulted: clang makes a + defaulted one a device function too (its members are Views), which refers to the device vtable + of another translation unit, not linked without RDC. + +Applied by cmake/build_or_find_kalypsso_core.cmake to external/kalypsso-core for a HIP build with an +installed Kokkos, until kalypsso-core has it (base: kalypsso-core a5070cb with the Cuda patch). + +diff --git a/src/kalypsso/core/ComputeDataSliceAlongLine.cpp b/src/kalypsso/core/ComputeDataSliceAlongLine.cpp +index 5b9a44c..1df266b 100644 +--- a/src/kalypsso/core/ComputeDataSliceAlongLine.cpp ++++ b/src/kalypsso/core/ComputeDataSliceAlongLine.cpp +@@ -510,7 +510,7 @@ ComputeDataSliceAlongLine::get_mid_box_end_point(const ConfigMap + // ================================================================================================ + // ================================================================================================ + template +-void ++KOKKOS_FUNCTION void + ComputeDataSliceAlongLine::operator()(const TagMarkCells, + const int32_t & i_global) const + { +@@ -552,7 +552,7 @@ ComputeDataSliceAlongLine::operator()(const TagMarkCells, + // ================================================================================================ + // ================================================================================================ + template +-void ++KOKKOS_FUNCTION void + ComputeDataSliceAlongLine::operator()(const TagWriteCellData, + const int32_t & i_global) const + { +@@ -580,7 +580,7 @@ ComputeDataSliceAlongLine::operator()(const TagWriteCellData, + // ================================================================================================ + // ================================================================================================ + template +-void ++KOKKOS_FUNCTION void + ComputeDataSliceAlongLine::operator()(const TagWriteFaceData, + const int32_t & i_global) const + { +diff --git a/src/kalypsso/core/MeshGhostsExchanger.h b/src/kalypsso/core/MeshGhostsExchanger.h +index d10b913..fc1dbf5 100644 +--- a/src/kalypsso/core/MeshGhostsExchanger.h ++++ b/src/kalypsso/core/MeshGhostsExchanger.h +@@ -112,7 +112,9 @@ public: + // ========================================================================= + // ========================================================================= + //! destructor +- virtual ~MeshGhostsExchanger() = default; ++ // not defaulted: a defaulted destructor would be a device function too with HIP (Views), ++ // referring to the device vtable of another translation unit (no relocatable device code) ++ virtual ~MeshGhostsExchanger() {} + + // ========================================================================= + // ========================================================================= +diff --git a/src/kalypsso/core/MeshGhostsExchangerMultiVar.h b/src/kalypsso/core/MeshGhostsExchangerMultiVar.h +index 5d365e8..782cf95 100644 +--- a/src/kalypsso/core/MeshGhostsExchangerMultiVar.h ++++ b/src/kalypsso/core/MeshGhostsExchangerMultiVar.h +@@ -80,7 +80,8 @@ public: + // ========================================================================= + // ========================================================================= + //! destructor +- ~MeshGhostsExchangerMultiVar() = default; ++ // not defaulted: see ~MeshGhostsExchanger ++ ~MeshGhostsExchangerMultiVar() override {} + + // ========================================================================= + // ========================================================================= +diff --git a/src/kalypsso/core/kokkos_shared.h b/src/kalypsso/core/kokkos_shared.h +index bcc6f07..2d9002c 100644 +--- a/src/kalypsso/core/kokkos_shared.h ++++ b/src/kalypsso/core/kokkos_shared.h +@@ -15,11 +15,12 @@ + #include + #include + +-// Cuda without relocatable device code (shared Kokkos library, e.g. that of pykokkos-base): a device ++// Cuda or HIP without relocatable device code (shared Kokkos library, e.g. that of pykokkos-base): a device + // function called from another translation unit must be defined in it. The classes whose device + // functions are called across translation units (StencilHelper, UserDataRemapperImplBCC) then define + // them in their headers (_impl.h) instead of instantiating them once in their .cpp. +-#if defined(KOKKOS_ENABLE_CUDA) && !defined(KOKKOS_ENABLE_CUDA_RELOCATABLE_DEVICE_CODE) ++#if (defined(KOKKOS_ENABLE_CUDA) && !defined(KOKKOS_ENABLE_CUDA_RELOCATABLE_DEVICE_CODE)) || \ ++ (defined(KOKKOS_ENABLE_HIP) && !defined(KOKKOS_ENABLE_HIP_RELOCATABLE_DEVICE_CODE)) + # define KALYPSSO_CORE_DEVICE_CODE_IN_HEADERS + #endif + +diff --git a/src/kalypsso/utils/monitoring/CMakeLists.txt b/src/kalypsso/utils/monitoring/CMakeLists.txt +index 8d765b4..818390b 100644 +--- a/src/kalypsso/utils/monitoring/CMakeLists.txt ++++ b/src/kalypsso/utils/monitoring/CMakeLists.txt +@@ -1,4 +1,4 @@ +-add_library(kalypsso_monitoring HostTimer.h CudaBlockingTimer.h CudaAsyncTimer.h memory_utils.h ++add_library(kalypsso_monitoring HostTimer.h CudaBlockingTimer.h CudaAsyncTimer.h HIPAsyncTimer.h memory_utils.h + ProfilingManager.h ProfilingManager.cpp) + + target_include_directories( +diff --git a/src/kalypsso/utils/monitoring/HIPAsyncTimer.h b/src/kalypsso/utils/monitoring/HIPAsyncTimer.h +new file mode 100644 +index 0000000..1746681 +--- /dev/null ++++ b/src/kalypsso/utils/monitoring/HIPAsyncTimer.h +@@ -0,0 +1,218 @@ ++// SPDX-FileCopyrightText: 2025 kalypsso-core authors ++// ++// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception ++ ++/** ++ * \file HIPAsyncTimer.h ++ * \brief A simple timer class for HIP based on events. ++ * ++ */ ++#ifndef KALYPSSO_UTILS_MONITORING_HIPASYNCTIMER_H_ ++#define KALYPSSO_UTILS_MONITORING_HIPASYNCTIMER_H_ ++ ++#include ++ ++#include ++ ++#ifndef assertm ++# define assertm(exp, msg) assert(((void)msg, exp)) ++#endif ++ ++namespace kalypsso ++{ ++ ++/** ++ * \brief a simple timer for HIP kernel. ++ * ++ * hipEventSynchronize is called with some delay (asynchronously) to avoid too much synchronization ++ * between CPU and GPU, and allow the CPU to perform useful stuff while the GPU is computing. ++ * ++ * The way to achieve this is to use an array of HIP events (start/stop), and use two indexes one ++ * to write/record events, and the other to read/synchronize then and compute accumulated time. ++ * These read/write indexes are always increasing; as they are stored on 64 bits integer the upper ++ * limit is sufficiently high to be never reached in practice. We use the rest of division by the ++ * size of the event array, to address the array. ++ * ++ */ ++class HIPAsyncTimer ++{ ++protected: ++ class HIPEvent ++ { ++ public: ++ HIPEvent() { hipEventCreate(&m_event); } ++ ++ HIPEvent(const HIPEvent &) = delete; ++ ++ ~HIPEvent() { hipEventDestroy(m_event); } ++ ++ void ++ record() ++ { ++ auto res = hipEventRecord(m_event, 0); ++ assertm(res == hipSuccess, "Recording HIP event failed"); ++ } ++ ++ bool ++ query() const ++ { ++ return hipEventQuery(m_event) == hipSuccess; ++ } ++ ++ void ++ synchronize() const ++ { ++ hipEventSynchronize(m_event); ++ } ++ hipEvent_t ++ event() const ++ { ++ return m_event; ++ } ++ ++ private: ++ hipEvent_t m_event; ++ }; ++ ++ //! total number of pair of start/stop events ++ static constexpr int NUM_EVENTS = 32; ++ using idx_t = uint64_t; ++ ++ HIPEvent startEv[NUM_EVENTS], stopEv[NUM_EVENTS]; ++ idx_t readIdx, writeIdx; ++ double total_time; ++ ++public: ++ // ======================================================= ++ // ======================================================= ++ HIPAsyncTimer() ++ { ++ readIdx = 0; ++ writeIdx = 0; ++ total_time = 0.0; ++ } ++ ++ // ======================================================= ++ // ======================================================= ++ ~HIPAsyncTimer() {} ++ ++ // ======================================================= ++ // ======================================================= ++ /** ++ * record start event and process past events that are completed. ++ */ ++ void ++ start() ++ { ++ [[maybe_unused]] const auto processed_events = process_events(false); ++ ++ startEv[writeIdx % NUM_EVENTS].record(); ++ } ++ ++ // ======================================================= ++ // ======================================================= ++ /** ++ * record stop event. ++ */ ++ void ++ stop() ++ { ++ stopEv[writeIdx % NUM_EVENTS].record(); ++ assertm(writeIdx < std::numeric_limits::max(), "writeIdx is definitely too large"); ++ ++ writeIdx++; ++ } ++ ++ // ======================================================= ++ // ======================================================= ++ /** ++ * reset internal state ++ */ ++ void ++ reset() ++ { ++ readIdx = 0; ++ writeIdx = 0; ++ total_time = 0.0; ++ } ++ ++ // ======================================================= ++ // ======================================================= ++ /** ++ * return elapsed time in seconds (as record in total_time) ++ */ ++ double ++ elapsed() ++ { ++ // flush events to process ++ [[maybe_unused]] const auto processed_events = process_events(true); ++ assertm(readIdx == writeIdx, "Wrong read/write index after processing all events."); ++ return total_time; ++ } ++ ++private: ++ // ======================================================= ++ // ======================================================= ++ /** ++ * Process a pair of start/stop event and accumulate time. ++ * ++ * \param[in] enforce_synchronization is true, CPU is blocked waiting for the stop event to happen ++ * ++ * When stop even is satisfied, total_time is updated, and the read index incremented. ++ */ ++ void ++ process_event(bool enforce_synchronize = true) ++ { ++ ++ float gpuTime; ++ ++ if (enforce_synchronize) ++ stopEv[readIdx % NUM_EVENTS].synchronize(); ++ hipEventElapsedTime( ++ &gpuTime, startEv[readIdx % NUM_EVENTS].event(), stopEv[readIdx % NUM_EVENTS].event()); ++ readIdx++; ++ total_time += 1e-3 * static_cast(gpuTime); ++ ++ } // process_event ++ ++ // ======================================================= ++ // ======================================================= ++ /** ++ * Process pairs of start/stop events to accumulate time. ++ * ++ * \param[in] if flush is true, always call hipEventSynchronize to make sure the stop event is ++ * completed. ++ * ++ * \return the number of events processed, i.e. events for which hipEventQuery was successful. ++ */ ++ int ++ process_events(bool flush = false) ++ { ++ ++ int processed = 0; ++ constexpr bool NO_SYNC = false; ++ ++ // if the event stack is almost full, enforce synchronization to process events ++ // if flush is requested, enforce synchronization ++ while ((writeIdx - readIdx > NUM_EVENTS - 4) or (flush and readIdx < writeIdx)) ++ { ++ process_event(); ++ processed++; ++ } ++ ++ // just query for stop events that are satisfied, and if so process them ++ while (readIdx < writeIdx and stopEv[readIdx % NUM_EVENTS].query() == hipSuccess) ++ { ++ process_event(NO_SYNC); ++ processed++; ++ } ++ ++ return processed; ++ ++ } // process_events ++ ++}; // class HIPAsyncTimer ++ ++} // namespace kalypsso ++ ++#endif // KALYPSSO_UTILS_MONITORING_HIPASYNCTIMER_H_ +diff --git a/src/kalypsso/utils/monitoring/ProfilingManager.h b/src/kalypsso/utils/monitoring/ProfilingManager.h +index 19264ea..971b87d 100644 +--- a/src/kalypsso/utils/monitoring/ProfilingManager.h ++++ b/src/kalypsso/utils/monitoring/ProfilingManager.h +@@ -33,7 +33,7 @@ + #endif + + #ifdef KOKKOS_ENABLE_HIP +-// # include "HIPAsyncTimer.h" ++# include "HIPAsyncTimer.h" + #endif + + #ifdef KALYPSSO_CORE_NVTX_ANNOTATION_ENABLED +@@ -87,7 +87,7 @@ private: + #if defined(KOKKOS_ENABLE_CUDA) + using DeviceTimer = CudaAsyncTimer; + #elif defined(KOKKOS_ENABLE_HIP) +- // using DeviceTimer = HIPAsyncTimer; ++ using DeviceTimer = HIPAsyncTimer; + #else + using DeviceTimer = HostTimer; + #endif diff --git a/cmake/pykokkos.cmake b/cmake/pykokkos.cmake index b4f8859..9941cc0 100644 --- a/cmake/pykokkos.cmake +++ b/cmake/pykokkos.cmake @@ -7,8 +7,9 @@ # * Kokkos (external/kalypsso-core/external/kokkos), shared, built and installed at the configuration # in /_deps/kokkos/install (a few minutes, once): kalypsso-core and canoP find it there, and # pykokkos compiles the kernels with it during the runs. Backend: KALYPSSO_CORE_KOKKOS_BACKEND -# (OpenMP, or Cuda with OpenMP on the host), architecture: the Kokkos_ARCH_=ON given to -# cmake, other Kokkos options: CANOP_KOKKOS_CMAKE_ARGS. +# (OpenMP, or Cuda or HIP with OpenMP on the host), architecture: the Kokkos_ARCH_=ON given +# to cmake, other Kokkos options: CANOP_KOKKOS_CMAKE_ARGS. HIP: the C++ compiler is hipcc (or +# another compiler of HIP code), e.g. -DCMAKE_CXX_COMPILER=hipcc. # * pykokkos-base (external/pykokkos/base, the Python bindings of Kokkos) with this Kokkos and the # pybind11 of canoP, during the build (target pykokkos_base), used from its build directory # /_deps/pykokkos-base. @@ -120,10 +121,13 @@ set(KALYPSSO_CORE_KOKKOS_BUILD CACHE BOOL "Kokkos built by kalypsso-core: never with canoP, which builds its shared Kokkos" FORCE) if(KALYPSSO_CORE_KOKKOS_BACKEND STREQUAL "Cuda") set(_canop_kokkos_args -DKokkos_ENABLE_CUDA=ON -DKokkos_ENABLE_CUDA_CONSTEXPR=ON) +elseif(KALYPSSO_CORE_KOKKOS_BACKEND STREQUAL "HIP") + # the kernels of pykokkos are separate shared libraries: no relocatable device code (the default) + set(_canop_kokkos_args -DKokkos_ENABLE_HIP=ON) elseif(KALYPSSO_CORE_KOKKOS_BACKEND STREQUAL "OpenMP") set(_canop_kokkos_args) else() - message(FATAL_ERROR "[canoP / pykokkos] KALYPSSO_CORE_KOKKOS_BACKEND must be OpenMP or Cuda " + message(FATAL_ERROR "[canoP / pykokkos] KALYPSSO_CORE_KOKKOS_BACKEND must be OpenMP, Cuda or HIP " "(is '${KALYPSSO_CORE_KOKKOS_BACKEND}')") endif() @@ -258,13 +262,13 @@ if(CANOP_OPENMP_ROOT) set(_canop_pykokkos_base_openmp -DOpenMP_ROOT=${CANOP_OPENMP_ROOT}) endif() # with Cuda, each of the 24 files of view bindings of pykokkos-base takes 4.6 to 5.6 GB with nvcc -# (about 3 min): its build has its own number of jobs, so that the jobs of a large build (a compute -# node) do not run out of memory; empty: the jobs of the build of canoP (shared) +# (about 3 min), with HIP also several GB: its build has its own number of jobs, so that the jobs of a +# large build (a compute node) do not run out of memory; empty: the jobs of the build of canoP (shared) set(CANOP_PYKOKKOS_BASE_JOBS "" - CACHE STRING "Parallel jobs of the build of pykokkos-base (empty: 8 with Cuda, those of canoP otherwise)") + CACHE STRING "Parallel jobs of the build of pykokkos-base (empty: 8 on a GPU, those of canoP otherwise)") set(_canop_pykokkos_base_jobs ${CANOP_PYKOKKOS_BASE_JOBS}) -if(NOT _canop_pykokkos_base_jobs AND KALYPSSO_CORE_KOKKOS_BACKEND STREQUAL "Cuda") +if(NOT _canop_pykokkos_base_jobs AND KALYPSSO_CORE_KOKKOS_BACKEND MATCHES "^(Cuda|HIP)$") set(_canop_pykokkos_base_jobs 8) endif() set(_canop_pykokkos_base_build) diff --git a/docs/developer-guide/tests.md b/docs/developer-guide/tests.md index 4a4609e..c979c66 100644 --- a/docs/developer-guide/tests.md +++ b/docs/developer-guide/tests.md @@ -36,7 +36,7 @@ the physics compiled by pykokkos are kept too (49 kernels, about 4 minutes to co few minutes, about 15 without these caches. A failed test is reported as an annotation of the run, and the logs and input files of its runs of canoP are kept for 7 days as an artifact of the run (`logs`). -The GitHub runners have no GPU: the Cuda build and the GPU runs are not tested there. +The GitHub runners have no GPU: the Cuda and HIP builds and the GPU runs are not tested there. ## Code quality diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md index 0cedd46..821f9eb 100644 --- a/docs/getting-started/installation.md +++ b/docs/getting-started/installation.md @@ -10,7 +10,7 @@ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception - a C++17 compiler, CMake, MPI and HDF5 (parallel); - Python 3.11 to 3.14 with numpy and pybind11 3.1.0 (h5py for the tools and the tests); -- for GPUs: the CUDA toolkit. +- for GPUs: the CUDA toolkit (NVIDIA) or ROCm (AMD). kalypsso-core (mesh, AMR, I/O), Kokkos, p4est and pykokkos come as git submodules and are built with canoP. @@ -107,6 +107,41 @@ The build needs no GPU. The kernels of the physics are compiled by the first run Building the view bindings of pykokkos-base with nvcc needs about 5 GB of memory per file: they are built with 8 jobs (`-DCANOP_PYKOKKOS_BASE_JOBS=`) whatever the parallelism of the build. +### GPUs (HIP) + +For AMD GPUs, Kokkos is built with HIP (and OpenMP and Serial for the host), with `hipcc` of ROCm as +C++ compiler and the architecture of the GPU (`AMD_GFX90A` for an MI250X, `AMD_GFX942_APU` for an +MI300A): + +```bash +cmake -B _build_hip -S . \ + -DCANOP_KALYPSSO_CORE_BUILD=ON \ + -DKALYPSSO_CORE_KOKKOS_BACKEND=HIP \ + -DKALYPSSO_CORE_BUILD_P4EST=ON \ + -DKALYPSSO_CORE_BUILD_SPDLOG=ON \ + -DCMAKE_CXX_COMPILER=hipcc \ + -DKokkos_ARCH_AMD_GFX90A=ON +``` + +As with Cuda, the build needs no GPU, the kernels of the physics are compiled with `hipcc` by the +first run on a GPU node (about 15 to 30 s per kernel on an MI250X), and pykokkos-base is built with +8 jobs. + +canoP gives the MPI library buffers in GPU memory. On a Cray system (e.g. Adastra), link the GPU +support of cray-mpich and turn it on for the runs: + +```bash +module load GCC-GPU-6.0.0 # Adastra: gcc, cray-mpich, ROCm, MI250X (gfx90a) +module load cray-hdf5-parallel cmake cray-python +export CC=gcc +export LDFLAGS="$PE_MPICH_GTL_DIR_amd_gfx90a $PE_MPICH_GTL_LIBS_amd_gfx90a" +export MPICH_GPU_SUPPORT_ENABLED=1 +``` + +On Adastra a job names no partition: the kind of node is a constraint (`--constraint=GENOA` for the +CPUs, `MI250` or `MI300` for the GPUs) and the GPUs are requested per node (`--gpus-per-node`). +canoP studio pre-fills these environments and Slurm lines on Adastra. + ### Options | Option | Effect | diff --git a/docs/physics-guide/kernels.md b/docs/physics-guide/kernels.md index 6db1619..6bc794a 100644 --- a/docs/physics-guide/kernels.md +++ b/docs/physics-guide/kernels.md @@ -25,7 +25,8 @@ kernels. `physics/jit.py` configures CMake once per compiler and options, uses a and calls the compiler directly: about 10 s per kernel on CPUs, plus about one minute the first time. Each compilation prints `pykokkos: / compiled` in the log. -On GPUs the kernels are compiled by nvcc during the first run on a GPU node (about 20 to 45 s each). +On GPUs the kernels are compiled by nvcc (Cuda) or hipcc (HIP) during the first run on a GPU node +(about 20 to 45 s each with nvcc). ## Errors diff --git a/docs/physics-guide/overview.md b/docs/physics-guide/overview.md index d11863c..890eadd 100644 --- a/docs/physics-guide/overview.md +++ b/docs/physics-guide/overview.md @@ -39,7 +39,7 @@ of canoP, host or GPU, indexed `[octant][variable][cell]` with `cell = i + n (j The kernels are the loops of `loops.py`: conversion to primitive variables, time step, initial condition, boundary (ghost) cells, fluxes, sources, relaxations, refinement criterion, output fields. Each loop calls the functions of `model.py` and of the files of the options. pykokkos translates a -kernel to C++ and compiles it for the backend of canoP (OpenMP or CUDA) at its first use, see +kernel to C++ and compiles it for the backend of canoP (OpenMP, CUDA or HIP) at its first use, see {doc}`kernels`. ## Variables of a model diff --git a/docs/tutorial/build.md b/docs/tutorial/build.md index 069b692..61aec8e 100644 --- a/docs/tutorial/build.md +++ b/docs/tutorial/build.md @@ -28,20 +28,20 @@ model (`onephase`, `twophase5eq`, `twophase7eq`) is not chosen here but in the i (`simulation.model`): the physics is written in Python and compiled at run time, so a new model, initial condition or flux needs no new build of canoP. -**Kokkos backend**: OpenMP for the CPUs, Cuda for NVIDIA GPUs. **CPU architecture** (and, for Cuda, -the architecture of the GPU of the runs, e.g. `AMPERE80` for an A100) is passed to Kokkos; *none* -leaves the choice to the compiler. +**Kokkos backend**: OpenMP for the CPUs, Cuda for NVIDIA GPUs, HIP for AMD GPUs. **CPU +architecture** (and, for Cuda and HIP, the architecture of the GPU of the runs, e.g. `AMPERE80` for +an A100, `AMD_GFX90A` for an MI250X) is passed to Kokkos; *none* leaves the choice to the compiler. **Environment (modules…)** are the shell lines run before the build and before each run: they load a C++17 compiler, CMake, MPI, HDF5 and a Python 3.11 or later. **CMake options** are added to the -configuration. Both, and the Slurm options of the runs, belong to the backend: switching from -OpenMP to Cuda shows those of Cuda, and back. The studio sets the backend and architectures of Kokkos +configuration. Both, the Slurm options of the runs and the GPU architecture belong to the backend: +switching from OpenMP to Cuda shows those of Cuda, and back. The studio sets the backend and architectures of Kokkos itself and removes them from the CMake options. **Build on**: *this node* runs the build on the node of the studio (the login node); *a compute node* submits a Slurm job of one task with **Build jobs** cores, with the **Slurm options of the build**. -A Cuda build needs no GPU. On a shared login node, prefer the compute node. +A Cuda or HIP build needs no GPU. On a shared login node, prefer the compute node. **Configure** runs CMake only; **Build** configures when needed and compiles; **Empty the build directory** deletes the build of this variant (CMake configuration included). **Executable** shows diff --git a/physics/common.py b/physics/common.py index 2de8353..b196ba1 100644 --- a/physics/common.py +++ b/physics/common.py @@ -186,7 +186,7 @@ def option_path(model, category, name): def memory_space(): - """Return the memory space of the arrays of canoP: pk.HostSpace, or pk.CudaSpace on a GPU. + """Return the memory space of the arrays of canoP: pk.HostSpace, or pk.CudaSpace (pk.HIPSpace) on a GPU. pykokkos uses the views of this space in the kernels as they are (no copy). """ diff --git a/physics/jit.py b/physics/jit.py index 261bbc9..7406066 100644 --- a/physics/jit.py +++ b/physics/jit.py @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: 2026 canoP authors # # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -"""Faster compilation and launch of the pykokkos kernels (OpenMP, Serial, Cuda). +"""Faster compilation and launch of the pykokkos kernels (OpenMP, Serial, Cuda, HIP). pykokkos builds each kernel as a CMake project: configure, build, install. On a shared file system (GPFS) most of this time is spent reading files, not compiling. Measured for one kernel on a GPFS @@ -12,8 +12,13 @@ ``/jit//``): its compile and link lines are kept, with a precompiled header of the headers that every kernel includes first. Each kernel is then compiled by a direct call of the compiler with this header (about 10 s). Any failure falls back to the CMake build of pykokkos; -``CANOP_PYKOKKOS_CMAKE=1`` always uses it. With Cuda (``nvcc_wrapper``) there is no precompiled -header: the compiler is called directly, without the configure and install steps of each kernel. +``CANOP_PYKOKKOS_CMAKE=1`` always uses it. With Cuda (``nvcc_wrapper``) and HIP there is no +precompiled header: the compiler is called directly, without the configure and install steps of each +kernel. + +With HIP, pykokkos would compile the kernels with g++ when it is given the Kokkos to use +(``PK_KOKKOS_LIB_PATH``): here they are compiled with the compiler of that Kokkos (e.g. hipcc), read +in its CMake configuration. pykokkos reads the compute capability of the GPU with cupy, although CMake does not use it. Here it is that of the Kokkos install (``KOKKOS_ARCH_AMPERE80``: 80), without cupy and without a GPU, so @@ -53,7 +58,8 @@ from pathlib import Path HOST_SPACES = ("OpenMP", "Serial", "Threads") # compiled with a precompiled header -DIRECT_SPACES = HOST_SPACES + ("Cuda",) # compiled without CMake for each kernel +HIP_SPACES = ("Experimental::HIP", "HIP") # PK_EXEC_SPACE of HIP (pykokkos: Experimental::HIP) +DIRECT_SPACES = HOST_SPACES + ("Cuda",) + HIP_SPACES # compiled without CMake for each kernel HEADER = "kernels.hpp" # the precompiled header: HEADER.gch next to it NVIDIA_ARCHS = ("KEPLER", "MAXWELL", "PASCAL", "VOLTA", "TURING", "AMPERE", "ADA", "HOPPER", "BLACKWELL") @@ -213,8 +219,8 @@ def translation_error_str(self): _IDENTIFIER = re.compile(r"[A-Za-z_]\w*") _CPP_WORDS = {"double", "float", "int", "int32_t", "int64_t", "uint32_t", "bool", "auto", "const", "return", "if", "else", "for", "while", "void", "this", "true", "false", "Kokkos", "View", "LayoutRight", "LayoutLeft", - "HostSpace", "CudaSpace", "Experimental", "DefaultViewHooks", "KOKKOS_FUNCTION", "static_cast", - "pk", "math", "ExecSpace"} + "HostSpace", "CudaSpace", "HIPSpace", "Experimental", "DefaultViewHooks", "KOKKOS_FUNCTION", + "static_cast", "pk", "math", "ExecSpace"} class _CompileError(Exception): @@ -443,6 +449,35 @@ def _with_python(cmake_args): if _arg(cmake_args, name) is None] +def _kokkos_compiler(): + """Return the C++ compiler that the Kokkos of PK_KOKKOS_LIB_PATH was built with, or None. + + It is ``Kokkos_CXX_COMPILER`` in ``/cmake/Kokkos/KokkosConfigCommon.cmake``. + """ + lib = os.environ.get("PK_KOKKOS_LIB_PATH") + if not lib: + return None + for path in Path(lib).glob("cmake/Kokkos/KokkosConfigCommon.cmake"): + m = re.search(r'^set\(Kokkos_CXX_COMPILER\s+"([^"]+)"\)', path.read_text(), re.M | re.I) + if m: + return m.group(1) + return None + + +def _with_compiler(cmake_args): + """Return the CMake arguments with the compiler of the Kokkos install for HIP. + + pykokkos gives g++ for every space but Cuda when PK_KOKKOS_LIB_PATH is set; HIP code needs the + compiler Kokkos was built with (hipcc, amdclang++ or a Cray wrapper). + """ + if _arg(cmake_args, "PK_EXEC_SPACE") not in HIP_SPACES: + return list(cmake_args) + compiler = _kokkos_compiler() + if not compiler: + return list(cmake_args) + return [a for a in cmake_args if not a.startswith("-DCMAKE_CXX_COMPILER=")] + ["-DCMAKE_CXX_COMPILER=" + compiler] + + def _kernel_name(output_dir): """Return / from /sources//_/..., else the directory.""" parts = Path(output_dir).parts @@ -464,7 +499,7 @@ def _run(cmd, cwd=None): def _invoke_cmake(self, output_dir, cmake_args, module_name): """Build the module of a kernel in output_dir (replaces CppSetup.invoke_cmake).""" output_dir = Path(output_dir) - cmake_args = _with_python(cmake_args) + cmake_args = _with_compiler(_with_python(cmake_args)) name = _kernel_name(output_dir) start = time.time() if _arg(cmake_args, "PK_EXEC_SPACE") not in HOST_SPACES: diff --git a/src/python/PythonInterpreter.cpp b/src/python/PythonInterpreter.cpp index 6287b7d..095cc58 100644 --- a/src/python/PythonInterpreter.cpp +++ b/src/python/PythonInterpreter.cpp @@ -103,7 +103,7 @@ PYBIND11_EMBEDDED_MODULE(canop_cpp, m) m.def("get_string", [](std::string const & s, std::string const & k, std::string const & d) { return settings().getString(s, k, d); }); m.def("get_bool", [](std::string const & s, std::string const & k, bool d) { return settings().getBool(s, k, d); }); - m.def("memory_space", &memory_space_name, "memory space of the arrays given to the physics (HostSpace, CudaSpace)"); + m.def("memory_space", &memory_space_name, "memory space of the arrays given to the physics (HostSpace, CudaSpace, HIPSpace)"); m.def("device_copy", &device_copy, "copy of a numpy array in the memory of the arrays of canoP"); } diff --git a/tools/canop_core.py b/tools/canop_core.py index 3927626..dcad412 100644 --- a/tools/canop_core.py +++ b/tools/canop_core.py @@ -15,6 +15,7 @@ import shlex import shutil import signal +import socket import subprocess import sys import time @@ -32,22 +33,41 @@ # the build: on this node (direct), or as a Slurm job on a compute node (sbatch) BUILD_LAUNCHERS = ["direct", "sbatch"] GPU_BACKENDS = ("Cuda", "HIP", "SYCL") -# backends of the shared Kokkos that canoP builds with pykokkos-base (Cuda uses OpenMP on the host) -PYKOKKOS_BACKENDS = ("OpenMP", "Cuda") -GPU_REQUESTS = ("gpus-per-task", "gres") # Slurm: --gpus-per-task=G, or --gres=gpu:G (per node) +# backends of the shared Kokkos that canoP builds with pykokkos-base (Cuda and HIP use OpenMP on the host) +PYKOKKOS_BACKENDS = ("OpenMP", "Cuda", "HIP") +# Slurm: --gpus-per-task=G, or per node --gres=gpu:G or --gpus-per-node=G (e.g. Adastra) +GPU_REQUESTS = ("gpus-per-task", "gres", "gpus-per-node") # -------------------------------------------------------------------------- # pre-filled values of the settings (all editable; the code depends on none of them). The Slurm # partitions are found with sinfo (prefill_slurm). The modules and the GPU architecture cannot be -# detected: with a module system, those of the Ruche cluster (mesocentre Paris-Saclay) are -# pre-filled, otherwise comments. +# detected: on Adastra (CINES, found by the name of the host) its modules; with another module +# system, those of the Ruche cluster (mesocentre Paris-Saclay); otherwise comments. # -------------------------------------------------------------------------- _MODULES = bool(os.environ.get("LMOD_CMD") or os.environ.get("MODULESHOME")) +_ADASTRA = socket.getfqdn().endswith(".adastra.cines.fr") +# the whole environment of a backend, when it is not derived from that of another one (default_profile) +PREFILL_ENVS = {} # shell lines run before cmake and before the solver (environment of the OpenMP backend): the # compilers, CMake, MPI, HDF5 and a python3 >= 3.11 (the first in the PATH, given to cmake; canoP makes # its venv /.local/python from it when it lacks numpy or pybind11 3.1.0: Readme.md) -if _MODULES: +if _ADASTRA: + # the CINES environments: GCC-CPU (genoa nodes) for OpenMP; GCC-GPU (MI250X nodes: trento CPU, + # gfx90a, ROCm) for HIP, with hipcc for C++ (Settings.compiler_args) and the GPU support of + # cray-mpich (its GTL library, linked by LDFLAGS; MPICH_GPU_SUPPORT_ENABLED for the runs): canoP + # gives device buffers to MPI + _ADASTRA_COMMON = "module load cray-hdf5-parallel/1.14.3.7 cmake/3.27.9 cray-python/3.11.7" + PREFILL_ENVS = { + "OpenMP": ["module purge", "module load GCC-CPU-6.0.0", _ADASTRA_COMMON, "export CC=cc CXX=CC"], + "HIP": ["module purge", "module load GCC-GPU-6.0.0", _ADASTRA_COMMON, "export CC=gcc", + 'export LDFLAGS="$PE_MPICH_GTL_DIR_amd_gfx90a $PE_MPICH_GTL_LIBS_amd_gfx90a"', + "export MPICH_GPU_SUPPORT_ENABLED=1"], + } + PREFILL_ENV_LINES = PREFILL_ENVS["OpenMP"] + PREFILL_GPU_LINES = {"Cuda": ["# no NVIDIA GPU on Adastra"]} + PREFILL_ARCH_GPUS = {"HIP": "AMD_GFX90A"} # MI250X (partition mi250); AMD_GFX942_APU: MI300A (mi300) +elif _MODULES: # gcc 15 has no cc: CC=gcc, or CMake takes /usr/bin/cc for the C code (p4est) PREFILL_ENV_LINES = [ "module load gcc/15.1.0/gcc-15.1.0 cmake/3.31.9/gcc-15.1.0 openmpi/4.1.8/gcc-15.1.0-cuda " @@ -55,13 +75,19 @@ "export CC=gcc CXX=g++", ] # the CUDA toolkit of the Cuda backend: CUDA 13 accepts gcc 15 - PREFILL_GPU_LINES = ["module load cuda/13.0.2/none-none"] - PREFILL_ARCH_GPU = "AMPERE80" # A100 (the GPUs of gpua100) + PREFILL_GPU_LINES = {"Cuda": ["module load cuda/13.0.2/none-none"], + "HIP": ["# the ROCm toolkit (hipcc) of the HIP backend, e.g. module load rocm"]} + PREFILL_ARCH_GPUS = {"Cuda": "AMPERE80"} # A100 (the GPUs of gpua100) else: PREFILL_ENV_LINES = ["# compilers, CMake, MPI, HDF5 and python3 (>= 3.11) of the PATH; export CC=gcc CXX=g++ " "to choose other compilers"] - PREFILL_GPU_LINES = ["# the CUDA toolkit (nvcc) of the Cuda backend, e.g. module load cuda"] - PREFILL_ARCH_GPU = "" + PREFILL_GPU_LINES = {"Cuda": ["# the CUDA toolkit (nvcc) of the Cuda backend, e.g. module load cuda"], + "HIP": ["# the ROCm toolkit (hipcc) of the HIP backend, e.g. module load rocm"]} + PREFILL_ARCH_GPUS = {} +# the GPU architecture pre-filled for each GPU backend ("" for none) +PREFILL_ARCH_GPU = PREFILL_ARCH_GPUS.get("Cuda", "") +# every pre-filled GPU line, removed from the environment of a backend made from that of another one +_ALL_GPU_LINES = {line for lines in PREFILL_GPU_LINES.values() for line in lines} DEFAULT_ENV = "\n".join(PREFILL_ENV_LINES) DEFAULT_CMAKE = "\n".join( [ @@ -73,6 +99,8 @@ ) # fields with one value per backend, swapped when the backend changes (Settings.switch_backend) BACKEND_FIELDS = ("env_setup", "cmake_options", "slurm_options") +# also kept per backend, but editable by the agents too: the GPU architecture (Cuda and HIP differ) +PROFILE_FIELDS = BACKEND_FIELDS + ("kokkos_arch_gpu",) # CMake options that the studio sets from the settings (the backend and architectures of Kokkos; canoP # never uses the Kokkos built by kalypsso-core): removed from the CMake options of the panel MANAGED_CMAKE_OPTIONS = ("-DKALYPSSO_CORE_KOKKOS_BACKEND=", "-DKokkos_ARCH_", "-DKALYPSSO_CORE_KOKKOS_BUILD=") @@ -107,7 +135,10 @@ def clean_cmake_options(text): _GPU_NAMES = {"KEPLER": ("k80", "k40", "k20"), "MAXWELL": ("m40", "m60"), "PASCAL": ("p100", "p40"), "VOLTA": ("v100",), "TURING": ("t4", "rtx"), "AMPERE80": ("a100",), "AMPERE86": ("a40", "a10", "a6000"), "AMPERE87": ("orin",), "ADA": ("l40", "l4"), "HOPPER": ("h100", "h200", "gh200"), - "BLACKWELL": ("b200", "gb200", "b100", "b300")} + "BLACKWELL": ("b200", "gb200", "b100", "b300"), + "AMD_GFX90A": ("mi250", "mi210"), "VEGA90A": ("mi250", "mi210"), "AMD_GFX908": ("mi100",), + "VEGA908": ("mi100",), "AMD_GFX942_APU": ("mi300a", "mi300"), "AMD_GFX942": ("mi300", "mi325"), + "AMD_GFX940": ("mi300",), "AMD_GFX1100": ("w7900", "7900"), "AMD_GFX1030": ("w6800", "6800")} def _seconds(limit): @@ -129,7 +160,19 @@ def prefill_slurm(kind, arch_gpu=PREFILL_ARCH_GPU): tells the GPU of arch_gpu (a100 for AMPERE80), else the first one with GPUs. When none fits, the partition line is a commented placeholder (omitted without Slurm, except for 'gpu'). The time is one hour, or the time limit of the partition when it is shorter. + + On Adastra, where a job may not name a partition, the kind of node is a constraint: GENOA for + the CPUs, MI250 or MI300 (AMD_GFX942*) for the GPUs. """ + if _ADASTRA: + if kind == "gpu": + node = "MI300" if arch_gpu.startswith("AMD_GFX94") else "MI250" + else: + node = "GENOA" + lines = ["#SBATCH --constraint=%s" % node, "#SBATCH --time=01:00:00"] + if kind != "build": + lines.append("#SBATCH --nodes=1") + return "\n".join(lines) parts = slurm_partitions_info() cpu = [p for p in parts if not p["gpus"]] if kind == "gpu": @@ -149,18 +192,27 @@ def prefill_slurm(kind, arch_gpu=PREFILL_ARCH_GPU): return "\n".join(lines) -def default_profile(backend, env_setup=DEFAULT_ENV, cmake_options=DEFAULT_CMAKE, arch_gpu=PREFILL_ARCH_GPU): +def default_profile(backend, env_setup=DEFAULT_ENV, cmake_options=DEFAULT_CMAKE, arch_gpu=None): """Pre-filled fields of a backend, {field: value}, derived from those of another backend. - The environment gets (GPU) or loses (CPU) the lines of the CUDA toolkit, the CMake options stay - the same, and the Slurm lines are those of a CPU or GPU partition. + The environment loses the pre-filled lines of the GPU toolkits and gets those of the backend (the + CUDA toolkit for Cuda, ROCm for HIP); a pre-filled environment not changed becomes that + pre-filled for the backend when there is one (PREFILL_ENVS). The CMake options stay the same, + the GPU architecture is arch_gpu (default: the pre-filled one of the backend), and the Slurm + lines are those of a CPU or GPU partition (that of the architecture). """ gpu = backend in GPU_BACKENDS - lines = [line for line in env_setup.splitlines() if line not in PREFILL_GPU_LINES] - if gpu: - lines += PREFILL_GPU_LINES - return {"env_setup": "\n".join(lines), "cmake_options": clean_cmake_options(cmake_options), - "slurm_options": prefill_slurm("gpu" if gpu else "cpu", arch_gpu)} + if arch_gpu is None: + arch_gpu = PREFILL_ARCH_GPUS.get(backend, "") + if backend in PREFILL_ENVS and env_setup in ["\n".join(v) for v in PREFILL_ENVS.values()]: + # a pre-filled environment, not changed: that pre-filled for the backend + env = "\n".join(PREFILL_ENVS[backend]) + else: + lines = [line for line in env_setup.splitlines() if line not in _ALL_GPU_LINES] + env = "\n".join(lines + PREFILL_GPU_LINES.get(backend, [])) + return {"env_setup": env, "cmake_options": clean_cmake_options(cmake_options), + "slurm_options": prefill_slurm("gpu" if gpu else "cpu", arch_gpu), + "kokkos_arch_gpu": arch_gpu if gpu else ""} # the python of the environment, its shared library and its headers, for cmake (Settings.python_args; @@ -695,9 +747,9 @@ class Settings: kokkos_backend: str = "OpenMP" kokkos_arch_host: str = "" # Kokkos_ARCH_, empty: none (compiler default) kokkos_arch_gpu: str = PREFILL_ARCH_GPU # GPU backends only (required to build) - backend_profiles: dict = field(default_factory=lambda: {"Cuda": default_profile("Cuda")}) + backend_profiles: dict = field(default_factory=lambda: {b: default_profile(b) for b in PYKOKKOS_BACKENDS[1:]}) gpus_per_task: int = 1 # GPU backends: GPUs per MPI process (gres: per node) - gpu_request: str = GPU_REQUESTS[0] + gpu_request: str = "gpus-per-node" if _ADASTRA else GPU_REQUESTS[0] # limits of the campaigns driven by an agent (MCP tools), editable by the user only camp_max_submit: int = 20 # runs submitted at once camp_max_runs: int = 30 # runs in a campaign @@ -721,12 +773,15 @@ def __post_init__(self): self.dim = DIMS[0] if self.build_launcher not in BUILD_LAUNCHERS: self.build_launcher = BUILD_LAUNCHERS[0] - # the shared Kokkos built by canoP for pykokkos: OpenMP or Cuda + # the shared Kokkos built by canoP for pykokkos: OpenMP, Cuda or HIP if self.kokkos_backend not in PYKOKKOS_BACKENDS: self.kokkos_backend = PYKOKKOS_BACKENDS[0] profiles = self.backend_profiles if isinstance(self.backend_profiles, dict) else {} + # profiles saved before the GPU architecture was kept per backend: that of the settings was the + # one of Cuda (the only GPU backend then) self.backend_profiles = { - b: {k: str(p.get(k, "")) for k in BACKEND_FIELDS} + b: {k: str(p.get(k, self.kokkos_arch_gpu if (k == "kokkos_arch_gpu" and b == "Cuda") else "")) + for k in PROFILE_FIELDS} for b, p in profiles.items() if b in PYKOKKOS_BACKENDS and isinstance(p, dict) } @@ -752,9 +807,10 @@ def from_dict(cls, data): def profile(b): gpu = b in GPU_BACKENDS - p = default_profile(b, env, settings.cmake_options, settings.kokkos_arch_gpu) - if gpu: - p["env_setup"] = env.rstrip("\n") + "\n" + (gpu_lines or "\n".join(PREFILL_GPU_LINES)) + arch = settings.kokkos_arch_gpu if b == "Cuda" else None + p = default_profile(b, env, settings.cmake_options, arch) + if b == "Cuda": + p["env_setup"] = env.rstrip("\n") + "\n" + (gpu_lines or "\n".join(PREFILL_GPU_LINES["Cuda"])) if slurm.strip() != prefill_slurm("cpu" if gpu else "gpu", settings.kokkos_arch_gpu): p["slurm_options"] = slurm return p @@ -788,10 +844,9 @@ def switch_backend(self, backend): if backend == self.kokkos_backend or backend not in PYKOKKOS_BACKENDS: return profiles = dict(self.backend_profiles) - profiles[self.kokkos_backend] = {k: getattr(self, k) for k in BACKEND_FIELDS} - new = profiles.pop(backend, None) or default_profile(backend, self.env_setup, self.cmake_options, - self.kokkos_arch_gpu) - for k in BACKEND_FIELDS: + profiles[self.kokkos_backend] = {k: getattr(self, k) for k in PROFILE_FIELDS} + new = profiles.pop(backend, None) or default_profile(backend, self.env_setup, self.cmake_options) + for k in PROFILE_FIELDS: setattr(self, k, new.get(k, "")) self.kokkos_backend = backend self.backend_profiles = profiles @@ -843,13 +898,18 @@ def nvcc_wrapper(self): return os.path.join(self.source, "external", "kalypsso-core", "external", "kokkos", "bin", "nvcc_wrapper") def compiler_args(self): - """Shell words giving cmake the compiler of a Cuda build, as Kokkos requires. + """Shell words giving cmake the compiler of a GPU build, as Kokkos requires. - The compiler is the nvcc_wrapper of the Kokkos sources, unless the CMake options name one. + Cuda: the nvcc_wrapper of the Kokkos sources; HIP: hipcc (of ROCm, in the PATH). None when the + CMake options name a compiler. """ - if self.kokkos_backend != "Cuda" or "-DCMAKE_CXX_COMPILER=" in self.cmake_options: + if "-DCMAKE_CXX_COMPILER=" in self.cmake_options: return "" - return shlex.quote("-DCMAKE_CXX_COMPILER=" + self.nvcc_wrapper()) + if self.kokkos_backend == "Cuda": + return shlex.quote("-DCMAKE_CXX_COMPILER=" + self.nvcc_wrapper()) + if self.kokkos_backend == "HIP": + return "-DCMAKE_CXX_COMPILER=hipcc" + return "" def environment(self): """Shell lines run before cmake and the solver: the environment of the current backend.""" @@ -1048,8 +1108,9 @@ def start_build(self, s, configure=False, build=True): if s.environment_problem(): return False, s.environment_problem() if configure and s.gpu and not s.kokkos_arch_gpu: - return False, ("choose the GPU architecture (Kokkos_ARCH, e.g. AMPERE80 for an A100): the Kokkos " - "built by canoP is compiled for it, and a build node has no GPU to find it") + return False, ("choose the GPU architecture (Kokkos_ARCH, e.g. AMPERE80 for an A100, AMD_GFX90A for " + "an MI250X): the Kokkos built by canoP is compiled for it, and a build node has no GPU " + "to find it") jobs = max(1, int(s.build_jobs)) # CMAKE_BUILD_PARALLEL_LEVEL: also the jobs of the Kokkos that canoP builds when it configures lines = [s.environment(), "export CMAKE_BUILD_PARALLEL_LEVEL=%d" % jobs, "set -x"] @@ -1152,8 +1213,10 @@ def start_run(self, s, ini_text, name): header.append("#SBATCH --cpus-per-task=%d" % s.omp_threads) if s.gpu: ngpus = max(1, s.gpus_per_task) - header.append("#SBATCH --gpus-per-task=%d" % ngpus if s.gpu_request == "gpus-per-task" - else "#SBATCH --gres=gpu:%d" % ngpus) + header.append({"gres": "#SBATCH --gres=gpu:%d", + "gpus-per-node": "#SBATCH --gpus-per-node=%d"}.get(s.gpu_request, + "#SBATCH --gpus-per-task=%d") + % ngpus) script = os.path.join(run_dir, "canoP_job.slurm") _write_script(script, header + s.slurm_options.splitlines() + body) # the previous log would be shown until the job starts @@ -1196,12 +1259,12 @@ def kokkos_options(source): """Backends and architectures that canoP can be built with. Return {"backends": [...], "host": [(name, label)], "Cuda": [...], "HIP": [...], "SYCL": [...]}: - the backends of the shared Kokkos that canoP builds for pykokkos (OpenMP or Cuda), with the + the backends of the shared Kokkos that canoP builds for pykokkos (OpenMP, Cuda or HIP), with the architectures found in the Kokkos sources. """ out = {"backends": list(PYKOKKOS_BACKENDS), "host": [], "Cuda": [], "HIP": [], "SYCL": []} o = kalypsso_kokkos_options(source) - out["host"], out["Cuda"] = o["host"], o["Cuda"] + out["host"], out["Cuda"], out["HIP"] = o["host"], o["Cuda"], o["HIP"] return out diff --git a/tools/canop_i18n_en.py b/tools/canop_i18n_en.py index 5e3cfb4..3de55b4 100644 --- a/tools/canop_i18n_en.py +++ b/tools/canop_i18n_en.py @@ -82,7 +82,7 @@ "Kokkos (partagé) et pykokkos sont construits avec canoP pour ce backend et ces architectures (GPU : celle du GPU des runs, ex. AMPERE80 pour un A100). L'environnement, les options CMake et les options Slurm des runs sont propres à chaque backend : ils changent avec lui.": "Kokkos (shared) and pykokkos are built with canoP for this backend and these architectures (GPU: that of the GPU of the runs, e.g. AMPERE80 for an A100). The environment, the CMake options and the Slurm options of the runs belong to each backend: they change with it.", "Build de cette variante : {{ build_dir_resolved }}": "Build of this variant: {{ build_dir_resolved }}", "Le backend et les architectures de Kokkos viennent des menus ci-dessus : le studio retire -DKALYPSSO_CORE_KOKKOS_BACKEND, -DKokkos_ARCH_… et -DKALYPSSO_CORE_KOKKOS_BUILD de ces options.": "The backend and the architectures of Kokkos come from the menus above: the studio removes -DKALYPSSO_CORE_KOKKOS_BACKEND, -DKokkos_ARCH_… and -DKALYPSSO_CORE_KOKKOS_BUILD from these options.", - "Un job d'une tâche avec « Jobs de compilation » cœurs ; Cuda se compile sans GPU.": "A job of one task with “Build jobs” cores; Cuda builds without a GPU.", + "Un job d'une tâche avec « Jobs de compilation » cœurs ; Cuda et HIP se compilent sans GPU.": "A job of one task with “Build jobs” cores; Cuda and HIP build without a GPU.", "{{ executable ? 'Exécutable : ' + executable : 'Exécutable non compilé' }}": "{{ executable ? 'Executable: ' + executable : 'Executable not built' }}", "Vider le répertoire de build": "Empty the build directory", "Exécution": "Execution", @@ -132,7 +132,7 @@ "Threads OpenMP": "OpenMP threads", "0 : non défini": "0: not set", "GPU par processus": "GPUs per process", - "avec --gres : GPU par nœud": "with --gres: GPUs per node", + "avec --gres ou --gpus-per-node : GPU par nœud": "with --gres or --gpus-per-node: GPUs per node", "Demande Slurm": "Slurm request", "Runs par soumission": "Runs per submission", "Runs par campagne": "Runs per campaign", diff --git a/tools/trame/campaign_template/project.py b/tools/trame/campaign_template/project.py index 237a173..1ce5dfc 100644 --- a/tools/trame/campaign_template/project.py +++ b/tools/trame/campaign_template/project.py @@ -145,7 +145,7 @@ def _partition(job): def _gpus(job): - """GPUs per process (per node with --gres) for a GPU build, else 0.""" + """GPUs per process (per node with --gres or --gpus-per-node) for a GPU build, else 0.""" return int(_setting(job, "gpus_per_task", 1) or 1) if _launch(job).get("gpu") else 0 diff --git a/tools/trame/campaign_template/templates/script.sh b/tools/trame/campaign_template/templates/script.sh index 1933f17..5dc6aa4 100644 --- a/tools/trame/campaign_template/templates/script.sh +++ b/tools/trame/campaign_template/templates/script.sh @@ -15,6 +15,8 @@ {% if op.directives.canop_gpus %} {% if project.doc.launch.gpu_request == "gres" %} #SBATCH --gres=gpu:{{ op.directives.canop_gpus }} +{% elif project.doc.launch.gpu_request == "gpus-per-node" %} +#SBATCH --gpus-per-node={{ op.directives.canop_gpus }} {% else %} #SBATCH --gpus-per-task={{ op.directives.canop_gpus }} {% endif %} diff --git a/tools/trame/canop_app.py b/tools/trame/canop_app.py index 943da5f..8bccf06 100644 --- a/tools/trame/canop_app.py +++ b/tools/trame/canop_app.py @@ -354,7 +354,7 @@ def on_settings(**_): state.kokkos_is_gpu = current_settings().gpu -# the backend whose environment, CMake options and Slurm lines are shown (core.BACKEND_FIELDS) +# the backend whose environment, CMake options, Slurm lines and GPU architecture are shown (core.PROFILE_FIELDS) _backend_shown = {"backend": None} @@ -371,7 +371,7 @@ def select_backend(backend): return s = current_settings(kokkos_backend=previous) s.switch_backend(backend) - for k in core.BACKEND_FIELDS + ("backend_profiles", "kokkos_backend"): + for k in core.PROFILE_FIELDS + ("backend_profiles", "kokkos_backend"): state["s_" + k] = getattr(s, k) @@ -1221,7 +1221,8 @@ def settings_panel(): v3.VTextarea(label=tr("Options Slurm de la compilation (#SBATCH)"), v_model=("s_build_slurm_options",), rows=2, auto_grow=True, density="compact", hide_details=True, classes="mb-2 mono", v_show="s_build_launcher === 'sbatch'") - html.Div(tr("Un job d'une tâche avec « Jobs de compilation » cœurs ; Cuda se compile sans GPU."), + html.Div(tr("Un job d'une tâche avec « Jobs de compilation » cœurs ; " + "Cuda et HIP se compilent sans GPU."), classes="text-caption mb-2", v_show="s_build_launcher === 'sbatch'") with html.Div(classes="d-flex ga-2"): v3.VBtn(tr("Configurer"), click=ctrl.configure, variant="tonal", size="small", @@ -1246,7 +1247,7 @@ def settings_panel(): with html.Div(classes="d-flex ga-2 mb-2", v_if="kokkos_is_gpu"): v3.VTextField(label=tr("GPU par processus"), v_model=("s_gpus_per_task",), type="number", density="compact", hide_details=True, - title=tr("avec --gres : GPU par nœud")) + title=tr("avec --gres ou --gpus-per-node : GPU par nœud")) v3.VSelect(label=tr("Demande Slurm"), v_model=("s_gpu_request",), items=("gpu_requests",), density="compact", hide_details=True) v3.VTextField(label=tr("Arguments supplémentaires"), v_model=("s_extra_args",), density="compact", diff --git a/tools/trame/canop_assistant.py b/tools/trame/canop_assistant.py index a604835..45340cd 100644 --- a/tools/trame/canop_assistant.py +++ b/tools/trame/canop_assistant.py @@ -75,14 +75,15 @@ its physics files compiles its kernels with pykokkos (about 10 s per kernel, a line 'pykokkos: ... compiled' each in the log, about 1 min more the first time for a compiler and Kokkos; kept in /pykokkos_cache): do not take it for a hang. canoP runs on the host (kokkos_backend -OpenMP) or on a GPU (Cuda, with kokkos_arch_gpu the architecture of the GPU, e.g. AMPERE80 for an -A100; its kernels are compiled by the first run on a GPU node, 20 to 45 s each, not on a login -node). Each backend has its own environment, CMake options and Slurm lines of the runs (user -only), switched with kokkos_backend. The build of canoP also builds its shared Kokkos (at the first -configuration, a few minutes) and pykokkos-base; build_launcher 'sbatch' compiles on a compute node -(a Slurm job, build_jobs cores, Cuda included: no GPU needed) instead of the login node -('direct'). Through the tools you can read and edit the ini parameter file shown in the -editor, build the code, run it, read the logs, and look at the results shown in the view +OpenMP) or on a GPU (Cuda for NVIDIA, HIP for AMD, with kokkos_arch_gpu the architecture of the +GPU, e.g. AMPERE80 for an A100, AMD_GFX90A for an MI250X; its kernels are compiled by the first run +on a GPU node, 20 to 45 s each, not on a login node). Each backend has its own environment, CMake +options, Slurm lines of the runs (user only) and GPU architecture, switched with kokkos_backend. +The build of canoP also builds its shared Kokkos (at the first configuration, a few minutes) +and pykokkos-base; build_launcher 'sbatch' compiles on a compute node (a Slurm job, build_jobs +cores, Cuda and HIP included: no GPU needed) instead of the login node ('direct'). Through the +tools you can read and edit the ini parameter file shown in the editor, build the code, +run it, read the logs, and look at the results shown in the view (fields, time steps, 3D slices, images, statistics, line profiles). Every change you make appears live in the user's browser. Keep runs small when the launcher is @@ -855,10 +856,11 @@ def _obj(props=None, required=None): ("update_settings", "Change build/run settings: dim (2 or 3: executable canoP_2d or canoP_3d), build_dir, run_dir, launcher " "(direct, mpirun, srun, sbatch), nprocs, omp_threads, build_jobs, build_launcher (direct: build on this " - "node; sbatch: a Slurm job on a compute node with build_jobs cores), kokkos_backend (OpenMP or Cuda: " + "node; sbatch: a Slurm job on a compute node with build_jobs cores), kokkos_backend (OpenMP, Cuda or HIP: " "the shared Kokkos that canoP builds; each backend and architecture has its own build directory: build " - "it before running; the environment, CMake options and Slurm lines of the runs switch with it), " - "kokkos_arch_host, kokkos_arch_gpu (Kokkos_ARCH name, required for Cuda, e.g. AMPERE80 for an A100), " + "it before running; the environment, CMake options, Slurm lines of the runs and GPU architecture switch " + "with it), kokkos_arch_host, kokkos_arch_gpu (Kokkos_ARCH name, required for Cuda and HIP, e.g. AMPERE80 " + "for an A100, AMD_GFX90A for an MI250X), " "gpus_per_task. Shell fields (modules, Python environment, cmake options, slurm lines of the runs and " "of the build) and the campaign limits are user-only.", _obj({k: {"type": v} for k, v in AGENT_SETTINGS.items()}), t_update_settings),