Saving Stan models in rds format

I’m checking a colleague’s code, and I noticed that they save files using this weird method which I have never seen before. I was told this was suggested by one of the Stan developers but the author of the code has forgotten why this approach to saving models is needed. I was under the impression that the model is saved automatically as an .rds file in the directory where the .stan model lives. So using saveRDS is redundant, isn’t it?

M1a_orig <- stan(file = “stan/Model1a.stan”,
data = crit_orig_M1a,
iter = 2000,
chains = 4)

write model to file

M1a_orig@stanmodel@dso <- new(“cxxdso”)
saveRDS(M1a_orig, file = “models/M1a_orig.rds”)

Msny thanks,

Shravan

This is just clearing out the reference to the binary s.t. R doesn’t try to load it when the saved object is loaded. IIRC sometimes loading a stale rstan object would crash or throw errors (?). The second step is just saving an R object.

Whether the object is saved automatically depends on you options.

Right, I meant that once I have set it up to save automatically, I should be able to load using readRDS. Given such a setup, these steps seem redundant correct?

This line is removing a slot prior to saving so you don’t save the model binary, that’s different than the automatic save. This way you could load the object (and samples) on another computer without crashing anything, although I don’t know that it’s relevant anymore.

Yeah, the one that gets saved automatically is only viable on that particular computer. If you want to send a stanmodel to someone else, then it is best to either specify save_dso = FALSE when you call stan_model or clear the cxxdso out. But whoever you are sending the stanmodel to is not going to be able to do much of anything with it, except print out the Stan program. So, I would say yes it is largely redundant.