paul-buerkner / brms

brms R package for Bayesian generalized multivariate non-linear multilevel models using Stan
https://paul-buerkner.github.io/brms/
GNU General Public License v2.0
1.28k stars 187 forks source link

Use draws from pathfinder posterior as inits #1662

Open StaffanBetner opened 6 months ago

StaffanBetner commented 6 months ago

The latest cmdstanr supports using (random draws from) a previous fit as inits. This is especially useful when using pathfinder to initialize HMC. It would be useful to have it in brms as well, either by providing a previous stanfit object or by specifying "pathfinder" as the init argument.

StaffanBetner commented 6 months ago

A simple workaround:

brm_pathfinder_inits <- function(...){
  brm(empty = T, ...) -> 
    brm_empty

  cmdstanr::write_stan_file(brm_empty$model) %>% 
    cmdstan_model(cpp_options = list(stan_threads = TRUE)) -> 
    model_cmdstan

  model_cmdstan$pathfinder(data = make_standata(...), 
                           init = 2, 
                           history_size = 100, 
                           num_threads = list(...)$cores, 
                           num_paths = list(...)$chains) ->
    pathfinder_inits

  brm(init = pathfinder_inits, ...) ->
    output_pathfinder_inits

  return(output_pathfinder_inits)
}

EDIT: Updated the code a little bit, and the instability seems to be fixed by https://github.com/stan-dev/cmdstanr/pull/993