Making auto differentiation thread-safe

  • OS (Operating System): Linux
    • CXX (Compiler): g++
    • CXX_TYPE gcc
    • Compiler version: 7.7

In my program I have multiple threads running stan math’s auto differentiation (AD). As the AD is not thread-safe, I get a segfault doing so. I have read about enabling threading support but I could not make it work yet.

I created the file make/local and I added the lines

CXXFLAGS += -DSTAN_THREADS
CXXFLAGS += -pthread

What do I have to do next? Recompile Stan-Math? If so, how?

Thanks in advance!

You need to declare in each thread an instance of

stan::math::ChainableStack ad_tape;

in order to initialise the ad tape in each thread. Then it should work just as prior to 2.20.

Note that we decided to support threading via the functionals like map_rect… but I should update the wiki page you refer to.