Reason for STAN RuntimeError: Initiation failed

Hi, I am new to STAN (pystan) and ran into this problem. The codes look reasonable but the error message doesn’t seem to help much. Would you be able to take a look for me?

Thank you so much!
Xiaolong

import pandas as pd
import numpy as np
from random import choices

import stan

import nest_asyncio
nest_asyncio.apply()

### formulate data dictionary

model_data = {}
model_data[‘Subject’] = list(range(1,11))+choices(range(1,11), k=10) ### subject id, to be used as index set as an array
model_data[‘N_obs’]=len(model_data[‘Subject’])
model_data[‘N’]=len(set(model_data[‘Subject’]))
model_data[‘y’] =np.random.normal(20., 4., model_data[‘N_obs’])

model = """
data {
    int<lower=0> N_obs;    // number of NSAA observations
    vector[N_obs] y;        // NSAA observations
    
    int<lower=0> N;    // number of unique subjects
    int Subject[N_obs] ;     // subject id
    
    int<lower=0> n_arms;    // number of treatments
    int treatment[N_obs] ;     // treatment id
    
    int<lower=0> K;    // number of different visits
    int Visit[N_obs] ;     // subject visit number, to be used as index
}
parameters {
    vector<lower=0>[K] beta_k;   //  visit k decline
    vector<lower=0>[N_obs] sigma;   //  measurement error
    real<lower=0> sigma_beta;
    vector[N] beta_s;     //  subject NSAA change slope
   
}
transformed parameters {
    vector<lower=0>[K] cumbeta_k;
    vector[N_obs] mu ;
    
    
    cumbeta_k=cumulative_sum(beta_k);
    for (n in 1:N_obs) {
        mu[n]=beta_s[Subject[n]]*cumbeta_k[Visit[n]];
                        }
                        }
model {
    beta_k ~ normal(0., 4.); // visit decline
    sigma_beta ~ uniform(0., 2.) ;
    beta_s ~ gamma(1./(sigma_beta*sigma_beta), 1./(sigma_beta*sigma_beta));
// get NSAA data                     
    sigma ~ uniform(0., 20.) ;  
    y ~ normal(mu, sigma);
}
"""
posterior = stan.build(model, data=model_data, random_seed=1) ### runs fine
fit = posterior.sample(num_chains=4, num_samples=1000) ### have problem

Error message:

Sampling: 0%Sampling: Initialization failed.

RuntimeError Traceback (most recent call last)
in
----> 1 fit = posterior.sample(num_chains=4, num_samples=1000)

~/anaconda3/lib/python3.8/site-packages/stan/model.py in sample(self, num_chains, **kwargs)
87
88 “”"
—> 89 return self.hmc_nuts_diag_e_adapt(num_chains=num_chains, **kwargs)
90
91 def hmc_nuts_diag_e_adapt(self, *, num_chains=4, **kwargs) → stan.fit.Fit:

~/anaconda3/lib/python3.8/site-packages/stan/model.py in hmc_nuts_diag_e_adapt(self, num_chains, **kwargs)
106 “”"
107 function = “stan::services::sample::hmc_nuts_diag_e_adapt”
→ 108 return self._create_fit(function=function, num_chains=num_chains, **kwargs)
109
110 def fixed_param(self, *, num_chains=4, **kwargs) → stan.fit.Fit:

~/anaconda3/lib/python3.8/site-packages/stan/model.py in _create_fit(self, function, num_chains, **kwargs)
309
310 try:
→ 311 return asyncio.run(go())
312 except KeyboardInterrupt:
313 return # type: ignore

~/anaconda3/lib/python3.8/site-packages/nest_asyncio.py in run(future, debug)
30 loop = asyncio.get_event_loop()
31 loop.set_debug(debug)
—> 32 return loop.run_until_complete(future)
33
34 if sys.version_info >= (3, 6, 0):

~/anaconda3/lib/python3.8/site-packages/nest_asyncio.py in run_until_complete(self, future)
68 raise RuntimeError(
69 ‘Event loop stopped before Future completed.’)
—> 70 return f.result()
71
72 def _run_once(self):

~/anaconda3/lib/python3.8/asyncio/futures.py in result(self)
176 self.__log_traceback = False
177 if self._exception is not None:
→ 178 raise self._exception
179 return self._result
180

~/anaconda3/lib/python3.8/asyncio/tasks.py in __step( ***failed resolving arguments*** )
278 # We use the `send` method directly, because coroutines
279 # don’t have `__iter__` and `__next__` methods.
→ 280 result = coro.send(None)
281 else:
282 result = coro.throw(exc)

~/anaconda3/lib/python3.8/site-packages/stan/model.py in go()
233 sampling_output.clear()
234 sampling_output.write_line(“Sampling: Initialization failed.”)
→ 235 raise RuntimeError(“Initialization failed.”)
236 raise RuntimeError(message)
237

RuntimeError: Initialization failed.

I like to keep things in Python. I tried Tensorflow Probability before. The model seemed working but it was too slow. That’s why I tried to explore Pystan, which showed current problem.

It’s a simplified repeated data modeling, where each subject has possibly multiple observations but all of them have subject specific mean(i.i.d. from a gamma).

The error message seemed related to nest_asyncio package. Would appreciate anyone can comment on this.

Thanks,
Xiaolong

“Initialization failed” indicates that your model is mis-specified. the sampler is trying to choose a set of initial values for the model parameters in the range of -2, 2, and failing.

an alternative Python interface is CmdStanPy - you might try this instead.