wlandau / instantiate

Pre-compiled CmdStan models in R packages
https://wlandau.github.io/instantiate/
Other
22 stars 2 forks source link

`expose_functions()` method fails for pre-compiled models #21

Closed bifouba closed 6 months ago

bifouba commented 7 months ago

For a minimal example, create a generic example package:

instantiate::stan_package_create("TEST")
instantiate::stan_package_configure("TEST")

Add a basic function to the bernoulli.stan file:

functions {
  int testfun(int n){
    return(n + 1);
  }
}

Now running cmdstanr within the package directory directly works fine:

stan_mod <- cmdstanr::cmdstan_model('src/stan/bernoulli.stan', compile = TRUE)
stan_mod$expose_functions()
stan_mod$functions$testfun(1)

But the pre-compiled model doesn't allow exposing the function.

stan_mod <- instantiate::stan_package_model("bernoulli", "example")
stan_mod$expose_functions()

fails with error Error in if (function_env$existing_exe) { : argument is of length zero.

macOS 14.4.1 RStudio 2023.06.1+524 cmdstanr version 0.7.1 CmdStan version: 2.34.1 instantiate version 0.2.2

wlandau commented 6 months ago

instantiate::stan_package_model() assumes the model is already compiled, and according to https://mc-stan.org/cmdstanr/reference/model-method-expose_functions.html, you would have to recompile the model anyway. So even if you didn't see "Error in if (function_env$existing_exe) { : argument is of length zero", you would still see "Exporting standalone functions is not possible with a pre-compiled Stan model!".

To be a good fit with instantiate, those functions would need to compile at package installation time. But unfortunately, the compiled functions do not live in a persistent exe, they go away when the session restarts. If the Stan team saves those functions somewhere that cmdstanr can later find without recompilation, then I would be open to integrating this with instantiate.

bifouba commented 6 months ago

Fair enough, and I did also reach that conclusion when I went further down that rabbit hole. Having said that, please note that rstantools has begun to include that functionality (https://discourse.mc-stan.org/t/using-expose-stan-functions-in-a-package/5982/10?u=bifouba) although it's not documented yet, so it might just be a matter of time before cmdstanr does to and the question of how instantiate needs to deal with that comes up again. You can cross that bridge when you come to it, of course, just as a heads up. Thank you!