I've found that compiling Stan models is kind of slow, and I'm often recompiling the same model "to avoid crashing R session". It seems like ccache would be a great solution here -- I could cache the result of compilation, can R could reload the compiled object as necessary.
However, ccache isn't able to return the cached results because rstan::stan_model
is creating temporary C++ files with different names. Is there any way to have stan_model
use the same C++ filename? Or is there a better way to cache compilation?
This comment in the rstan code makes it seem like caching could be possible.
model_code <- brms::make_stancode(
count ~ zAge + zBase * Trt + (1 | patient),
data = brms::epilepsy, family = "poisson"
)
cpp1 <- rstan::stanc(model_code=model_code, model_name="my_model", obfuscate_model_name=FALSE)
cpp2 <- rstan::stanc(model_code=model_code, model_name="my_model", obfuscate_model_name=FALSE)
# The content of the C++ code is identical
identical(cpp1, cpp2)
#> TRUE
m1 <- rstan::stan_model(stanc_ret=cpp1, auto_write=FALSE, save_dso=FALSE, verbose=TRUE)
#> Compilation argument:
#> /usr/lib/R/bin/R CMD SHLIB file1b4dc0286e.cpp 2> file1b4dc0286e.cpp.err.txt
m2 <- rstan::stan_model(stanc_ret=cpp1, auto_write=FALSE, save_dso=FALSE, verbose=TRUE)
#> Compilation argument:
#> /usr/lib/R/bin/R CMD SHLIB file1b4d61eb0c7.cpp 2> file1b4d61eb0c7.cpp.err.txt
System details:
Ubuntu, R 4.0, gcc 9.3.0, ccache 3.7.7.
ccache has its default settings, except for hash_dir=false
and compression=true
.
Footnote: Why not use auto_write=TRUE
? It's possible I'm doing things wrong, but in the models I've run this doesn't prevent recompilation.