Skip to content

Fix/aligned vari alloc - #3466

Open
SteveBronder wants to merge 6 commits into
developfrom
fix/aligned-vari-alloc
Open

SteveBronder wants to merge 6 commits into
developfrom
fix/aligned-vari-alloc

Conversation

@SteveBronder

@SteveBronder SteveBronder commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

This fixes a segfault when a reverse mode callback captures a fixed-size Eigen type, and while I was in the stack allocator I also did most of #2303.

reverse_pass_callback and make_callback_vari store the lambda's captures inside the vari, and the vari lives on our arena which only hands out 8 byte aligned memory. If you capture something like a Matrix<double, 4, 4> or a Matrix<var, 2, 1>, Eigen assumes the memory is aligned and uses aligned simd loads/stores, which can crash.

The changes are

  • stack_alloc::alloc(len, alignment = 8) replaces alloc(len). For alignment <= 8 it's the same bump pointer as before. For larger alignments it rounds up next_loc_ first.
  • alloc_array<T>(n, alignment = 8) is the array version of alloc(...)
  • vari_base gets an aligned operator new / operator delete so C++17 picks it for anything over 16 byte aligned.
  • reverse_pass_callback and make_callback_vari do placement new at memalloc_.alloc(sizeof(vari_t), alignof(vari_t)), which covers the 16 byte case too.
  • Arena blocks come from STAN_ALIGNED_ALLOC and are freed with STAN_ALIGNED_FREE. MSVC and MinGW don't have std::aligned_alloc, so on Windows these go to _aligned_malloc / _aligned_free. I don't have a Windows machine so CI is the first real test of that.

