Skip to content

Add cmake as the default for building stan math's tests - #3463

Open
SteveBronder wants to merge 21 commits into
developfrom
cmake-math
Open

SteveBronder wants to merge 21 commits into
developfrom
cmake-math

Conversation

@SteveBronder

Copy link
Copy Markdown
Collaborator

Summary

This is my new take on having a cmake scheme. It imports a lot of what I did in #3068. This is the nth time we have attempted to make a cmake scheme for our build setup, but this time, I feel good about it! I've made many smaller PRs to try to get the math library ready for this, so now instead of 100k+ changes we have about 1K+ changes.

Since this is rather new for stan developers the readme.md has a big intro for how to use the new cmake backend. After a few releases I will put that in the normal docs page. But while we are moving to using this new tool I think it is better we are very verbose in showing people how to use it.

Tests

./runTests.py and jenkins now use the cmake backend.

The cmake creates folder level test executables and individual test executables.

The folder level tests are much faster to compile now. For example the test/unit/math/mix/fun tests all compile into one object file which took about 30 minutes on my machine using 24 cores (and at max about 65 gb of memory). On develop these take about an hour and a half on my machine.

Side Effects

Yes. I mean this is a pretty big change.

One really nice change is that we have precompiled headers with this. That should speed up test compilation. In another PR I am planning to do some tricks with the distribution tests which should speed compilation for those by a good bit.

Release notes

Add cmake as the build backend

