diff --git a/.github/workflows/cpu-portability.yml b/.github/workflows/cpu-portability.yml new file mode 100644 index 0000000..1673a5f --- /dev/null +++ b/.github/workflows/cpu-portability.yml @@ -0,0 +1,73 @@ +name: CPU portability + +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +jobs: + cpu: + name: ${{ matrix.name }} + strategy: + fail-fast: false + matrix: + include: + - name: Linux x86_64 + os: ubuntu-24.04 + arch: x86_64 + - name: macOS arm64 + os: macos-15 + arch: arm64 + runs-on: ${{ matrix.os }} + timeout-minutes: 20 + defaults: + run: + shell: bash + env: + OMP_NUM_THREADS: '2' + OPENBLAS_NUM_THREADS: '1' + VECLIB_MAXIMUM_THREADS: '1' + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: '3.12' + - name: Install build dependencies + run: | + test "$(uname -m)" = '${{ matrix.arch }}' + if [[ "$RUNNER_OS" == macOS ]]; then + brew install cmake libomp openblas + else + sudo apt-get update + sudo apt-get install -y cmake make g++ libopenblas-dev + fi + python -m venv .venv + .venv/bin/python -m pip install -r python/tests/requirements-cpu.txt + - name: Build CPU and GRIB executables + run: | + if [[ "$RUNNER_OS" == macOS ]]; then + omp_prefix="$(brew --prefix libomp)" + blas_prefix="$(brew --prefix openblas)" + CMAKE_PREFIX_PATH="$omp_prefix:$blas_prefix" + export CMAKE_PREFIX_PATH + fi + ECCODES_HOME="$(.venv/bin/python -I -c 'import sysconfig; print(sysconfig.get_path("purelib"))')" + export ECCODES_HOME + cmake -S . -B build-ci -DVARDA_CUDA=OFF -DVARDA_GRIB=ON + cmake --build build-ci -j 2 + test -x build-ci/varda-forecast + - name: Unit tests + run: ctest --test-dir build-ci --output-on-failure + - name: Synthetic numerical parity + run: | + BIN="$PWD/build-ci" SYN_DIR="$RUNNER_TEMP/varda-synthetic" \ + bash tests/run_synthetic.sh cpu + - name: Repeated inference smoke test + run: | + build-ci/varda-run --model "$RUNNER_TEMP/varda-synthetic/e.model.safetensors" \ + --input "$RUNNER_TEMP/varda-synthetic/e.golden.safetensors" \ + --device cpu --precision fp32 --threads 2 --steps 3 diff --git a/CMakeLists.txt b/CMakeLists.txt index ac1896b..ed6de78 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,6 +19,11 @@ set(CMAKE_BUILD_RPATH_USE_LINK_PATH ON) find_package(OpenMP REQUIRED) set(BLA_VENDOR OpenBLAS) find_package(BLAS REQUIRED) +# Prefer OpenBLAS headers to the SDK's Accelerate cblas.h on macOS. The CPU backend +# uses OpenBLAS's thread-control API, which Accelerate's headers do not declare. +if(APPLE) + set(CMAKE_FIND_FRAMEWORK LAST) +endif() find_path(CBLAS_INCLUDE_DIR cblas.h HINTS ENV OPENBLAS_HOME PATH_SUFFIXES include include/openblas REQUIRED) # CPU numerics: no implicit FMA contraction, so element-wise code rounds like the @@ -26,7 +31,7 @@ find_path(CBLAS_INCLUDE_DIR cblas.h HINTS ENV OPENBLAS_HOME PATH_SUFFIXES includ set(VARDA_CXX_FLAGS -ffp-contract=off -Wall -Wextra -Wno-unused-parameter) if(VARDA_NATIVE) list(APPEND VARDA_CXX_FLAGS -march=native) -else() +elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64|i[3-6]86)$") list(APPEND VARDA_CXX_FLAGS -mavx2 -mfma -mf16c) endif() @@ -66,7 +71,7 @@ endif() set(VARDA_HAVE_GRIB OFF) if(VARDA_GRIB) find_path(ECCODES_INCLUDE_DIR eccodes.h HINTS ENV ECCODES_HOME PATH_SUFFIXES eccodeslib/include include) - find_library(ECCODES_LIBRARY eccodes HINTS ENV ECCODES_HOME PATH_SUFFIXES eccodeslib/lib64 lib64 lib) + find_library(ECCODES_LIBRARY eccodes HINTS ENV ECCODES_HOME PATH_SUFFIXES eccodeslib/lib64 eccodeslib/lib lib64 lib) if(ECCODES_INCLUDE_DIR AND ECCODES_LIBRARY) set(VARDA_HAVE_GRIB ON) get_filename_component(ECCODES_LIBDIR ${ECCODES_LIBRARY} DIRECTORY) @@ -74,9 +79,13 @@ if(VARDA_GRIB) add_library(varda_io STATIC ${VARDA_IO_SRC}) target_include_directories(varda_io PUBLIC ${ECCODES_INCLUDE_DIR}) target_compile_options(varda_io PRIVATE ${VARDA_CXX_FLAGS}) - # libeccodes needs eckit next to it; old-style RPATH reaches transitive dependencies. - target_link_libraries(varda_io PUBLIC varda ${ECCODES_LIBRARY} - "-Wl,--disable-new-dtags,-rpath,${ECCODES_LIBDIR}:${ECCODES_LIBDIR}/../../eckitlib/lib64") + # ELF builds use old-style RPATH to reach ecCodes' transitive eckit dependency. + # Darwin uses the normal dylib load paths instead of this GNU linker option. + target_link_libraries(varda_io PUBLIC varda ${ECCODES_LIBRARY}) + if(UNIX AND NOT APPLE) + target_link_libraries(varda_io PUBLIC + "-Wl,--disable-new-dtags,-rpath,${ECCODES_LIBDIR}:${ECCODES_LIBDIR}/../../eckitlib/lib64") + endif() else() message(WARNING "VARDA_GRIB=ON but ecCodes not found (set ECCODES_HOME): no GRIB layer") endif() diff --git a/README.md b/README.md index b5607e5..75b7b9e 100644 --- a/README.md +++ b/README.md @@ -118,6 +118,10 @@ build/varda-rollout ... # docs/ `build/varda-forecast` runs a forecast from real data (KENDA-CH1 and IFS open data in, GRIB out, as anemoi-inference does); it needs ecCodes (`-DVARDA_GRIB=ON`, `tools/env.sh`): `docs/forecast.md`. +Apple Silicon: the CPU fp32 backend builds natively on macOS arm64 with OpenMP and OpenBLAS. +Build, GRIB dependencies and verification: [docs/apple-silicon.md](docs/apple-silicon.md). +There is no Apple GPU backend; CUDA requires an NVIDIA GPU. + ## Licence and disclaimer - The code is licensed under the BSD 3-Clause License (`LICENSE`), for every version of this repository. diff --git a/apps/varda-run.cpp b/apps/varda-run.cpp index f1a602a..6d130bf 100644 --- a/apps/varda-run.cpp +++ b/apps/varda-run.cpp @@ -10,6 +10,9 @@ // Prints load time, per-step wall time, and peak RSS (VmHWM: includes the resident pages of // the mapped model and input files). --out writes the first output as `out.y`. #include +#ifdef __APPLE__ +#include +#endif #include #include @@ -27,14 +30,29 @@ namespace { std::exit(2); } -// kB value of a /proc/self/status field (VmHWM, VmRSS, RssAnon, RssFile), or -1. +// KiB value of a memory statistic, or -1 when unavailable. long proc_status_kb(const char* field) { +#ifdef __APPLE__ + if (std::string(field) == "VmHWM") { + struct rusage ru {}; + return getrusage(RUSAGE_SELF, &ru) == 0 ? ru.ru_maxrss / 1024 : -1; + } + if (std::string(field) == "VmRSS") { + mach_task_basic_info_data_t info {}; + mach_msg_type_number_t count = MACH_TASK_BASIC_INFO_COUNT; + if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO, + reinterpret_cast(&info), &count) == KERN_SUCCESS) + return static_cast(info.resident_size / 1024); + } + return -1; +#else std::ifstream f("/proc/self/status"); std::string line; const std::string want = std::string(field) + ":"; while (std::getline(f, line)) if (line.compare(0, want.size(), want) == 0) return std::atol(line.c_str() + want.size()); return -1; +#endif } } // namespace @@ -97,9 +115,14 @@ int main(int argc, char** argv) { steps > 1 ? (repeat_bitwise ? ", repeats bitwise equal" : ", REPEATS DIFFER") : ""); struct rusage ru; getrusage(RUSAGE_SELF, &ru); +#ifdef __APPLE__ + std::printf("peak RSS %.2f GB (ru_maxrss), RSS now %.2f GB\n", + ru.ru_maxrss / 1073741824.0, proc_status_kb("VmRSS") / 1048576.0); +#else std::printf("peak RSS %.2f GB (VmHWM; ru_maxrss %.2f GB), RSS now %.2f GB (anon %.2f, file %.2f)\n", proc_status_kb("VmHWM") / 1048576.0, ru.ru_maxrss / 1048576.0, proc_status_kb("VmRSS") / 1048576.0, proc_status_kb("RssAnon") / 1048576.0, proc_status_kb("RssFile") / 1048576.0); +#endif if (!out_path.empty()) { varda::write_safetensors(out_path, {{"out.y", varda::DType::F32, y_shape, y0.data()}}, diff --git a/docs/apple-silicon.md b/docs/apple-silicon.md new file mode 100644 index 0000000..67f18b2 --- /dev/null +++ b/docs/apple-silicon.md @@ -0,0 +1,72 @@ +# Apple Silicon (macOS arm64) + +The existing CPU fp32 backend runs natively on Apple Silicon using Apple Clang, +OpenMP and OpenBLAS. CUDA is NVIDIA-only; there is no Metal or MPS backend, so the +Apple GPU is not used. No model arithmetic or numerical tolerances are changed. + +## CPU build + +Install Xcode Command Line Tools and the build dependencies: + +```sh +brew install cmake libomp openblas +cmake -S . -B build-apple -DVARDA_CUDA=OFF -DVARDA_GRIB=OFF \ + -DCMAKE_PREFIX_PATH="$(brew --prefix libomp);$(brew --prefix openblas)" +cmake --build build-apple -j 4 +OMP_NUM_THREADS=8 OPENBLAS_NUM_THREADS=1 ctest --test-dir build-apple --output-on-failure +``` + +The prefix list lets CMake discover Homebrew's keg-only OpenMP and OpenBLAS +installations. The build prefers OpenBLAS's `cblas.h` over the SDK's Accelerate +header, and does not pass x86 AVX flags to the ARM compiler. `VARDA_NATIVE=ON` +remains optional for tuning to the build host. + +## GRIB build and synthetic verification + +The small test environment uses versions from the existing reference locks. It +does not need torch or Anemoi: + +```sh +uv venv --python 3.12 .venv +uv pip install --python .venv/bin/python -r python/tests/requirements-cpu.txt +export ECCODES_HOME="$(.venv/bin/python -I -c 'import sysconfig; print(sysconfig.get_path("purelib"))')" +cmake -S . -B build-apple -DVARDA_CUDA=OFF -DVARDA_GRIB=ON \ + -DCMAKE_PREFIX_PATH="$(brew --prefix libomp);$(brew --prefix openblas)" +cmake --build build-apple -j 4 +OMP_NUM_THREADS=8 OPENBLAS_NUM_THREADS=1 ctest --test-dir build-apple --output-on-failure +BIN="$PWD/build-apple" SYN_DIR="$PWD/local/synthetic" \ + OPENBLAS_NUM_THREADS=1 VECLIB_MAXIMUM_THREADS=1 bash tests/run_synthetic.sh cpu +``` + +The macOS ecCodes wheel uses `eccodeslib/lib` instead of Linux's +`eccodeslib/lib64`. Both layouts are supported. Homebrew ecCodes can also be +linked, but `test_io_link` deliberately checks the reference version, 2.47.3; +using a different version fails that check and does not establish GRIB parity. + +The synthetic suite checks all six configurations at 1 and 8 threads, plus a +different chunk size (18 checks), against an independent float64 reference with +the existing tolerances. Tests that need model checkpoints, recorded forcings, +GRIB templates or real-data dumps still skip those parts when fixtures are absent. +The CPU portability workflow runs these checks on macOS arm64 and Linux x86_64. + +## Full Varda forecasts + +Use `--device cpu --precision fp32`. The full model's measured CPU footprint on +Linux is approximately 25 GB before allowing for other applications and forecast +I/O; a 16 GB Mac is not a practical target. Synthetic parity is not a full-model +or real-data forecast qualification on macOS. In particular, macOS libm and ARM +OpenBLAS may differ in rounding from the Linux reference. + +With a prepared assets bundle, the forecast wrapper can run locally without +Slurm (see `quickstart.md` for preparing assets): + +```sh +VARDA_ENV=none VARDA_SRUN=0 VARDA_BUILD="$PWD/build-apple" \ + VARDA_SCRATCH=/path/to/scratch VARDA_ASSETS=/path/to/assets \ + ./varda forecast latest --device cpu --precision fp32 +``` + +`varda-run` reports RSS through macOS APIs and converts `ru_maxrss` from bytes; +Linux retains its `/proc` statistics and KiB conversion. Weight prefetch uses +page touching on macOS, while Linux retains `MADV_POPULATE_READ` and its existing +fallback on kernels that do not support it. diff --git a/python/tests/requirements-cpu.txt b/python/tests/requirements-cpu.txt new file mode 100644 index 0000000..b4dfc40 --- /dev/null +++ b/python/tests/requirements-cpu.txt @@ -0,0 +1,5 @@ +# Small CPU/GRIB test environment; no torch or anemoi needed for synthetic parity. +# Versions match requirements-ref-varda.lock.txt (numpy) and the real-data reference lock. +numpy==2.3.5 +eccodeslib==2.47.3.21 +eckitlib==2.1.0.21 diff --git a/src/varda/format.cpp b/src/varda/format.cpp index bacd6d4..23e7e92 100644 --- a/src/varda/format.cpp +++ b/src/varda/format.cpp @@ -16,7 +16,7 @@ #include "nlohmann/json.hpp" -#ifndef MADV_POPULATE_READ +#if defined(__linux__) && !defined(MADV_POPULATE_READ) #define MADV_POPULATE_READ 22 // Linux >= 5.14; older kernels reject it with EINVAL #endif @@ -143,17 +143,21 @@ void SafeTensorsFile::prefetch(int threads) const { threads = static_cast(std::min(static_cast(threads), n_chunks)); const size_t page = static_cast(::sysconf(_SC_PAGESIZE)); std::atomic next{0}; +#ifdef MADV_POPULATE_READ std::atomic populate{true}; +#endif auto worker = [&] { unsigned sum = 0; for (size_t c; (c = next.fetch_add(1)) < n_chunks;) { const size_t lo = c * kChunk, hi = std::min(map_size_, lo + kChunk); char* p = static_cast(map_) + lo; // lo is a multiple of kChunk: page aligned +#ifdef MADV_POPULATE_READ if (populate.load(std::memory_order_relaxed)) { if (::madvise(p, hi - lo, MADV_POPULATE_READ) == 0) continue; if (errno != EINVAL) continue; // EINTR, or an I/O error that surfaces where the bytes are read, as before populate.store(false, std::memory_order_relaxed); // kernel without it: touch the pages } +#endif const volatile unsigned char* q = reinterpret_cast(p); for (size_t o = 0; o < hi - lo; o += page) sum += q[o]; }