Rstan session aborted for Mac OS

Hi everyone

I’m also getting “R session Aborted R encountered a fatal error” on my Mac OS repeatedly…

My code is quite complicated… I have Stan models in one function and use that function in a for loop… After several successful samplings, I’ll encounter this “R session aborted” issue and everything is gone…

Here is my codes: https://github.com/yup958/BOISE.git

And this is how I encounter the problem:

set.seed(2154)
library(rstan)
options(mc.cores = parallel::detectCores())
rstan_options(auto_write = TRUE)
load(“BOISE_test1.RData”)
source(“dpmm.R”)
source(“pel1.R”)

high_hit = which(apply(dat,2,sum)>15)
clust1 = sample(which(cl$C == 1), 16)
clust2 = sample(which(cl$C == 2), 8)
clust3 = sample(which(cl$C == 3), 8)
subdat = dat[c(clust1,clust2,clust3), high_hit]
cl = dpmm(subdat,a = 2, aux = 2, iter = 100)
pel_value = rep(0, length(high_hit))
for (i in 1:20) {
A = i
nA = 1
nT = 2
pel_value[i] = pel1(A, nA, nT, cl, subdat)
}

Everything is fine except for the last step… After 2-4 iterations this issue will happen…

I was thinking this may be caused by RAM excess but I don’t know how to get rid of it… Can anyone help me out? Thanks a lot!

You either have to avoid reloading the shared object or slow the loop down with something like a Sys.sleep(5).

Thanks!
Sorry I don’t really get what do you mean by “avoid reloading the shared object”… How can I achieve that?

Calling stan or sampling from inside a function often means that it reloads the compiled shared object from the disk repeatedly. The usual solution is to compile it once in the global environment and then call sample from inside the loop. But you may need to slow the loop down anyway.

Thanks! The problem is solved by using a larger dataset, which forces MCMC to run slower than previous (10-20 seconds instead of <1 second).
But use Sys.sleep(5) doesn’t really help, no matter I use it within loop or after each sampling, it always crashes.
I also tried to stop parallel computing and only use 1 core but it didn’t help…