Rstan tip: prevent RStudio from locking up during model compilation

One thing that occasionally occurs for me is I start compiling a model with rstan::stan_model(), which I know should take a minute or so, and in the meantime I want to open another file only to discover that RStudio hangs until the model compilation is done. Below is a wrapper function that solves this by doing the compilation in a different process. It should otherwise behave the same as rstan::stan_model(), including showing any non-fatal warnings and errors.

build_stan = function(file){
	script_file = tempfile()
	stdout_file = tempfile()
	stderr_file = tempfile()
		args = commandArgs(trailingOnly=TRUE)
		file = args[1]
		rstan_options(auto_write = TRUE)
		mod = rstan::stan_model(file)
		, file = script_file
		command = "Rscript"
		, args = c("--vanilla",script_file,file)
		, stdout = stdout_file
		, stderr = stderr_file
		, wait = TRUE
1 Like

Oh, and a side-benefit is that irrelevant (to non-stan-devs) warnings from the lower-level libs like boost, Eigen, etc (that you’d normally have to figure out how to turn off by adding lines to your Makevars files) are suppressed.

Huh, maybe not a panacea; if you attempt to re-compile a model that’s been compiled then edited, Rstudio gets unresponsive during the compile again.

@mike-lawrence I’ve had luck using {future} to compile the model off on a parallel process without losing the ability to be interactive in RStudio while I wait. This was using multicore on an OS that supports forking and RStudio Server. YMMV. Note that {future} also supports plan(multiprocess) which tries to do multicore but falls back to multisession (i.e. PSOCK/snow like cluster).

scode <- "
parameters {
  real y[2]; 
model {
  y[1] ~ normal(0, 1);
  y[2] ~ double_exponential(0, 2);
fit1 %<-% stan(model_code = scode, iter = 10, verbose = FALSE) 

If you call fit1 before the compilation and other work is done, things may lock up, but that hasn’t been my experience.

P.S. Big fan of {ez}, it really helped me cut my teeth in R when I first started.


We’ve really got to get those compilation times down!

1 Like