Speeding up the allocator (#2303)

In Stan we do a ton of allocations on the first gradient and after that we are pretty much always reusing memory the arena already has. So the hot path is just bump the pointer and compare. We want to use STAN_STRONG_INLINE and STAN_COLD_PATH on specific functions and constructors such that the hot path we normally run is as clear and inline as possible. This is an annoying optimization problem, but one that claude is great at. So I told claude the problem and the set of functions/constructors it could add those two macros at to find a set that will give a speedup on a given google benchmark below.

I wrote an MRE of develop and this PR's stack allocator to look at the asm.

https://godbolt.org/z/xYcrhY73T

clang is really conservative with inlining. On develop it leaves move_to_next_block() as a function call, so it has to load and store next_loc_ through memory on every allocation. Adding STAN_STRONG_INLINE to alloc(), alloc_array(), move_to_next_block(), and vari_base::operator new lets clang keep it in a register. gcc already inlines all of this so the arena is the same speed there.

I also added push_var_stack() and push_var_nochain_stack() to AutodiffStackStorage, which put the vector's grow path in a STAN_COLD_PATH function since after the first gradient the var stack basically never grows. That takes a register spill out of every vari construction on gcc.

Below is a Google Benchmark against the actual stan headers, comparing the commit this branch started from to this PR. ns per op, mean ± sd of 10 repetitions.

develop gcc PR gcc develop clang PR clang
new vari 2.94 ± 0.04 2.59 ± 0.02 2.69 ± 0.02 2.62 ± 0.01
reverse_pass_callback 2.53 ± 0.04 2.11 ± 0.03 2.35 ± 0.01 2.17 ± 0.00
alloc(24) 0.81 ± 0.01 0.76 ± 0.00 1.42 ± 0.01 0.76 ± 0.01
alloc_array<double>(n) 1.02 ± 0.02 0.70 ± 0.01 1.58 ± 0.00 1.09 ± 0.01

Going through the hot loops with perf annotate, here is where the time comes from

  • clang alloc / alloc_array: develop's loop loads next_loc_ from memory, adds to it, and stores it back, so every allocation waits on the last one's store. The PR's loop keeps next_loc_ in a register and only stores it.
  • gcc new vari: develop spills the vari pointer to the stack every iteration for the vector grow path. That grow path is now in the cold function so the spill is gone.
  • reverse_pass_callback: on gcc the placement new drops the null check that new with a noexcept operator new has to do, and the spill is gone like above. On clang, develop reloads ChainableStack::instance_ after constructing the vari to push it on the var stack, and the PR reuses the one it already loaded.
  • clang new vari: the loop is basically the same in both, clang was already inlining the vari constructor.
  • gcc alloc / alloc_array: the instructions are identical in both builds. The difference in this table is from where the loop happened to land in the binary, so I would not count it.

gcc's develop numbers also moved a few percent between runs on this shared machine (e.g. new vari was 2.75 in an earlier run), so take the gcc vari / callback numbers as roughly 5-15%.

I have a PR that turns off our auto performance testing models, but I will be pretty interested in whether they show a noticeable speedup here.

Running the benchmarks

The benchmark code and instructions for downloading and running it are in this gist. It builds the benchmark against this branch and its merge base with develop and compares them with Google Benchmark's compare.py.

Tests

New tests leave the arena 8 bytes past an aligned boundary and then capture a Vector2d, a Matrix4d, and fixed-size var matrices in reverse_pass_callback, make_callback_vari, and multiply. They all segfault on develop.

./runTests.py test/unit/math/memory/stack_alloc_test.cpp \
  test/unit/math/rev/core/callback_vari_test.cpp \
  test/unit/math/rev/core/reverse_pass_callback_test.cpp

Release notes

Fixed a crash when a reverse mode callback captures types that need more than 8 byte alignment. The arena allocator now supports aligned allocations and is faster with clang.

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

reverse_pass_callback stores its captures inside the vari, which is
allocated on the arena with 8 byte alignment. A capture that needs more,
such as a fixed-size Eigen matrix (Matrix2d needs 32 bytes), could be
misaligned and crash in vectorized code.

- stack_alloc::alloc(len, alignment) returns memory aligned to
  `alignment`. Allocations after it stay 8 byte aligned. New blocks for
  alignments over 8 come from std::aligned_alloc, and blocks are only
  reused when the aligned allocation fits.
- vari_base gains operator new(size_t, std::align_val_t), which C++17
  calls for over-aligned types, and the matching operator delete.

Known gaps: types needing exactly 16 bytes still use operator new(size_t)
(C++17 only calls the aligned overload above __STDCPP_DEFAULT_NEW_ALIGNMENT__),
and std::aligned_alloc is not available on MSVC/MinGW.
stan::math::multiply's callback captures fixed-size Eigen matrices inside
the vari, so this crashed before the aligned vari allocation.
reverse_pass_callback and make_callback_vari store the callback's captures
inside the vari. C++17 only calls vari_base's aligned operator new for
alignments above __STDCPP_DEFAULT_NEW_ALIGNMENT__ (16 on common
platforms), so a capture that needs exactly 16 bytes, e.g. a
Matrix<var, 2, 1> captured by multiply, still went through
operator new(size_t) and the 8 byte aligned arena. Copying the capture
into the misaligned vari faulted (seen in RealSchur's Francis QR step,
which multiplies fixed-size Householder vectors).

Both now place the vari at memalloc_.alloc(sizeof(vari), alignof(vari)),
which is unchanged for varis that need at most 8 bytes.

Tests capture a Vector2d (16 bytes) and a Matrix4d (32 bytes) in each
helper after leaving the arena 8 bytes past a 16 byte boundary; both
segfaulted before this change.
alloc(len) and alloc(len, alignment) are now one function. Alignments of
8 or less take the old bump-pointer fast path, which folds away at
compile time since callers pass a constant alignment; larger alignments
round up the next location and then use the same bump and block check.
The generated code for default-aligned allocations is unchanged, and
over-aligned allocations no longer do separate size arithmetic.

alloc_array also takes an alignment, and the class docs now state that
every allocation is at least 8 byte aligned.
Add STAN_STRONG_INLINE (always_inline) to compiler_attributes.hpp and use
it on the allocation fast path: stack_alloc::alloc, alloc_array,
move_to_next_block, vari_base::operator new, the scalar vari_value
constructors, reverse_pass_callback_vari and reverse_pass_callback.

With move_to_next_block inlined the compiler can keep next_loc_ and
cur_block_end_ in registers across a loop of allocations. When it is an
out of line call, clang reloads and stores them through memory on every
allocation. In a microbenchmark that reuses the arena (the steady state
after the first gradient) clang goes from 1.34 to 0.50 ns per alloc(24),
1.55 to 0.69 ns per alloc_array, and 5.6 to 3.6 ns per new vari; gcc
already inlined these and is unchanged.

Add AutodiffStackStorage::push_var_stack and push_var_nochain_stack,
which keep vector growth in a STAN_COLD_PATH function since the stacks
are reused and almost never grow. This takes a register spill out of
every vari construction with gcc (3.8 to 3.5 ns per new vari). All
direct var_stack_ and var_nochain_stack_ push_back calls now use them.

New arena blocks always come from aligned_malloc, so move_to_next_block
no longer branches on the alignment to pick an allocator.
MSVC and MinGW do not provide std::aligned_alloc. Add
STAN_ALIGNED_ALLOC(alignment, size) and STAN_ALIGNED_FREE(ptr), which use
_aligned_malloc and _aligned_free on _WIN32 and std::aligned_alloc and
std::free everywhere else.

Memory from _aligned_malloc must be released with _aligned_free, so every
arena block now comes from STAN_ALIGNED_ALLOC, including the first block
that used to come from malloc, and every block is released with
STAN_ALIGNED_FREE. eight_byte_aligned_malloc had no other users and is
removed.
@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.02 1.57% faster
stat_comp_benchmarks/benchmarks/gp_regr/gp_regr.stan 0.16 0.18 0.92 -8.76% slower
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.87 0.97 0.89 -11.98% slower
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.01 0.99 -0.74% slower
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.1 0.11 0.95 -5.38% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 7.99 8.38 0.95 -4.91% slower
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 3.67 4.03 0.91 -9.92% slower
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 33.62 33.64 1.0 -0.05% slower
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.38 0.39 0.97 -3.49% slower
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 6.85 8.16 0.84 -19.17% slower
stat_comp_benchmarks/benchmarks/sir/sir.stan 136.13 170.47 0.8 -25.23% slower
stat_comp_benchmarks/benchmarks/arK/arK.stan 3.23 3.45 0.94 -6.64% slower
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.77 0.58 1.32 24.43% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 25.23 25.38 0.99 -0.57% slower
performance.compilation 414.6 391.46 1.06 5.58% faster
Mean result: 0.9700593825610772

Jenkins Console Log
Jenkins Build Stages
Commit hash: 29e32c4215464fd5550540ce9a448016d22be56f

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.504
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 WardBrian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall this looks clear, but the cold path for growing the vector is confusing to me

Comment on lines +138 to +149
STAN_STRONG_INLINE static inline void push_back_reused(
std::vector<ChainableT *> &stack, ChainableT *vi) {
if (likely(stack.size() != stack.capacity())) {
stack.push_back(vi);
} else {
grow_and_push_back(stack, vi);
}
}

STAN_COLD_PATH static void grow_and_push_back(
std::vector<ChainableT *> &stack, ChainableT *vi) {
stack.push_back(vi);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How is this really an optimization? both sides of the if are just vector.push_back?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it relying on the compiler inlining push_back or something? If so I feel like a comment should say so

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.

4 participants