Checklist

  • Copyright holder: Simons Foundation

    The copyright holder is typically you or your assignee, such as a university or company. By submitting this pull request, the copyright holder is agreeing to the license the submitted work under the following licenses:
    - Code: BSD 3-clause (https://opensource.org/licenses/BSD-3-Clause)
    - Documentation: CC-BY 4.0 (https://creativecommons.org/licenses/by/4.0/)

  • the basic tests are passing

    • unit tests pass (to run, use: ./runTests.py test/unit)
    • header checks pass, (make test-headers)
    • dependencies checks pass, (make test-math-dependencies)
    • docs build, (make doxygen)
    • code passes the built in C++ standards checks (make cpplint)
  • the code is written in idiomatic C++ and changes are documented in the doxygen

  • the new changes are tested

Import and modernize the CMake setup for current vendored dependencies. Use CMake by default in runTests.py, group directory tests into executables, reuse per-source objects and PCH, and cap build parallelism at six jobs.

Migrate Jenkins test stages, document the workflow, and ignore CMake build trees. Fix shared test helper linkage, Eigen fixture initialization, and the Bernoulli GLM invalid-label fixture; suppress GCC column-tracking notes.

Validation: 21 runner, selection, and CMake build regression checks passed. Previously validated reverse and primitive function groups, generated probability and expression tests, and object reuse across test selections.
@SteveBronder

Copy link
Copy Markdown
Collaborator Author

Note this is not ready for a review yet. I think once all of the jenkins passes it will be good to look at

@WardBrian

Copy link
Copy Markdown
Member

Exciting!
(as an aside, it would be great if all the little inline changes etc to the hpps got moved to their own PR before this was ready to review!)

@SteveBronder

Copy link
Copy Markdown
Collaborator Author

Yes I was fingers crossed those would not be necessary, but it is much much less than the last time 😆 . So I'll make a PR for those once all the tests pass here

Keep grouped thread-pool tests independent of singleton initialization and restore thread-count environments. Match Windows UCRT and ARM definitions across TBB and consumers, disable broken Clang 9/10 PCH use, and validate varmat build setup before classifying signatures.

Scope the old GoogleTest policy minimum and allow OpenCL header checks without a loader while retaining executable link requirements. Move CMake runner commands into runTests.py and update Jenkins and documentation.
Remove unused declarations exposed by the Jenkins -Werror build and group
conditional callback captures without changing the derivative branches.
Forward empty softmax inputs and exercise reverse-mode segment exceptions.

Remove discarded reduction copies that consumed temporary matrix inputs.
Add regressions covering temporary inputs to all six affected factories.
@SteveBronder

Copy link
Copy Markdown
Collaborator Author

I'll have to make a stacked pr here for all of the math changes. There are a few little places that I missed.

Remove all 23 tuple captures from the OpenCL and CPU reverse callbacks.
Use direct value captures to avoid Clang 10 unused explicit-capture warnings
while keeping the original derivative bodies and callback ownership.

Verify trivial callback destruction across 23 affected test translation
units using validation-only compile-time assertions.
Link ARKODE for the new ODE wrappers and mirror Make's Windows math
constant definition. Pair symmetric finite differences before weighting
to avoid FMA cancellation noise without relaxing test tolerances.

Keep MPI command registration objects in every test executable and use
Stan's test flags for its customized GoogleTest main.

Validated on the exact CI merge: 11 numerical/ODE executables and five
MPI executables pass. The gradient suite also passes with Clang 10 and
-Werror; Windows definition propagation and CMake 4 configuration checked.
Remove the unused capture and two profiling-test variables rejected by
Clang 10. Pair symmetric fixed-step
finite differences before weighting to cancel constant terms, with
constant-function and analytic-polynomial regressions.

Use absolute bounds for zero-valued matrix sums and solver finite
differences, and verify the degenerate solver's analytic gradient
independently. Preserve public APIs and thread-pool initialization.

Validated all 20 Jenkins threading executables with Clang 10 and -Werror,
seven numerical suites with FMA enabled for C and C++, and ten shuffled
grouped-core repetitions each with threading on and off.
runPod supplies PARALLEL in the container environment, while the Groovy
env lookup fell back to one. Resolve it through sh and reuse that count
for CMake builds and CTest. Apply the same lookup to header and doxygen
builds, retaining the default of one and explicit serial test overrides.

Validated the old failure and repaired commands with a Groovy harness
that separates the controller binding from the container shell environment.
Checked unset, empty, four, six, and nonpositive values, plus serial test
overrides. All eight CMake command-planning tests pass.
Update standalone header checks, test executables, PCH producers, and
compile-only PCH producers to use the clearer source filename.

Verified before renaming that header targets compile ordinary ELF
objects with PCH enabled on Clang 18, without producing PCH artifacts.
After renaming, rebuilt three header checks, a test executable, and the
unit/compile-only PCH paths. The test and CMake planning checks pass.
Capture the nested arena count explicitly across GCC and Clang. Preserve
value categories when returning unit_vector_free results and remove the
remaining unused OpenCL and normal-sufficient variables.

Match Make's ARM floating-point options for Stan and SUNDIALS, honor OpenCL
header overrides, and select existing complete test aggregates so Make can
use the requested parallelism. Split Jenkins expression generation into
24 batches to fit Clang 10 compilation within its 64 GiB pod.
@andrjohns

andrjohns commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator

Would it be worth updating the vendored TBB instead of cmake-ing around it? RcppParallel recently moved up to oneTBB 2022.0, so the R-side isn't a hold-up/blocker at least

@WardBrian

Copy link
Copy Markdown
Member

Would it worth updating the vendored TBB instead of cmake-ing around it? RcppParallel recently moved up to oneTBB 2022.0, so the R-side isn't a hold-up/blocker at least

Doing this eventually is one of the main reasons we’d like CMake, but it will be hard to do for the period of time where we’d like to still support the make-only build system. I think it’s better off doing the upgrade separately (and, unfortunately, a good bit later)

@SteveBronder

Copy link
Copy Markdown
Collaborator Author

@andrjohns yes. To clarify the steps here we will be doing the following

  1. Get all of the tests working in this PR
  2. Break up all of the code fixes this PR needs into separate smaller PRs and merge those
  3. Once all tests with those changes pass on this PR, merge this PR
  4. Swap out our vendored dependencies and instead use cmake's FetchContent for getting our dependencies (keeping the same versions)
  5. Setup cmake in the other C++ repos. The weirdest one will be cmdstan which may still need a small make file for compiling models
  6. Delete our vendored versions and have each repo instead use FetchContent directly
  7. Totally remove make
  8. Upgrade our vendored versions using cmake from now on

So it is a bit of a long road, but there is a clear path. We can also start the cmake stuff in the other repos now. There is not really a stan math dependency to using cmake in the cmdstan and stan repos.

@SteveBronder
SteveBronder added this pull request to stack #3493 October 26, 2026 19:15
Add cmake/StanTest.cmake with the shared test flags, PCH creation and
test configuration, and use it for the compile test. Replace the
duplicated per-test and grouping logic in test/ and test/unit/ with
three functions: stan_add_test_binary, stan_add_gtest and
stan_add_test_group. Umbrella unit tests now get the unit_subtests
target and stan_build label, and use mpiexec only when STAN_MPI is on.

Jenkins now tests whole directories through their <prefix>_<dir>_all_tests
executables instead of building every per-file executable: expressions,
the threading unit tests on the main branch, and each test/prob
distribution directory. runTests.py gains --test-jobs to run several
executables at once, and a trailing slash in a glob selects only
directories.

Linking each distribution directory into one executable exposed name
collisions. Move the plain TESTs in twelve prob fixture headers into
the matching prim unit tests, and give four fixture classes unique
names (neg_binomial_2 ccdf_log, poisson_log, loglogistic cdf and
std_normal cdf_log). The neg_binomial_2 collision made the cdf_log
tests run the ccdf_log fixture.
Start from develop's Jenkinsfile, keeping its stages, pod sizes,
stanorg/ci:v1 image, changed-test selection and GNU parallel
distribution runs, and replace each make call and make/local setting
with CMake options passed through runTests.py:

- Add STAN_SANITIZE_ADDRESS and cpplint/test-math-dependencies
  targets, and print the build settings at configure time in place of
  make print-compiler-flags.
- Build test objects as PIC and link executables as PIE.
- runTests.py --fresh deletes CMakeCache.txt and the top-level
  CMakeFiles directory, as cmake --fresh does, so it works with the
  image's CMake 3.16. Run ctest from the build directory instead of
  using --test-dir (3.20).
- Build selected files and distribution fixtures through one
  stan_selected_tests target, since CMake's top-level Makefile builds
  separate targets one at a time.
- Accept distribution fixtures (test/prob/*/*_test.hpp) in runTests.py
  and add --configure-only. getDependencies.py lists each fixture's
  includes with the configured build's compile command instead of make.
- Keep the distribution fixtures out of prob_pch. Clang 7 runs static
  initializers from a PCH out of order, so REGISTER_TYPED_TEST_SUITE_P
  checked the suites before TYPED_TEST_P had added any tests and every
  generated test aborted.
- cpplint: pass explicit file lists like make/cpplint, since --recursive
  needs Python 3.9 and stanorg/ci:v1 has 3.8.
- varmat compatibility checks: return the result from non-static
  functions so -Wall -Werror builds have no unused variables or functions.
- Expression tests: split into 4 files per job like develop; one file per
  job ran clang out of memory.
- Add a ReleaseTesting configuration (-O1 without NDEBUG, so assertions
  stay on as in make) and make it the runTests.py default.
@stan-buildbot

Copy link
Copy Markdown
Contributor
Name Old Result New Result Ratio Performance change( 1 - new / old )
stat_comp_benchmarks/benchmarks/gp_regr/gen_gp_data.stan 0.04 0.04 1.0 0.2% faster
stat_comp_benchmarks/benchmarks/gp_regr/gp_regr.stan 0.16 0.16 1.0 0.16% faster
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.86 0.87 0.99 -1.46% slower
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.01 0.98 -2.13% slower
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.1 0.11 0.98 -2.23% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 8.1 8.02 1.01 0.98% faster
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 3.68 3.65 1.01 1.03% faster
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 32.81 33.29 0.99 -1.47% slower
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.38 0.39 0.99 -0.8% slower
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 6.78 6.8 1.0 -0.26% slower
stat_comp_benchmarks/benchmarks/sir/sir.stan 167.66 162.84 1.03 2.87% faster
stat_comp_benchmarks/benchmarks/arK/arK.stan 3.24 3.27 0.99 -0.95% slower
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.63 0.63 1.0 -0.13% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 25.84 25.04 1.03 3.09% faster
performance.compilation 381.58 391.32 0.98 -2.55% slower
Mean result: 0.9978385188375384

Jenkins Console Log
Jenkins Build Stages
Commit hash: 1dfac7ebd63e7747b7c9fe5984b0252ad312ebea

Machine information
Distributor ID:	Ubuntu
Description:	Ubuntu 20.04.3 LTS
Release:	20.04
Codename:	focal

CPU:

Architecture:                            x86_64
CPU op-mode(s):                          32-bit, 64-bit
Byte Order:                              Little Endian
Address sizes:                           52 bits physical, 57 bits virtual
CPU(s):                                  192
On-line CPU(s) list:                     0-191
Thread(s) per core:                      2
Core(s) per socket:                      48
Socket(s):                               2
NUMA node(s):                            2
Vendor ID:                               AuthenticAMD
CPU family:                              25
Model:                                   17
Model name:                              AMD EPYC 9474F 48-Core Processor
Stepping:                                1
Frequency boost:                         enabled
CPU MHz:                                 1497.678
CPU max MHz:                             4114.4229
CPU min MHz:                             1500.0000
BogoMIPS:                                7189.39
Virtualization:                          AMD-V
L1d cache:                               3 MiB
L1i cache:                               3 MiB
L2 cache:                                96 MiB
L3 cache:                                512 MiB
NUMA node0 CPU(s):                       0-47,96-143
NUMA node1 CPU(s):                       48-95,144-191
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Old microcode:             Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Mitigation; Safe RET
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; Enhanced / Automatic IBRS; IBPB conditional; STIBP always-on; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Mitigation; Clear CPU buffers
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Mitigation; IBPB before exit to userspace
Flags:                                   fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good amd_lbr_v2 nopl xtopology nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba perfmon_v2 ibrs ibpb stibp ibrs_enhanced vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local user_shstk avx512_bf16 clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin cppc arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif x2avic v_spec_ctrl vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq la57 rdpid overflow_recov succor smca fsrm flush_l1d debug_swap

G++:

g++ (Ubuntu 9.4.0-1ubuntu1~20.04) 9.4.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Clang:

clang version 10.0.0-4ubuntu1 
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin

@WardBrian

Copy link
Copy Markdown
Member

Latest jenkins run looks pretty good, do you want to split off the c++ changes necessary for this and maybe look into breaking up the mix tests into multiple batches before review?

@SteveBronder

Copy link
Copy Markdown
Collaborator Author

Yes I'm going to need to make a good few number of stacked PRs. I'd like this PR to be just cmake and nothing else

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants