Pystan runtime error: initialization failed

The following Python+Stan code is analogous to Bayesian linear regression, except that the code infers a linear function that bounds ys.

import stan

stan_code = """
data {
    int<lower=0> number_inputs;
    matrix[number_inputs, 2] xs_vandermonde;
    vector[number_inputs] ys;
}
parameters {
    vector[2] coefficients;
}
model {
    coefficients ~ normal(3,6);
    for (n in 1:number_inputs) {
        if (xs_vandermonde[n] * coefficients > 0) {
            ys[n] ~ uniform(0, xs_vandermonde[n] * coefficients);
        }
        else {
            target += negative_infinity();
        }
    }
}
"""

number_inputs = 1
xs_vandermonde = [[1, 1]]
ys = [1]

data = {"number_inputs": number_inputs,
        "xs_vandermonde": xs_vandermonde, 
        "ys": ys}

posterior = stan.build(stan_code, data=data, random_seed=1)
fit = posterior.sample(num_chains=4, num_samples=1000)
df = fit.to_frame()
print(df)

The above code runs without any problems. However, if I change line 27 from ys = [1] to ys = [10], the code fails. It reports a runtime error that initialization failed.

Do you know what is going on by any chance? Because 1 works but 10 fails, I initially suspected numerical overflow in the calculation of log densities, but Iā€™m unsure. Thanks a lot!

Additional information:

  1. OS: Ubuntu 20.04
  2. Pystan: version 3.4.0
  3. Runtime error message:
Building: 25.1s, done.
Messages from stanc:
Warning in '/tmp/httpstan_lx46qdm4/model_hdn23ye4.stan', line 13, column 8: A
    control flow statement depends on parameter(s): coefficients.
Sampling: Initialization failed.
Traceback (most recent call last):
  File "debug.py", line 34, in <module>
    fit = posterior.sample(num_chains=4, num_samples=1000)
  File "/home/longpham/.local/lib/python3.8/site-packages/stan/model.py", line 89, in sample
    return self.hmc_nuts_diag_e_adapt(num_chains=num_chains, **kwargs)
  File "/home/longpham/.local/lib/python3.8/site-packages/stan/model.py", line 108, in hmc_nuts_diag_e_adapt
    return self._create_fit(function=function, num_chains=num_chains, **kwargs)
  File "/home/longpham/.local/lib/python3.8/site-packages/stan/model.py", line 311, in _create_fit
    return asyncio.run(go())
  File "/usr/lib/python3.8/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/home/longpham/.local/lib/python3.8/site-packages/stan/model.py", line 235, in go
    raise RuntimeError("Initialization failed.")
RuntimeError: Initialization failed.

Welcome!

The issue is that for at least one n, at initialization

is always less than 10. You could try initializing coefficients to larger values. A backdoor way to achieve this would be to declare coefficients with an <offset, multiplier>.

Thank you so much for your help! It solves my problem.

1 Like