diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 05719f486..a03a7ac06 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -179,6 +179,42 @@ jobs: call "C:\Program Files (x86)\Intel\oneAPI\setvars.bat" >nul 2>&1 ctest --test-dir build-sycl --output-on-failure -R test_derivatives_sycl + hip-tests: + runs-on: ubuntu-22.04 + container: + image: rocm/dev-ubuntu-24.04:7.2 + name: Test HIP on ubuntu-22.04 (ROCm container) + steps: + - uses: actions/checkout@v3 + + - name: install build tools + run: | + apt-get update + apt-get install -y cmake build-essential git + + - name: record ROCm inventory + run: | + hipcc --version || true + rocminfo || true + + - name: configure HIP build + run: | + cmake -B build-hip -S . \ + -DSPHERICART_BUILD_TESTS=ON \ + -DSPHERICART_ENABLE_HIP=ON \ + -DCMAKE_PREFIX_PATH=/opt/rocm + + - name: build HIP tests + run: cmake --build build-hip --parallel + + # GitHub-hosted runners have no AMD GPU: the test compiles here and + # skips its device checks; full execution runs on self-hosted HIP + # runners (e.g. the gfx1151 qualification host used by symmetrix-xl) + - name: run HIP ctest + # matches test_derivatives_hip and test_hip_async; both skip without a + # device, example_hip (which does not skip) stays out + run: ctest --test-dir build-hip --output-on-failure -R "test_.*hip" + # check that we can build Python wheels on any Python version python-build: runs-on: ubuntu-24.04 diff --git a/README.md b/README.md index ccd346350..3ee2a9ade 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,7 @@ The support for GPU offload could be controled with the following CMake variable - `-DSPHERICART_ENABLE_CUDA=ON/OFF`: build with CUDA support also set `CUDA_HOME` environement variable. - `-DSPHERICART_ENABLE_SYCL=ON/OFF`: build with SYCL support, configure tool will search for `sycl/sycl.h` header. - `-DSPHERICART_SYCL_DEVICE=all/cpu/gpu`: target architecute for SYCL support, check which devices are available with `sycl-ls`, for `all` (default) is possible to control at execution with `export ONEAPI_DEVICE_SELECTOR=opencl:gpu` or `export ONEAPI_DEVICE_SELECTOR=opencl:cpu`. +- `-DSPHERICART_ENABLE_HIP=ON/OFF`: build the HIP backend with AMD ROCm support, the configure tool will search for the HIP runtime (e.g. `-DCMAKE_PREFIX_PATH=/opt/rocm`). The kernels are compiled at runtime with hipRTC, targeting the GCN architecture of the installed GPU, so no HIP compiler is needed at build time. HIP can be enabled alongside the CUDA and SYCL backends. Published wheels do not include the HIP backend; build from source on a system with ROCm. The following flags have been tested with Intel OneAPI 2025.3 for enabling SYCL support: - `-DCMAKE_CXX_COMPILER=icpx` diff --git a/docs/src/index.rst b/docs/src/index.rst index 0e7dda2d7..bb9318ecf 100644 --- a/docs/src/index.rst +++ b/docs/src/index.rst @@ -14,9 +14,10 @@ spherical harmonics and their derivatives in Cartesian coordinates. The theory behind this efficient implementation is detailed in `this paper `_. -The core library is implemented in C++ (with OpenMP parallelism), CUDA and SYCL. +The core library is implemented in C++ (with OpenMP parallelism), CUDA, HIP and SYCL. It also provides APIs for C, Python (NumPy), PyTorch and JAX. The torch and JAX -implementations provide fast spherical harmonics on Nvidia GPUs. +implementations provide fast spherical harmonics on Nvidia GPUs; the HIP backend +targets AMD GPUs through ROCm. A native Julia package is also available, contributed by `Christoph Ortner `_. diff --git a/docs/src/installation.rst b/docs/src/installation.rst index a51e93b31..e93481517 100644 --- a/docs/src/installation.rst +++ b/docs/src/installation.rst @@ -82,6 +82,7 @@ The following cmake configuration options are available: - ``-DSPHERICART_ENABLE_CUDA=ON/OFF``: build the CUDA backend (OFF by default) - ``-DSPHERICART_ENABLE_SYCL=ON/OFF``: build the SYCL backend (OFF by default) - ``-DSPHERICART_SYCL_DEVICE=all/cpu/gpu/accelerator``: select the device type used by the SYCL backend (``all`` by default) +- ``-DSPHERICART_ENABLE_HIP=ON/OFF``: build the HIP backend with AMD ROCm (OFF by default). The backend requires a ROCm installation (e.g. ``-DCMAKE_PREFIX_PATH=/opt/rocm``); kernels are compiled at runtime with hipRTC, so no HIP compiler is needed at build time. HIP can be enabled alongside the CUDA and SYCL backends. - ``-DCMAKE_INSTALL_PREFIX=where/you/want/to/install``: set the root path for installation (``/usr/local`` by default) Without specifying any options, the commands above will attempt to install diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index a1796d378..b9e6e60bf 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -30,6 +30,14 @@ if (SPHERICART_ENABLE_SYCL) add_test(NAME example_sycl COMMAND ./example_sycl) endif() +if (SPHERICART_ENABLE_HIP) + add_executable(example_hip hip/example.cpp) + target_link_libraries(example_hip sphericart ${ROCM_HIP_LIBRARY}) + target_include_directories(example_hip PRIVATE ${ROCM_HIP_INCLUDE_DIR}) + target_compile_definitions(example_hip PRIVATE __HIP_PLATFORM_AMD__=1) + add_test(NAME example_hip COMMAND ./example_hip) +endif() + find_package(Kokkos CONFIG) if(Kokkos_FOUND) add_executable(example_kokkos kokkos/example.cpp) diff --git a/examples/hip/example.cpp b/examples/hip/example.cpp new file mode 100644 index 000000000..6784ba85c --- /dev/null +++ b/examples/hip/example.cpp @@ -0,0 +1,155 @@ +/** @file example.cpp + * @brief Usage example for the HIP C++ API + */ + +#include "sphericart_hip.hpp" +#include +#include +#include +#include +#include + +#ifndef DTYPE +#define DTYPE double +#endif + +#include "sphericart.hpp" + +#define CHECK_HIP(call) \ + do { \ + hipError_t status_ = (call); \ + if (status_ != hipSuccess) { \ + std::cout << "HIP error at " << __FILE__ << ":" << __LINE__ << ": " \ + << hipGetErrorString(status_) << std::endl; \ + return 1; \ + } \ + } while (0) + +#define TOLERANCE 1e-4 // High tolerance: finite differences are inaccurate for second + +int main() { + /* ===== set up the calculation ===== */ + + // hard-coded parameters for the example + size_t n_samples = 1000; + size_t l_max = 6; + + // initializes samples + auto xyz = std::vector(n_samples * 3, 0.0); + for (size_t i = 0; i < n_samples * 3; ++i) { + xyz[i] = (DTYPE)rand() / (DTYPE)RAND_MAX * 2.0 - 1.0; + } + + // host-side results, used as a reference + auto sph = std::vector(n_samples * (l_max + 1) * (l_max + 1), 0.0); + auto dsph = std::vector(n_samples * 3 * (l_max + 1) * (l_max + 1), 0.0); + + // device-side results + auto sph_f = std::vector(n_samples * (l_max + 1) * (l_max + 1), 0.0); + auto dsph_f = std::vector(n_samples * 3 * (l_max + 1) * (l_max + 1), 0.0); + + DTYPE* xyz_device = nullptr; + DTYPE* sph_device = nullptr; + DTYPE* dsph_device = nullptr; + CHECK_HIP(hipMalloc(&xyz_device, xyz.size() * sizeof(DTYPE))); + CHECK_HIP(hipMalloc(&sph_device, sph.size() * sizeof(DTYPE))); + CHECK_HIP(hipMalloc(&dsph_device, dsph.size() * sizeof(DTYPE))); + CHECK_HIP(hipMemcpy(xyz_device, xyz.data(), xyz.size() * sizeof(DTYPE), hipMemcpyHostToDevice)); + + /* ===== API calls ===== */ + + // internal buffers and numerical factors are initialized at construction + // HIP calculator + sphericart::hip::SphericalHarmonics calculator_hip(l_max); + // CPU calculator + auto calculator = sphericart::SphericalHarmonics(l_max); + + std::cout << "ROUND 1 \n"; + std::cout << " Computing SPH only \n"; + calculator.compute(xyz, sph); + calculator_hip.compute(xyz_device, n_samples, sph_device); + + // Get results from device to host + CHECK_HIP( + hipMemcpy(sph_f.data(), sph_device, sph_f.size() * sizeof(DTYPE), hipMemcpyDeviceToHost) + ); + + /* ===== check results ===== */ + DTYPE sph_error = 0.0, sph_norm = 0.0, sph_error_max = 0.0; + for (size_t i = 0; i < sph.size(); ++i) { + DTYPE error = (sph_f[i] - sph[i]) * (sph_f[i] - sph[i]); + sph_error += error; + if (error > sph_error_max) { + sph_error_max = error; + } + sph_norm += sph[i] * sph[i]; + } + + std::cout << "CPU vs GPU relative error SPH: " << std::scientific << std::setprecision(8) + << sqrt(sph_error / sph_norm) << std::endl; + std::cout << "Maximum squared error SPH: " << std::scientific << std::setprecision(8) + << sph_error_max << std::endl; + std::cout << std::endl; + + std::cout << "ROUND 2 \n"; + std::cout << " Computing gradients (SPH and DSPH) \n"; + calculator.compute_with_gradients(xyz, sph, dsph); + calculator_hip.compute_with_gradients(xyz_device, n_samples, sph_device, dsph_device); + + CHECK_HIP( + hipMemcpy(sph_f.data(), sph_device, sph_f.size() * sizeof(DTYPE), hipMemcpyDeviceToHost) + ); + CHECK_HIP( + hipMemcpy(dsph_f.data(), dsph_device, dsph_f.size() * sizeof(DTYPE), hipMemcpyDeviceToHost) + ); + + /* ===== check results ===== */ + sph_error = 0.0, sph_norm = 0.0, sph_error_max = 0.0; + for (size_t i = 0; i < sph.size(); ++i) { + DTYPE error = (sph_f[i] - sph[i]) * (sph_f[i] - sph[i]); + sph_error += error; + if (error > sph_error_max) { + sph_error_max = error; + } + sph_norm += sph[i] * sph[i]; + } + + std::cout << "CPU vs GPU relative error SPH: " << std::scientific << std::setprecision(8) + << sqrt(sph_error / sph_norm) << std::endl; + std::cout << "Maximum squared error SPH: " << std::scientific << std::setprecision(8) + << sph_error_max << std::endl; + std::cout << std::endl; + + DTYPE dsph_error = 0.0, dsph_norm = 0.0, dsph_error_max = 0.0; + int n_sph = (l_max + 1) * (l_max + 1); + for (size_t alpha = 0; alpha < 3; alpha++) { + for (size_t i_sample = 0; i_sample < n_samples; i_sample++) { + for (int i_sph = 0; i_sph < n_sph; i_sph++) { + DTYPE d0 = dsph[3 * n_sph * i_sample + n_sph * alpha + i_sph]; + DTYPE d0_f = dsph_f[3 * n_sph * i_sample + n_sph * alpha + i_sph]; + DTYPE error = (d0 - d0_f) * (d0 - d0_f); + dsph_error += error; + if (error > dsph_error_max) { + dsph_error_max = error; + } + dsph_norm += d0 * d0; + } + } + } + std::cout << "CPU vs GPU relative error DSPH: " << std::scientific << std::setprecision(8) + << sqrt(dsph_error / dsph_norm) << std::endl; + std::cout << "Maximum squared error DSPH: " << std::scientific << std::setprecision(8) + << dsph_error_max << std::endl; + std::cout << std::endl; + + CHECK_HIP(hipFree(xyz_device)); + CHECK_HIP(hipFree(sph_device)); + CHECK_HIP(hipFree(dsph_device)); + + if (sqrt(sph_error / sph_norm) > TOLERANCE || sqrt(dsph_error / dsph_norm) > TOLERANCE) { + std::cout << "Example failed: GPU results do not match the CPU reference" << std::endl; + return 1; + } + + return 0; +} diff --git a/sphericart/CMakeLists.txt b/sphericart/CMakeLists.txt index d73455d05..e3d1f0f12 100644 --- a/sphericart/CMakeLists.txt +++ b/sphericart/CMakeLists.txt @@ -95,6 +95,7 @@ OPTION(SPHERICART_OPENMP "Try to use OpenMP when compiling Sphericart" ON) OPTION(SPHERICART_ARCH_NATIVE "Try to use -march=native when compiling Sphericart" ON) OPTION(SPHERICART_ENABLE_CUDA "Are we building the CUDA backend of Sphericart?" OFF) OPTION(SPHERICART_ENABLE_SYCL "Are we building the SYCL backend of Sphericart?" OFF) +OPTION(SPHERICART_ENABLE_HIP "Are we building the HIP backend with AMD ROCm?" OFF) if (SPHERICART_ENABLE_SYCL) # SYCL device type: "gpu", "cpu", "accelerator", or "all" @@ -241,19 +242,62 @@ else() list(APPEND COMMON_SOURCES "src/sphericart_cuda_stub.cpp") endif() +# Find HIP / ROCm. Kernels are compiled at runtime with hipRTC (a dlopen'd +# library), so the backend only needs the HIP runtime headers and library at +# build time - no HIP compiler is required, mirroring how the CUDA backend +# avoids a CUDA toolkit dependency through gpu-lite. +if (SPHERICART_ENABLE_HIP) + if (WIN32 OR APPLE) + message(FATAL_ERROR "The HIP backend of Sphericart is only supported on Linux") + endif() + + find_path(ROCM_HIP_INCLUDE_DIR + NAMES hip/hip_runtime.h + PATHS + "${ROCM_ROOT}/include" + "$ENV{ROCM_ROOT}/include" + "${HIP_PATH}/include" + "$ENV{HIP_PATH}/include" + /opt/rocm/include + ) + find_library(ROCM_HIP_LIBRARY + NAMES amdhip64 + PATHS + "${ROCM_ROOT}/lib" + "$ENV{ROCM_ROOT}/lib" + "${HIP_PATH}/lib" + "$ENV{HIP_PATH}/lib" + /opt/rocm/lib + ) + if (NOT ROCM_HIP_INCLUDE_DIR OR NOT ROCM_HIP_LIBRARY) + message(FATAL_ERROR + "SPHERICART_ENABLE_HIP=ON but the ROCm HIP runtime was not found. " + "Point CMake at your ROCm installation, e.g. " + "-DCMAKE_PREFIX_PATH=/opt/rocm") + endif() + message(STATUS "Found HIP runtime: ${ROCM_HIP_LIBRARY}") + + list(APPEND COMMON_SOURCES "include/hip_base.hpp") + list(APPEND COMMON_SOURCES "include/sphericart_hip.hpp") + list(APPEND COMMON_SOURCES "src/hiprtc_lite.cpp") + list(APPEND COMMON_SOURCES "src/hip_base.cpp") + list(APPEND COMMON_SOURCES "src/sphericart_hip.cpp") +endif() + add_library(sphericart ${COMMON_SOURCES}) -if (SPHERICART_ENABLE_CUDA) +if (SPHERICART_ENABLE_CUDA OR SPHERICART_ENABLE_HIP) #include the build/generated folder for compilation target_include_directories(sphericart PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) - target_link_libraries(sphericart PRIVATE gpulite) include_headers( "${CMAKE_CURRENT_SOURCE_DIR}/src/sphericart_impl.cu" "${CMAKE_CURRENT_BINARY_DIR}/generated/tmp.cu" ) - # Make the source file includeable by converting it to a string literal + # Make the source file includeable by converting it to a string literal. + # The same CUDA-dialect kernel source is embedded for the CUDA (NVRTC) and + # HIP (hipRTC) backends. make_includeable( "${CMAKE_CURRENT_BINARY_DIR}/generated/tmp.cu" "${CMAKE_CURRENT_BINARY_DIR}/generated/wrapped_sphericart_impl.cu" @@ -262,6 +306,19 @@ if (SPHERICART_ENABLE_CUDA) file(REMOVE "${CMAKE_CURRENT_BINARY_DIR}/generated/tmp.cuh") endif() +if (SPHERICART_ENABLE_CUDA) + target_link_libraries(sphericart PRIVATE gpulite) +endif() + +if (SPHERICART_ENABLE_HIP) + # __HIP_PLATFORM_AMD__ selects the AMD flavor of the HIP headers; hipcc + # defines it implicitly, this backend compiles with the host compiler + target_compile_definitions(sphericart PRIVATE SPHERICART_USE_HIP=1 __HIP_PLATFORM_AMD__=1) + target_include_directories(sphericart PRIVATE ${ROCM_HIP_INCLUDE_DIR}) + # ${CMAKE_DL_LIBS} is needed to dlopen libhiprtc at runtime + target_link_libraries(sphericart PRIVATE ${ROCM_HIP_LIBRARY} ${CMAKE_DL_LIBS}) +endif() + if (SYCL_COMPILER_FOUND AND NOT SPHERICART_ENABLE_SYCL) message(STATUS "Found a SYCL compiler but SPHERICART_ENABLE_SYCL=OFF, set SPHERICART_ENABLE_SYCL=ON in order to compile with CUDA support.") endif() diff --git a/sphericart/include/hip_base.hpp b/sphericart/include/hip_base.hpp new file mode 100644 index 000000000..1c9cde3db --- /dev/null +++ b/sphericart/include/hip_base.hpp @@ -0,0 +1,92 @@ +#ifndef SPHERICART_HIP_BASE_HPP +#define SPHERICART_HIP_BASE_HPP + +#include + +namespace sphericart { + +namespace hip { + +/** + * host function which wraps a HIP kernel to compute spherical harmonics and + * their derivatives. + * + * The kernel source is the same CUDA-dialect implementation used by the CUDA + * backend; it is compiled at runtime with hipRTC (following the mechanism + * qualified by symmetrix-xl's HIP backend) and launched through + * hipModuleLaunchKernel. + * + * @param xyz + * Pointer to a contiguous device-allocated coordinates array of shape + * [3N]. + * @param nedges + * Number of edges (N). + * @param prefactors + * Prefactors for spherical harmonics recursion. + * @param nprefactors + * Number of elements in the prefactors array. + * @param l_max + * The maximum degree of the spherical harmonics to be calculated. + * @param normalize + * If `false` (default) computes the scaled spherical harmonics, which + * are homogeneous polynomials in the Cartesian coordinates of the input + * points. If `true`, computes the normalized spherical harmonics that + * are evaluated on the unit sphere. In practice, this simply computes + * the scaled harmonics at the normalized coordinates \f$(x/r, y/r, z/r)\f$, and + * adapts the derivatives accordingly. + * @param GRID_DIM_X + * The size of the threadblock in the x dimension. Used to parallelize + * over the sample dimension + * @param GRID_DIM_Y + * The size of the threadblock in the y dimension. Used only to improve + * memory throughput on reads and writes. + * @param gradients + * Perform the computation of the first-order derivatives. + * @param hessian + * Perform the computation of the second-order derivatives. + * @param sph + * Pointer to a contiguous device-allocated spherical harmonics array of + * shape [N * (L + 1) ** 2]. + * @param dsph + * Pointer to a contiguous device-allocated spherical harmonics + * first-derivatives array of shape [N * 3 * (L + 1) ** 2]. + * @param ddsph + * Pointer to a contiguous device-allocated spherical harmonics + * second-derivatives array of shape [N * 3 * (L + 1) ** 2]. + * @param hip_stream + * Pointer to a hipStream_t or nullptr. If this is nullptr, the kernel + * launch will be performed on the default stream. + */ +template +void spherical_harmonics_hip_base( + const scalar_t* xyz, + const int nedges, + const scalar_t* prefactors, + const int nprefactors, + const int l_max, + const bool normalize, + const int64_t GRID_DIM_X, + const int64_t GRID_DIM_Y, + const bool gradients, + const bool hessian, + scalar_t* sph, + scalar_t* dsph, + scalar_t* ddsph, + void* hip_stream = nullptr, + bool synchronize = true +); + +template +void spherical_harmonics_backward_hip_base( + const scalar_t* dsph, + const scalar_t* sph_grad, + const int nedges, + const int ntotal, + scalar_t* xyz_grad, + void* hip_stream = nullptr +); + +} // namespace hip +} // namespace sphericart + +#endif diff --git a/sphericart/include/sphericart_hip.hpp b/sphericart/include/sphericart_hip.hpp new file mode 100644 index 000000000..ceb595e06 --- /dev/null +++ b/sphericart/include/sphericart_hip.hpp @@ -0,0 +1,199 @@ +/** \file sphericart_hip.hpp + * Defines the HIP C++ API for `sphericart`. Two classes are available: + * `SphericalHarmonics` and `SolidHarmonics`. The former calculates the + * real spherical harmonics \f$ Y^m_l \f$ as defined on Wikipedia, + * which are homogeneous polynomials of (x/r, y/r, z/r). The latter + * calculates the same polynomials but as a function of the Cartesian coordinates + * (x, y, z), or, equivalently, \f$ r^l\,Y^m_l \f$. + */ + +#ifndef SPHERICART_HIP_HPP +#define SPHERICART_HIP_HPP + +#include + +// wrap this with cond because breathe can't handle the same namespace in two +// files +/* @cond */ +namespace sphericart { +/* @endcond */ + +/** + * The `sphericart::hip` namespace contains the HIP (AMD ROCm) API for + * `sphericart`. + */ +namespace hip { + +/** + * A spherical harmonics calculator. + * + * It handles initialization of the prefactors upon initialization and it + * stores the buffers that are necessary to compute the spherical harmonics + * efficiently. + */ +template class SphericalHarmonics { + public: + /** Initialize the SphericalHarmonics class setting maximum degree and + * normalization + * + * @param l_max + * The maximum degree of the spherical harmonics to be calculated. + */ + SphericalHarmonics(size_t l_max); + + /* @cond */ + ~SphericalHarmonics(); + /* @endcond */ + + /** Computes the spherical harmonics for one or more 3D points, using + * pre-allocated device-side pointers + * + * @param xyz A pre-allocated device-side array of size `n_samples x 3`. It + * contains the Cartesian coordinates of the 3D points for which the + * spherical harmonics are to be computed, organized along two dimensions. + * The outer dimension is `n_samples` long, accounting for different + * samples, while the inner dimension has size 3 and it represents + * the x, y, and z coordinates respectively. + * @param n_samples Number of samples contained within `xyz`. + * @param sph On entry, a preallocated device-side array of size `n_samples + * x (l_max + 1)^2`. On exit, this array will contain the + * spherical harmonics organized along two dimensions. The leading dimension + * is `n_samples` long and it represents the different samples, while the + * inner dimension is + * `(l_max + 1)^2` long and it contains the spherical harmonics. + * These are laid out in lexicographic order. For example, if `l_max=2`, it + * will contain `(l, m) = (0, 0), (1, -1), (1, 0), (1, 1), (2, -2), (2, -1), + * (2, 0), (2, 1), (2, 2)`, in this order. + * @param hip_stream Pointer to a hipStream_t or nullptr. If this is + * nullptr, the kernel launch will be performed on the default stream. + */ + void compute(const T* xyz, const size_t n_samples, T* sph, void* hip_stream = nullptr); + + /** Computes the spherical harmonics and their first derivatives for one or + * more 3D points, using pre-allocated device-side pointers + * + * @param xyz A pre-allocated device-side array of size `n_samples x 3`. It + * contains the Cartesian coordinates of the 3D points for which the + * spherical harmonics are to be computed, organized along two dimensions. + * The outer dimension is `n_samples` long, accounting for different + * samples, while the inner dimension has size 3 and it represents + * the x, y, and z coordinates respectively. + * @param n_samples Number of samples contained within `xyz`. + * @param sph On entry, a preallocated device-side array of size `n_samples + * x (l_max + 1)^2`. On exit, this array will contain the + * spherical harmonics organized along two dimensions. The leading dimension + * is `n_samples` long and it represents the different samples, while the + * inner dimension is + * `(l_max + 1)^2` long and it contains the spherical harmonics. + * These are laid out in lexicographic order. For example, if `l_max=2`, it + * will contain `(l, m) = (0, 0), (1, -1), (1, 0), (1, 1), (2, -2), (2, -1), + * (2, 0), (2, 1), (2, 2)`, in this order. + * @param dsph On entry, nullptr or a preallocated device-side array of size + * `n_samples x 3 x (l_max + 1)^2`. If the pointer is not + * nullptr, then compute_with_gradients must also be true in order for + * gradients to be computed. + * @param hip_stream Pointer to a hipStream_t or nullptr. If this is + * nullptr, the kernel launch will be performed on the default stream. + */ + void compute_with_gradients( + const T* xyz, const size_t n_samples, T* sph, T* dsph, void* hip_stream = nullptr + ); + + /** Enqueues spherical harmonics and first derivatives without synchronizing. + * The caller owns stream synchronization and must keep all buffers alive + * until the work completes. + */ + void compute_with_gradients_async( + const T* xyz, const size_t n_samples, T* sph, T* dsph, void* hip_stream = nullptr + ); + + /** Releases lazily allocated device resources. The operation is idempotent. + * The caller must ensure that all work using this calculator has completed. + */ + void release_device_resources(); + + /** Computes the spherical harmonics and their first and second derivatives + * for one or more 3D points, using pre-allocated device-side pointers + * + * @param xyz A pre-allocated device-side array of size `n_samples x 3`. It + * contains the Cartesian coordinates of the 3D points for which the + * spherical harmonics are to be computed, organized along two dimensions. + * The outer dimension is `n_samples` long, accounting for different + * samples, while the inner dimension has size 3 and it represents + * the x, y, and z coordinates respectively. + * @param n_samples Number of samples contained within `xyz`. + * @param sph On entry, a preallocated device-side array of size `n_samples + * x (l_max + 1)^2`. On exit, this array will contain the + * spherical harmonics organized along two dimensions. The leading dimension + * is `n_samples` long and it represents the different samples, while the + * inner dimension is + * `(l_max + 1)^2` long and it contains the spherical harmonics. + * These are laid out in lexicographic order. For example, if `l_max=2`, it + * will contain `(l, m) = (0, 0), (1, -1), (1, 0), (1, 1), (2, -2), (2, -1), + * (2, 0), (2, 1), (2, 2)`, in this order. + * @param dsph On entry, nullptr or a preallocated device-side array of size + * `n_samples x 3 x (l_max + 1)^2`. If the pointer is not + * nullptr, then compute_with_gradients must also be true in order for + * gradients to be computed. + * @param ddsph On entry, nullptr or a preallocated device-side array of + * size `n_samples x 3 x 3 x (l_max + 1)^2`. If the pointer is + * not nullptr, then compute_with_hessians must also be true in order for + * gradients to be computed. + * @param hip_stream Pointer to a hipStream_t or nullptr. If this is + * nullptr, the kernel launch will be performed on the default stream. + */ + void compute_with_hessians( + const T* xyz, const size_t n_samples, T* sph, T* dsph, T* ddsph, void* hip_stream = nullptr + ); + + template friend class SolidHarmonics; + /* @cond */ + private: + size_t l_max; // maximum l value computed by this class + size_t nprefactors; + bool normalized; // should we normalize the input vectors? + T* prefactors_cpu = nullptr; // host prefactors buffer + T* prefactors_hip = nullptr; // storage space for prefactors + int bound_device = -1; + int device_count = 0; // number of visible GPU devices + int64_t HIP_GRID_DIM_X_ = 8; + int64_t HIP_GRID_DIM_Y_ = 8; + + void compute_internal( + const T* xyz, + const size_t n_samples, + bool compute_with_gradients, + bool compute_with_hessian, + T* sph, + T* dsph, + T* ddsph, + void* hip_stream, + bool synchronize + ); + /* @endcond */ +}; + +/** + * A solid harmonics calculator. + * + * Its interface is the same as that of the `SphericalHarmonics` class, but it + * calculates the solid harmonics \f$ r^l\,Y^m_l \f$ instead of the real spherical + * harmonics \f$ Y^m_l \f$, allowing for faster computations. + */ +template class SolidHarmonics : public SphericalHarmonics { + public: + /** Initialize the SolidHarmonics class setting its maximum degree + * + * @param l_max + * The maximum degree of the spherical harmonics to be calculated. + */ + SolidHarmonics(size_t l_max); +}; + +} // namespace hip + +/* @cond */ +} // namespace sphericart +/* @endcond */ + +#endif diff --git a/sphericart/src/hip_base.cpp b/sphericart/src/hip_base.cpp new file mode 100644 index 000000000..21454b506 --- /dev/null +++ b/sphericart/src/hip_base.cpp @@ -0,0 +1,386 @@ +#define _SPHERICART_INTERNAL_IMPLEMENTATION + +#include +#include +#include +#include +#include +#include + +#include + +#include "sphericart_impl.cuh" + +#include "hip_base.hpp" +#include "hiprtc_lite.hpp" + +#define HARDCODED_LMAX 1 + +// The kernel source is embedded as a byte array with a trailing 0x00 generated +// by make_includeable in CMakeLists.txt, matching the representation used in +// vesin and by the CUDA backend. The CUDA-dialect source is compiled at +// runtime by hipRTC (the mechanism ported from symmetrix-xl's HIP backend); +// hipCC/hipRTC accept CUDA-dialect kernels unchanged. +static const unsigned char HIP_CODE_DATA[] = { +#include "generated/wrapped_sphericart_impl.cu" +}; +static const char* HIP_CODE = reinterpret_cast(HIP_CODE_DATA); + +static void check_hip(hipError_t status, const std::string& what) { + if (status != hipSuccess) { + throw std::runtime_error(what + " failed: " + hipGetErrorString(status)); + } +} + +/* + Computes the total amount of shared memory space required by + spherical_harmonics_kernel. Mirrors the sizing in cuda_base.cpp. +*/ +static size_t total_buffer_size( + size_t l_max, size_t GRID_DIM_Y, size_t dtype_size, bool requires_grad, bool requires_hessian +) { + int nl = + std::max(static_cast((HARDCODED_LMAX + 1) * (HARDCODED_LMAX + 1)), 2 * l_max + 1); + + size_t total_buff_size = 0; + + total_buff_size += GRID_DIM_Y * (l_max + 1) * dtype_size; // buffer_c + total_buff_size += GRID_DIM_Y * (l_max + 1) * dtype_size; // buffer_s + total_buff_size += GRID_DIM_Y * (l_max + 1) * dtype_size; // buffer_twomz + total_buff_size += (l_max + 1) * (l_max + 2) * dtype_size; // buffer_prefactors + total_buff_size += GRID_DIM_Y * nl * dtype_size; // buffer_sph_out + + if (requires_grad) { + total_buff_size += 3 * GRID_DIM_Y * nl * dtype_size; // buffer_sph_derivs + } + + if (requires_hessian) { + total_buff_size += 9 * GRID_DIM_Y * nl * dtype_size; // buffer_sph_hessian + } + + return total_buff_size; +} + +// Name expression for the template kernels, e.g. +// "spherical_harmonics_kernel". The explicit float/double +// instantiations live at the bottom of sphericart_impl.cu. +template static std::string template_kernel_name(const std::string& fn_name) { + if constexpr (std::is_same::value) { + return fn_name + ""; + } else if constexpr (std::is_same::value) { + return fn_name + ""; + } else { + static_assert(sizeof(scalar_t) == 0, "sphericart HIP kernels only support float and double"); + } +} + +/* + Runtime-compiled kernel handle for one device. + + Mirrors gpulite's per-device KernelFactory on the CUDA side: the module is + compiled with hipRTC for the device's own GCN architecture (queried at + runtime from hipGetDeviceProperties, following symmetrix-xl), loaded with + hipModuleLoadData, and its kernels resolved through the lowered (mangled) + names of the requested name expressions. +*/ +struct HipKernelModule { + hipModule_t module = nullptr; + std::unordered_map functions; + int default_shared_memory_per_block = -1; + int optin_shared_memory_per_block = -1; + std::unordered_map shared_memory_opted_in; +}; + +static HipKernelModule& device_kernel_cache(int device) { + static std::mutex cache_mutex; + static std::unordered_map cache; + + std::lock_guard lock(cache_mutex); + return cache[device]; +} + +static hipFunction_t get_hip_kernel(int device, const std::string& kernel_expression) { + auto& entry = device_kernel_cache(device); + static std::mutex compile_mutex; + std::lock_guard lock(compile_mutex); + + auto found = entry.functions.find(kernel_expression); + if (found != entry.functions.end()) { + return found->second; + } + + // Resolve the target architecture at runtime, like symmetrix-xl does for + // its JIT modules: gcnArchName may carry feature suffixes + // ("gfx1151:sramecc+:xnack-"), which are not valid --gpu-architecture + // values and must be stripped. + hipDeviceProp_t properties; + check_hip(hipGetDeviceProperties(&properties, device), "hipGetDeviceProperties"); + std::string gcn_arch(properties.gcnArchName); + auto feature_suffix = gcn_arch.find(':'); + if (feature_suffix != std::string::npos) { + gcn_arch.erase(feature_suffix); + } + + auto compilation = sphericart::hip::compile_hip_with_hiprtc( + std::string(HIP_CODE), + "wrapped_sphericart_impl.cu", + {kernel_expression}, + {"--std=c++17", "--gpu-architecture=" + gcn_arch} + ); + + // hipModuleLoadData attaches the module to the current device context + int current_device = 0; + check_hip(hipGetDevice(¤t_device), "hipGetDevice"); + if (current_device != device) { + check_hip(hipSetDevice(device), "hipSetDevice"); + } + + check_hip(hipModuleLoadData(&entry.module, compilation.code.data()), "hipModuleLoadData"); + + auto lowered = compilation.lowered_names.find(kernel_expression); + if (lowered == compilation.lowered_names.end()) { + throw std::runtime_error( + "hipRTC did not lower the kernel name expression " + kernel_expression + ); + } + + hipFunction_t function = nullptr; + check_hip( + hipModuleGetFunction(&function, entry.module, lowered->second.c_str()), + "hipModuleGetFunction(" + kernel_expression + ")" + ); + + if (current_device != device) { + check_hip(hipSetDevice(current_device), "hipSetDevice"); + } + + entry.functions[kernel_expression] = function; + return function; +} + +/* + Opt the kernel into more than the default dynamic shared memory when the + launch needs it (the HIP analog of gpulite's checkAndAdjustSharedMem). +*/ +static void ensure_shared_memory(int device, hipFunction_t function, unsigned int shared_bytes) { + auto& entry = device_kernel_cache(device); + static std::mutex attribute_mutex; + std::lock_guard lock(attribute_mutex); + + if (entry.default_shared_memory_per_block < 0) { + int default_smem = 0; + check_hip( + hipDeviceGetAttribute(&default_smem, hipDeviceAttributeMaxSharedMemoryPerBlock, device), + "hipDeviceGetAttribute(MaxSharedMemoryPerBlock)" + ); + int optin_smem = 0; + check_hip( + hipDeviceGetAttribute(&optin_smem, hipDeviceAttributeSharedMemPerBlockOptin, device), + "hipDeviceGetAttribute(SharedMemPerBlockOptin)" + ); + entry.default_shared_memory_per_block = default_smem; + entry.optin_shared_memory_per_block = optin_smem; + } + + if (shared_bytes <= static_cast(entry.default_shared_memory_per_block)) { + return; + } + + if (shared_bytes > static_cast(entry.optin_shared_memory_per_block)) { + throw std::runtime_error( + "sphericart HIP kernel requires " + std::to_string(shared_bytes) + + " bytes of shared memory, more than the device opt-in limit of " + + std::to_string(entry.optin_shared_memory_per_block) + " bytes" + ); + } + + auto& opted_in = entry.shared_memory_opted_in[function]; + if (opted_in) { + return; + } + + check_hip( + hipFuncSetAttribute( + function, hipFuncAttributeMaxDynamicSharedMemorySize, entry.optin_shared_memory_per_block + ), + "hipFuncSetAttribute(MaxDynamicSharedMemorySize)" + ); + opted_in = true; +} + +/* + Wrapper to compile and launch the HIP kernel. + + GRID_DIM_X is the number of threads to launch in the x dimension. Used to + parallelize over the sample dimension. GRID_DIM_Y is the number of threads + to launch in the y dimension. Used only to improve memory throughput on + reads and writes. + + hip_stream should be of type (void *), therefore if you want to pass in + a hipStream_t, first do void * stream_ptr = reinterpret_cast + (stream); +*/ +template +void sphericart::hip::spherical_harmonics_hip_base( + const scalar_t* xyz, + const int nedges, + const scalar_t* prefactors, + const int nprefactors, + const int l_max, + const bool normalize, + const int64_t GRID_DIM_X, + const int64_t GRID_DIM_Y, + const bool gradients, + const bool hessian, + scalar_t* sph, + scalar_t* dsph, + scalar_t* ddsph, + void* hip_stream, + bool synchronize +) { + int n_total = (l_max + 1) * (l_max + 1); + auto find_num_blocks = [](int x, int bdim) { return x / bdim + (x % bdim != 0); }; + + int device; + check_hip(hipGetDevice(&device), "hipGetDevice"); + hipFunction_t function = + get_hip_kernel(device, template_kernel_name("spherical_harmonics_kernel")); + + unsigned int shared_bytes = static_cast( + total_buffer_size(l_max, GRID_DIM_Y, sizeof(scalar_t), gradients, hessian) + ); + ensure_shared_memory(device, function, shared_bytes); + + void* parameters[] = { + const_cast(&xyz), + const_cast(&nedges), + const_cast(&prefactors), + const_cast(&nprefactors), + const_cast(&l_max), + const_cast(&n_total), + const_cast(&gradients), + const_cast(&hessian), + const_cast(&normalize), + &sph, + &dsph, + &ddsph, + }; + + check_hip( + hipModuleLaunchKernel( + function, + static_cast(find_num_blocks(nedges, static_cast(GRID_DIM_Y))), + 1, + 1, + static_cast(GRID_DIM_X), + static_cast(GRID_DIM_Y), + 1, + shared_bytes, + reinterpret_cast(hip_stream), + parameters, + nullptr + ), + "hipModuleLaunchKernel(spherical_harmonics_kernel)" + ); + if (synchronize) { + check_hip( + hipStreamSynchronize(reinterpret_cast(hip_stream)), "hipStreamSynchronize" + ); + } +} + +template void sphericart::hip::spherical_harmonics_hip_base( + const float* xyz, + const int nedges, + const float* prefactors, + const int nprefactors, + const int l_max, + const bool normalize, + const int64_t GRID_DIM_X, + const int64_t GRID_DIM_Y, + const bool gradients, + const bool hessian, + float* sph, + float* dsph, + float* ddsph, + void* hip_stream, + bool synchronize +); + +template void sphericart::hip::spherical_harmonics_hip_base( + const double* xyz, + const int nedges, + const double* prefactors, + const int nprefactors, + const int l_max, + const bool normalize, + const int64_t GRID_DIM_X, + const int64_t GRID_DIM_Y, + const bool gradients, + const bool hessian, + double* sph, + double* dsph, + double* ddsph, + void* hip_stream, + bool synchronize +); + +template +void sphericart::hip::spherical_harmonics_backward_hip_base( + const scalar_t* dsph, + const scalar_t* sph_grad, + const int nedges, + const int ntotal, + scalar_t* xyz_grad, + void* hip_stream +) { + auto find_num_blocks = [](int x, int bdim) { return x / bdim + (x % bdim != 0); }; + + int device; + check_hip(hipGetDevice(&device), "hipGetDevice"); + hipFunction_t function = + get_hip_kernel(device, template_kernel_name("backward_kernel")); + + void* parameters[] = { + const_cast(&dsph), + const_cast(&sph_grad), + const_cast(&nedges), + const_cast(&ntotal), + &xyz_grad, + }; + + check_hip( + hipModuleLaunchKernel( + function, + static_cast(find_num_blocks(nedges, 32)), + 3, + 1, + 4, + 32, + 1, + 0, + reinterpret_cast(hip_stream), + parameters, + nullptr + ), + "hipModuleLaunchKernel(backward_kernel)" + ); +} + +template void sphericart::hip::spherical_harmonics_backward_hip_base( + const float* dsph, + const float* sph_grad, + const int nedges, + const int ntotal, + float* xyz_grad, + void* hip_stream +); + +template void sphericart::hip::spherical_harmonics_backward_hip_base( + const double* dsph, + const double* sph_grad, + const int nedges, + const int ntotal, + double* xyz_grad, + void* hip_stream +); diff --git a/sphericart/src/hiprtc_lite.cpp b/sphericart/src/hiprtc_lite.cpp new file mode 100644 index 000000000..3a04f6dd4 --- /dev/null +++ b/sphericart/src/hiprtc_lite.cpp @@ -0,0 +1,303 @@ +#include "hiprtc_lite.hpp" + +#if defined(SPHERICART_USE_HIP) && !defined(_WIN32) + +#include +#include + +#include +#include +#include +#include + +namespace sphericart { +namespace hip { +namespace { + +/* + * Runtime loader for libhiprtc, following symmetrix-xl's jit_hiprtc.cpp: + * explicit override first, then a small set of well-known candidates. + */ +class HiprtcApi { + public: + HiprtcApi() { + if (const char* explicit_library = std::getenv("SPHERICART_HIPRTC_LIBRARY"); + explicit_library != nullptr && explicit_library[0] != '\0') { + handle_ = dlopen(explicit_library, RTLD_NOW | RTLD_LOCAL); + if (handle_ != nullptr) { + library_ = explicit_library; + } + } + constexpr std::array candidates{ + "libhiprtc.so", + "libhiprtc.so.7", + "libhiprtc.so.6", + "/opt/rocm/lib/libhiprtc.so", + }; + for (const char* candidate : candidates) { + if (handle_ != nullptr) { + break; + } + handle_ = dlopen(candidate, RTLD_NOW | RTLD_LOCAL); + if (handle_ != nullptr) { + library_ = candidate; + break; + } + } + if (handle_ == nullptr) { + const char* error = dlerror(); + reason_ = error == nullptr ? "hipRTC shared library was not found" : error; + return; + } + try { + version = symbol("hiprtcVersion"); + create_program = symbol("hiprtcCreateProgram"); + destroy_program = symbol("hiprtcDestroyProgram"); + add_name_expression = + symbol("hiprtcAddNameExpression"); + compile_program = symbol("hiprtcCompileProgram"); + get_program_log_size = + symbol("hiprtcGetProgramLogSize"); + get_program_log = symbol("hiprtcGetProgramLog"); + get_code_size = symbol("hiprtcGetCodeSize"); + get_code = symbol("hiprtcGetCode"); + get_lowered_name = symbol("hiprtcGetLoweredName"); + get_error_string = symbol("hiprtcGetErrorString"); + } catch (const std::exception& error) { + reason_ = error.what(); + dlclose(handle_); + handle_ = nullptr; + } + } + + ~HiprtcApi() { + if (handle_ != nullptr) { + dlclose(handle_); + } + } + + HiprtcApi(const HiprtcApi&) = delete; + HiprtcApi& operator=(const HiprtcApi&) = delete; + + bool available() const noexcept { return handle_ != nullptr; } + const std::string& library() const noexcept { return library_; } + const std::string& reason() const noexcept { return reason_; } + + decltype(&hiprtcVersion) version = nullptr; + decltype(&hiprtcCreateProgram) create_program = nullptr; + decltype(&hiprtcDestroyProgram) destroy_program = nullptr; + decltype(&hiprtcAddNameExpression) add_name_expression = nullptr; + decltype(&hiprtcCompileProgram) compile_program = nullptr; + decltype(&hiprtcGetProgramLogSize) get_program_log_size = nullptr; + decltype(&hiprtcGetProgramLog) get_program_log = nullptr; + decltype(&hiprtcGetCodeSize) get_code_size = nullptr; + decltype(&hiprtcGetCode) get_code = nullptr; + decltype(&hiprtcGetLoweredName) get_lowered_name = nullptr; + decltype(&hiprtcGetErrorString) get_error_string = nullptr; + + private: + template Function symbol(const char* name) { + dlerror(); + void* address = dlsym(handle_, name); + const char* error = dlerror(); + if (error != nullptr || address == nullptr) { + throw std::runtime_error( + std::string("Could not resolve hipRTC symbol ") + name + ": " + + (error == nullptr ? "symbol is null" : error) + ); + } + return reinterpret_cast(address); + } + + void* handle_ = nullptr; + std::string library_; + std::string reason_; +}; + +HiprtcApi& api() { + static HiprtcApi instance; + return instance; +} + +std::runtime_error hiprtc_error( + const HiprtcApi& value, hiprtcResult status, const std::string& operation +) { + const char* message = + value.get_error_string == nullptr ? nullptr : value.get_error_string(status); + return std::runtime_error( + operation + " failed: " + (message == nullptr ? "unknown hipRTC error" : message) + ); +} + +class Program { + public: + Program(HiprtcApi& api, const std::string& source, const std::string& source_name) : api_(api) { + const auto status = + api_.create_program(&program_, source.c_str(), source_name.c_str(), 0, nullptr, nullptr); + if (status != HIPRTC_SUCCESS) { + throw hiprtc_error(api_, status, "hiprtcCreateProgram"); + } + } + + ~Program() { + if (program_ != nullptr) { + api_.destroy_program(&program_); + } + } + + Program(const Program&) = delete; + Program& operator=(const Program&) = delete; + hiprtcProgram get() const noexcept { return program_; } + + private: + HiprtcApi& api_; + hiprtcProgram program_ = nullptr; +}; + +std::string program_log(HiprtcApi& value, hiprtcProgram program) { + std::size_t size = 0; + auto status = value.get_program_log_size(program, &size); + if (status != HIPRTC_SUCCESS) { + throw hiprtc_error(value, status, "hiprtcGetProgramLogSize"); + } + if (size <= 1) { + return {}; + } + std::string log(size, '\0'); + status = value.get_program_log(program, log.data()); + if (status != HIPRTC_SUCCESS) { + throw hiprtc_error(value, status, "hiprtcGetProgramLog"); + } + while (!log.empty() && log.back() == '\0') { + log.pop_back(); + } + return log; +} + +} // namespace + +HiprtcInformation hiprtc_information() { + auto& value = api(); + HiprtcInformation result; + result.available = value.available(); + result.library = value.library(); + result.reason = value.reason(); + if (!value.available()) { + return result; + } + const auto status = value.version(&result.major, &result.minor); + if (status != HIPRTC_SUCCESS) { + throw hiprtc_error(value, status, "hiprtcVersion"); + } + return result; +} + +HiprtcCompilation compile_hip_with_hiprtc( + const std::string& source, + const std::string& source_name, + const std::vector& name_expressions, + const std::vector& options +) { + auto& value = api(); + if (!value.available()) { + throw std::runtime_error( + "hipRTC is unavailable: " + + (value.reason().empty() ? std::string("library not found") : value.reason()) + ); + } + if (source.empty()) { + throw std::invalid_argument("hipRTC source must not be empty"); + } + + HiprtcCompilation result; + auto status = value.version(&result.major, &result.minor); + if (status != HIPRTC_SUCCESS) { + throw hiprtc_error(value, status, "hiprtcVersion"); + } + + Program program(value, source, source_name); + + for (const auto& expression : name_expressions) { + if (expression.empty()) { + throw std::invalid_argument("hipRTC name expressions must not be empty"); + } + status = value.add_name_expression(program.get(), expression.c_str()); + if (status != HIPRTC_SUCCESS) { + throw hiprtc_error(value, status, "hiprtcAddNameExpression(" + expression + ")"); + } + } + + std::vector option_pointers; + option_pointers.reserve(options.size()); + for (const auto& option : options) { + if (option.empty()) { + throw std::invalid_argument("hipRTC options must not contain empty strings"); + } + option_pointers.push_back(option.c_str()); + } + status = value.compile_program( + program.get(), static_cast(option_pointers.size()), option_pointers.data() + ); + result.log = program_log(value, program.get()); + if (status != HIPRTC_SUCCESS) { + throw std::runtime_error( + std::string("hiprtcCompileProgram failed: ") + value.get_error_string(status) + + (result.log.empty() ? std::string() : std::string("\n") + result.log) + ); + } + + std::size_t code_size = 0; + status = value.get_code_size(program.get(), &code_size); + if (status != HIPRTC_SUCCESS) { + throw hiprtc_error(value, status, "hiprtcGetCodeSize"); + } + if (code_size == 0) { + throw std::runtime_error("hipRTC produced an empty code object"); + } + result.code.resize(code_size); + status = value.get_code(program.get(), reinterpret_cast(result.code.data())); + if (status != HIPRTC_SUCCESS) { + throw hiprtc_error(value, status, "hiprtcGetCode"); + } + + for (const auto& expression : name_expressions) { + const char* lowered_name = nullptr; + status = value.get_lowered_name(program.get(), expression.c_str(), &lowered_name); + if (status != HIPRTC_SUCCESS) { + throw hiprtc_error(value, status, "hiprtcGetLoweredName(" + expression + ")"); + } + if (lowered_name == nullptr) { + throw std::runtime_error("hiprtcGetLoweredName returned null for " + expression); + } + result.lowered_names[expression] = lowered_name; + } + return result; +} + +} // namespace hip +} // namespace sphericart + +#else + +#include + +namespace sphericart { +namespace hip { + +HiprtcInformation hiprtc_information() { + return {false, {}, "this sphericart build does not enable the HIP backend", 0, 0}; +} + +HiprtcCompilation compile_hip_with_hiprtc( + const std::string&, + const std::string&, + const std::vector&, + const std::vector& +) { + throw std::runtime_error("hipRTC compilation requires a HIP-enabled sphericart build"); +} + +} // namespace hip +} // namespace sphericart + +#endif diff --git a/sphericart/src/hiprtc_lite.hpp b/sphericart/src/hiprtc_lite.hpp new file mode 100644 index 000000000..127cbe466 --- /dev/null +++ b/sphericart/src/hiprtc_lite.hpp @@ -0,0 +1,57 @@ +#ifndef SPHERICART_HIPRTC_LITE_HPP +#define SPHERICART_HIPRTC_LITE_HPP + +#include +#include +#include + +namespace sphericart { +namespace hip { + +/* + * Minimal hipRTC front-end used by the HIP backend of sphericart. + * + * This is a port of the runtime-compilation mechanism of symmetrix-xl's HIP + * backend (libsymmetrix/source/jit_hiprtc.cpp): libhiprtc is resolved with + * dlopen at runtime — it is never a link-time dependency — so HIP wheels only + * require the ROCm runtime, and detailed diagnostics can be reported when the + * library is missing. + * + * Unlike symmetrix-xl (whose generated kernels are extern "C"), sphericart's + * kernels are templates, so the compile step also lowers kernel name + * expressions (e.g. "spherical_harmonics_kernel") to the mangled names + * required by hipModuleGetFunction, mirroring what gpu-lite does with NVRTC + * on the CUDA side. + */ + +struct HiprtcInformation { + bool available = false; + std::string library; + std::string reason; + int major = 0; + int minor = 0; +}; + +HiprtcInformation hiprtc_information(); + +struct HiprtcCompilation { + std::vector code; + // name expression (e.g. "spherical_harmonics_kernel") -> + // mangled kernel name in the code object + std::unordered_map lowered_names; + std::string log; + int major = 0; + int minor = 0; +}; + +HiprtcCompilation compile_hip_with_hiprtc( + const std::string& source, + const std::string& source_name, + const std::vector& name_expressions, + const std::vector& options +); + +} // namespace hip +} // namespace sphericart + +#endif diff --git a/sphericart/src/sphericart_hip.cpp b/sphericart/src/sphericart_hip.cpp new file mode 100644 index 000000000..d1b21f6b6 --- /dev/null +++ b/sphericart/src/sphericart_hip.cpp @@ -0,0 +1,298 @@ +#include + +#include + +#define _SPHERICART_INTERNAL_IMPLEMENTATION + +#include "hip_base.hpp" +#include "sphericart_hip.hpp" +#include "templates.hpp" +#include "hiprtc_lite.hpp" + +using namespace sphericart::hip; + +/* + This code checks whether the HIP runtime and the runtime compilation + library we need are available on the host. The HIP runtime is a link-time + dependency of this backend, while libhiprtc is resolved dynamically at + runtime (the mechanism ported from symmetrix-xl's HIP backend). +*/ + +static void checkHip() { + int device_count = 0; + hipError_t status = hipGetDeviceCount(&device_count); + if (status != hipSuccess) { + throw std::runtime_error( + std::string("Failed to initialize the HIP runtime: ") + hipGetErrorString(status) + ); + } + if (device_count < 1) { + throw std::runtime_error( + "No HIP devices are available in a usable state. Check that the " + "AMD GPU is visible to the ROCm runtime." + ); + } + + auto hiprtc = sphericart::hip::hiprtc_information(); + if (!hiprtc.available) { + throw std::runtime_error( + "Failed to load libhiprtc.so, which is required to compile " + "sphericart's HIP kernels at runtime. Set SPHERICART_HIPRTC_LIBRARY " + "to the full path of libhiprtc.so, or append the directory " + "containing this library (e.g. /opt/rocm/lib) to your " + "$LD_LIBRARY_PATH environment variable. (" + + hiprtc.reason + ")" + ); + } +} + +template SphericalHarmonics::SphericalHarmonics(size_t l_max) { + /* + This is the constructor of the SphericalHarmonics class. It initializes + buffer space, compute prefactors, and sets the function pointers that are + used for the actual calls + */ + + checkHip(); + + this->l_max = (int)l_max; + this->nprefactors = (int)(l_max + 1) * (l_max + 2); + this->normalized = true; // SphericalHarmonics class + this->prefactors_cpu = new T[this->nprefactors]; + + hipError_t status = hipGetDeviceCount(&this->device_count); + if (status != hipSuccess) { + throw std::runtime_error( + std::string("Failed to get the number of HIP devices: ") + hipGetErrorString(status) + ); + } + + // compute prefactors on host + compute_sph_prefactors((int)l_max, this->prefactors_cpu); +} + +template SphericalHarmonics::~SphericalHarmonics() { + // Destructor, frees the prefactors + if (this->prefactors_cpu != nullptr) { + delete[] (this->prefactors_cpu); + this->prefactors_cpu = nullptr; + } + + /* Leave OS to cleanup due to static (de-)initialisation problem with sphericart-jax. + if (this->prefactors_hip) { + hipFree(this->prefactors_hip); + } + */ +} + +template +void SphericalHarmonics::compute_internal( + const T* xyz, + const size_t n_samples, + bool compute_with_gradients, + bool compute_with_hessian, + T* sph, + T* dsph, + T* ddsph, + void* hip_stream, + bool synchronize +) { + if (n_samples == 0) { + // nothing to compute; we return here because some libraries (e.g. torch) + // seem to use nullptrs for tensors with 0 elements + return; + } + + if (sph == nullptr) { + throw std::runtime_error( + "sphericart::hip::SphericalHarmonics::compute expected " + "sph ptr initialised, instead nullptr found. Initialise " + "sph with hipMalloc." + ); + } + + if (compute_with_gradients && dsph == nullptr) { + throw std::runtime_error( + "sphericart::hip::SphericalHarmonics::compute expected " + "dsph != nullptr since compute_with_gradients = true. " + "initialise dsph with hipMalloc." + ); + } + + if (compute_with_hessian && ddsph == nullptr) { + throw std::runtime_error( + "sphericart::hip::SphericalHarmonics::compute expected " + "ddsph != nullptr since compute_with_hessian = true. " + "initialise ddsph with hipMalloc." + ); + } + + hipPointerAttribute_t attributes; + + hipError_t status = hipPointerGetAttributes(&attributes, xyz); + if (status != hipSuccess) { + throw std::runtime_error( + std::string( + "sphericart::hip::SphericalHarmonics::compute could not " + "resolve the device of the input pointer: " + ) + + hipGetErrorString(status) + ); + } + + int current_device; + + status = hipGetDevice(¤t_device); + if (status != hipSuccess) { + throw std::runtime_error(std::string("hipGetDevice failed: ") + hipGetErrorString(status)); + } + + if (this->bound_device >= 0 && this->bound_device != attributes.device) { + throw std::runtime_error( + "sphericart HIP calculator device migration is unsupported; the calculator is bound " + "to its first device" + ); + } + if (current_device != attributes.device) { + status = hipSetDevice(attributes.device); + if (status != hipSuccess) { + throw std::runtime_error( + std::string("hipSetDevice failed: ") + hipGetErrorString(status) + ); + } + } + + if (!this->prefactors_hip) { + status = hipMalloc((void**)&this->prefactors_hip, this->nprefactors * sizeof(T)); + if (status != hipSuccess) { + throw std::runtime_error(std::string("hipMalloc failed: ") + hipGetErrorString(status)); + } + this->bound_device = attributes.device; + + status = hipMemcpy( + this->prefactors_hip, + this->prefactors_cpu, + this->nprefactors * sizeof(T), + hipMemcpyHostToDevice + ); + if (status != hipSuccess) { + throw std::runtime_error(std::string("hipMemcpy failed: ") + hipGetErrorString(status)); + } + } + + sphericart::hip::spherical_harmonics_hip_base( + xyz, + n_samples, + this->prefactors_hip, + this->nprefactors, + this->l_max, + this->normalized, + this->HIP_GRID_DIM_X_, + this->HIP_GRID_DIM_Y_, + compute_with_gradients, + compute_with_hessian, + sph, + dsph, + ddsph, + hip_stream, + synchronize + ); + + if (current_device != attributes.device) { + status = hipSetDevice(current_device); + if (status != hipSuccess) { + throw std::runtime_error( + std::string("hipSetDevice failed: ") + hipGetErrorString(status) + ); + } + } +} + +template +void SphericalHarmonics::compute(const T* xyz, const size_t n_samples, T* sph, void* hip_stream) { + SphericalHarmonics::compute_internal( + xyz, n_samples, false, false, sph, nullptr, nullptr, hip_stream, true + ); +} + +template +void SphericalHarmonics::compute_with_gradients( + const T* xyz, const size_t n_samples, T* sph, T* dsph, void* hip_stream +) { + SphericalHarmonics::compute_internal( + xyz, n_samples, true, false, sph, dsph, nullptr, hip_stream, true + ); +} + +template +void SphericalHarmonics::compute_with_gradients_async( + const T* xyz, const size_t n_samples, T* sph, T* dsph, void* hip_stream +) { + SphericalHarmonics::compute_internal( + xyz, n_samples, true, false, sph, dsph, nullptr, hip_stream, false + ); +} + +template void SphericalHarmonics::release_device_resources() { + if (this->prefactors_hip == nullptr) { + return; + } + + if (this->bound_device < 0) { + throw std::runtime_error("sphericart HIP calculator has no bound device"); + } + + int current_device; + hipError_t status = hipGetDevice(¤t_device); + if (status != hipSuccess) { + throw std::runtime_error(std::string("hipGetDevice failed: ") + hipGetErrorString(status)); + } + + const bool restore_device = current_device != this->bound_device; + if (restore_device) { + status = hipSetDevice(this->bound_device); + if (status != hipSuccess) { + throw std::runtime_error( + std::string("hipSetDevice failed: ") + hipGetErrorString(status) + ); + } + } + + const hipError_t free_status = hipFree(this->prefactors_hip); + if (free_status == hipSuccess) { + this->prefactors_hip = nullptr; + } + hipError_t restore_status = hipSuccess; + if (restore_device) { + restore_status = hipSetDevice(current_device); + } + if (free_status != hipSuccess) { + throw std::runtime_error(std::string("hipFree failed: ") + hipGetErrorString(free_status)); + } + if (restore_status != hipSuccess) { + throw std::runtime_error( + std::string("hipSetDevice failed: ") + hipGetErrorString(restore_status) + ); + } +} + +template +void SphericalHarmonics::compute_with_hessians( + const T* xyz, const size_t n_samples, T* sph, T* dsph, T* ddsph, void* hip_stream +) { + SphericalHarmonics::compute_internal( + xyz, n_samples, true, true, sph, dsph, ddsph, hip_stream, true + ); +} + +template +SolidHarmonics::SolidHarmonics(size_t l_max) : SphericalHarmonics(l_max) { + this->normalized = false; // SolidHarmonics class +} + +// instantiates the SphericalHarmonics and SolidHarmonics classes +// for basic floating point types +template class sphericart::hip::SphericalHarmonics; +template class sphericart::hip::SphericalHarmonics; +template class sphericart::hip::SolidHarmonics; +template class sphericart::hip::SolidHarmonics; diff --git a/sphericart/src/sphericart_impl.cu b/sphericart/src/sphericart_impl.cu index 12c4dd2c9..8ba014fea 100644 --- a/sphericart/src/sphericart_impl.cu +++ b/sphericart/src/sphericart_impl.cu @@ -5,8 +5,13 @@ #define HARDCODED_LMAX 1 -/* MASK used for warp reductions */ +/* MASK used for warp reductions. HIP shuffles require the mask to be a 64-bit + integer, while CUDA uses a 32-bit one. */ +#ifdef __HIP_PLATFORM_AMD__ +#define FULL_MASK 0xffffffffffffffffULL +#else #define FULL_MASK 0xffffffff +#endif /* Computes the index for buffer values which are shared across GRID_DIM_Y diff --git a/sphericart/tests/CMakeLists.txt b/sphericart/tests/CMakeLists.txt index 1f84f942c..52562f78b 100644 --- a/sphericart/tests/CMakeLists.txt +++ b/sphericart/tests/CMakeLists.txt @@ -18,6 +18,21 @@ if (SPHERICART_ENABLE_SYCL) target_compile_features(test_derivatives_sycl PRIVATE cxx_std_17) endif() + +if (SPHERICART_ENABLE_HIP) + add_executable(test_derivatives_hip test_derivatives_hip.cpp) + target_link_libraries(test_derivatives_hip sphericart ${ROCM_HIP_LIBRARY}) + target_include_directories(test_derivatives_hip PRIVATE ${ROCM_HIP_INCLUDE_DIR}) + target_compile_definitions(test_derivatives_hip PRIVATE __HIP_PLATFORM_AMD__=1) + target_compile_features(test_derivatives_hip PRIVATE cxx_std_17) + + add_executable(test_hip_async test_hip_async.cpp) + target_link_libraries(test_hip_async sphericart ${ROCM_HIP_LIBRARY}) + target_include_directories(test_hip_async PRIVATE ${ROCM_HIP_INCLUDE_DIR}) + target_compile_definitions(test_hip_async PRIVATE __HIP_PLATFORM_AMD__=1) + target_compile_features(test_hip_async PRIVATE cxx_std_17) +endif() + if (NOT WIN32) add_test(NAME test_hardcoding COMMAND ./test_hardcoding) endif() @@ -26,3 +41,7 @@ add_test(NAME test_derivatives COMMAND ./test_derivatives) if (SPHERICART_ENABLE_SYCL) add_test(NAME test_derivatives_sycl COMMAND ./test_derivatives_sycl) endif() +if (SPHERICART_ENABLE_HIP) + add_test(NAME test_derivatives_hip COMMAND ./test_derivatives_hip) + add_test(NAME test_hip_async COMMAND ./test_hip_async) +endif() diff --git a/sphericart/tests/test_derivatives_hip.cpp b/sphericart/tests/test_derivatives_hip.cpp new file mode 100644 index 000000000..d13d3baa1 --- /dev/null +++ b/sphericart/tests/test_derivatives_hip.cpp @@ -0,0 +1,353 @@ +/** @file test_derivatives_hip.cpp + * @brief Tests the HIP backend derivatives using finite differences + */ + +#include +#include +#include +#include +#include + +#include "hip_base.hpp" +#include "sphericart_hip.hpp" + +#ifndef DTYPE +#define DTYPE double +#endif +#define DELTA 1e-4 +#define TOLERANCE 1e-4 // High tolerance: finite differences are inaccurate for second derivatives + +#include "sphericart.hpp" + +#define CHECK_HIP(call) \ + do { \ + hipError_t status_ = (call); \ + if (status_ != hipSuccess) { \ + std::cout << "HIP error at " << __FILE__ << ":" << __LINE__ << ": " \ + << hipGetErrorString(status_) << std::endl; \ + std::exit(1); \ + } \ + } while (0) + +template T* hip_malloc(size_t count) { + T* ptr = nullptr; + CHECK_HIP(hipMalloc(&ptr, count * sizeof(T))); + return ptr; +} + +template void hip_copy_to_device(T* dst, const T* src, size_t count) { + CHECK_HIP(hipMemcpy(dst, src, count * sizeof(T), hipMemcpyHostToDevice)); +} + +template void hip_copy_to_host(T* dst, const T* src, size_t count) { + CHECK_HIP(hipMemcpy(dst, src, count * sizeof(T), hipMemcpyDeviceToHost)); +} + +template