Working .stan Script Fails to Compile with PyStan

I’m attempting to build a pystan model (multilevel ordered logit) using a .stan script that previously compiled, with the only difference being the addition of whitespace (I need to make additional edits, and the issue is recurring, so I’m not able to simply revert). When I run stan.build(script, data = stan_data) (OS: macOS Montrey 12.4, pystan 3.5.0, python 3.9.12, anaconda 4.12.0), I’m thrown:

Building...
Error handling request
Traceback (most recent call last):
  File "/Users/bennett/opt/anaconda3/lib/python3.9/site-packages/aiohttp/web_protocol.py", line 435, in _handle_request
    resp = await request_handler(request)
  File "/Users/bennett/opt/anaconda3/lib/python3.9/site-packages/aiohttp/web_app.py", line 504, in _handle
    resp = await handler(request)
  File "/Users/bennett/opt/anaconda3/lib/python3.9/site-packages/httpstan/views.py", line 103, in handle_create_model
    _, stanc_warnings = httpstan.compile.compile(program_code, stan_model_name)
  File "/Users/bennett/opt/anaconda3/lib/python3.9/site-packages/httpstan/compile.py", line 37, in compile
    completed_process = subprocess.run(run_args, capture_output=True, timeout=1)
  File "/Users/bennett/opt/anaconda3/lib/python3.9/subprocess.py", line 507, in run
    stdout, stderr = process.communicate(input, timeout=timeout)
  File "/Users/bennett/opt/anaconda3/lib/python3.9/subprocess.py", line 1134, in communicate
    stdout, stderr = self._communicate(input, endtime, timeout)
  File "/Users/bennett/opt/anaconda3/lib/python3.9/subprocess.py", line 1980, in _communicate
    self._check_timeout(endtime, orig_timeout, stdout, stderr)
  File "/Users/bennett/opt/anaconda3/lib/python3.9/subprocess.py", line 1178, in _check_timeout
    raise TimeoutExpired(
subprocess.TimeoutExpired: Command '[PosixPath('/Users/bennett/opt/anaconda3/lib/python3.9/site-packages/httpstan/stanc'), '--name', 'model_ntce4pp2', '--warn-pedantic', '--print-cpp', '/var/folders/9t/53m4vvyn28d08r7hr7_h9xf80000gn/T/httpstan__n4i7362/model_ntce4pp2.stan']' timed out after 1 seconds

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [12], in <cell line: 1>()
----> 1 posterior = stan.build(script, data = stan_data)

File ~/opt/anaconda3/lib/python3.9/site-packages/stan/model.py:518, in build(program_code, data, random_seed)
    515         return Model(model_name, program_code, data, param_names, constrained_param_names, dims, random_seed)
    517 try:
--> 518     return asyncio.run(go())
    519 except KeyboardInterrupt:
    520     return

File ~/opt/anaconda3/lib/python3.9/site-packages/nest_asyncio.py:35, in _patch_asyncio.<locals>.run(main, debug)
     33 task = asyncio.ensure_future(main)
     34 try:
---> 35     return loop.run_until_complete(task)
     36 finally:
     37     if not task.done():

File ~/opt/anaconda3/lib/python3.9/site-packages/nest_asyncio.py:89, in _patch_loop.<locals>.run_until_complete(self, future)
     86 if not f.done():
     87     raise RuntimeError(
     88         'Event loop stopped before Future completed.')
---> 89 return f.result()

File ~/opt/anaconda3/lib/python3.9/asyncio/futures.py:201, in Future.result(self)
    199 self.__log_traceback = False
    200 if self._exception is not None:
--> 201     raise self._exception
    202 return self._result

File ~/opt/anaconda3/lib/python3.9/asyncio/tasks.py:256, in Task.__step(***failed resolving arguments***)
    252 try:
    253     if exc is None:
    254         # We use the `send` method directly, because coroutines
    255         # don't have `__iter__` and `__next__` methods.
--> 256         result = coro.send(None)
    257     else:
    258         result = coro.throw(exc)

File ~/opt/anaconda3/lib/python3.9/site-packages/stan/model.py:485, in build.<locals>.go()
    482 resp = task.result()
    484 if resp.status != 201:
--> 485     match = re.search(r"""ValueError\(['"](.*)['"]\)""", resp.json()["message"])
    486     if not match:  # unknown error, should not happen
    487         raise RuntimeError(resp.json()["message"])

File ~/opt/anaconda3/lib/python3.9/site-packages/stan/common.py:25, in HTTPResponse.json(self)
     23 def json(self) -> dict:
     24     # mypy 0.961 complains that simdjson lacks a `loads`.
---> 25     return simdjson.loads(self.content)

File ~/opt/anaconda3/lib/python3.9/site-packages/simdjson/__init__.py:61, in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kwargs)
     58     s = s.encode('utf-8')
     60 parser = Parser()
---> 61 return parser.parse(s, True)

ValueError: The JSON document has an improper structure: missing or superfluous commas, braces, missing keys, etc.

Any guidance on how to resolve? Thank you for your time and help.

P.S. The relevant .stan script is:

data {
  // Training Data (Individual-Level)
  /// Model Metadata
  int<lower=0> N; // Number of interviews
  int<lower=0> N_y; // Number of target classes
  /// Number of Levels for Varying Intercepts
  int<lower=0> N_gender;
  int<lower=0> N_parental_status;
  int<lower=0> N_marital_status;
  int<lower=0> N_age;
  int<lower=0> N_education;
  int<lower=0> N_race;
  /// Group-Level Indices
  int<lower=1> N_state;
  
  /// Interview Targets
  array[N] int<lower=1,upper= N_y> y;
  /// Varying Intercept Levels
  array[N] int<lower=1,upper=N_gender> gender;
  array[N] int<lower=1,upper=N_parental_status> parental_status;
  array[N] int<lower=1,upper=N_marital_status> marital_status;
  array[N] int<lower=1,upper=N_age> age;
  array[N] int<lower=1,upper=N_education> education;
  array[N] int<lower=1,upper=N_race> race;
  array[N] int<lower=1,upper=N_state> state;
}
parameters {
  // Target Cutpoints
  ordered[N_y - 1] c;
  
  // Prior Uncertainties for Demographic Varying Intercepts
  real<lower=0> sigma_gender;
  real<lower=0> sigma_parental_status;
  real<lower=0> sigma_marital_status;
  real<lower=0> sigma_age;
  real<lower=0> sigma_education;
  real<lower=0> sigma_race;
  real<lower=0> sigma_state;
  
  // Varying Intercepts
  /// Real codings for dichotomous Varying Intercepts
  real alpha_gender_raw;
  real alpha_parental_status_raw;
  real alpha_marital_status_raw;
  /// Vector codings for multi-level Varying Intercepts
  vector[N_age] alpha_age_raw;
  vector[N_education] alpha_education_raw;
  vector[N_race] alpha_race_raw;
  vector[N_state] alpha_state_raw;
}
transformed parameters{

  // Varying Intercepts
  /// Real codings for dichotomous Varying Intercepts
  real alpha_gender;
  real alpha_parental_status;
  real alpha_marital_status;
  /// Vector codings for multilevel Varying Intercepts
  vector[N_age] alpha_age;
  vector[N_education] alpha_education;
  vector[N_race] alpha_race;
  vector[N_state] alpha_state;

  // Non-Centered Parametrization for Varying Intercepts
  /// Dichotomous Intercepts
  alpha_gender = alpha_gender_raw * sigma_gender;
  alpha_parental_status = alpha_parental_status_raw * sigma_parental_status;
  alpha_marital_status = alpha_marital_status_raw * sigma_marital_status;
  /// Multilevel Intercepts
  for (n in 1:N_age){
    alpha_age[n] = alpha_age_raw[n] * sigma_age;
  }
  for (n in 1:N_education){
    alpha_education[n] = alpha_education_raw[n] * sigma_education;
  }
  for (n in 1:N_race){
    alpha_race[n] = alpha_race_raw[n] * sigma_race;
  }
  for (n in 1:N_state){
    alpha_state[n] = alpha_state_raw[n] * sigma_state;
  }
    
}
model {
  // Varying Intercept Prior SDs
  sigma_gender ~ std_normal();
  sigma_parental_status ~ std_normal();
  sigma_marital_status ~ std_normal();
  sigma_age ~ std_normal();
  sigma_education ~ std_normal();
  sigma_race ~ std_normal();
  sigma_state ~ std_normal();
  
  // Varying Intercepts
  /// Dichotomous Intercepts
  alpha_gender_raw ~ std_normal();
  alpha_parental_status_raw ~ std_normal();
  alpha_marital_status_raw ~ std_normal();
  /// Multilevel Intercepts
  for (n in 1:N_age){  
    alpha_age_raw[n] ~ std_normal();
  }
  for (n in 1:N_education){      
    alpha_education_raw[n] ~ std_normal();
  }
  for (n in 1:N_race){      
    alpha_race_raw[n] ~ std_normal();
  }
  for (n in 1:N_state){      
    alpha_state_raw[n] ~ std_normal();
  }

  // Training Loop
  for (n in 1:N){
      y[n] ~ ordered_logistic([alpha_gender, -alpha_gender][gender[n]] +[alpha_parental_status, -alpha_parental_status][parental_status[n]] + [alpha_marital_status, -alpha_marital_status][marital_status[n]] + alpha_age[age[n]] + alpha_education[education[n]] + alpha_race[race[n]] + alpha_state[state[n]], c);
  }

}

The example .stan file is missing the “data {”. Is that just a copy/paste mistake for the post or are you trying to compile the same model?

How do you read the script into python?

This could be some kind of glibc/libc++ missing symbol error due to Anaconda messing with the runtime link path. Anaconda Python is not currently supported.

Could you try this without using Anaconda?

@rok_cesnovar apologies for the lack of clarity – had data { on the same like as the triple “`” (to create a code snippet), just updated discourse formatting to clean things up (plus an additional content edit, as I realize I shared the wrong version of my specification).

@ahartikainen/@ariddell based on your guidance, I’ve moved my workflow out from Anaconda – new python environment is v. 3.10.5, PyStan version is still 3.5.0. I’m again able to build and sample my model, but when the build command completes I’m thrown a wall of warning messages (copied below).

Given that model output looks reasonable, (and baring a few Exception alerts about initialization for the cut-points on the ordered logit failing the ordering constraint, sampling doesn’t prompt any additional warning messages), how concerned should I be regarding the following build warnings?

ld: warning: ignoring file /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/lib/libsundials_cvodes.a, building for macOS-arm64 but attempting to link with file built for macOS-x86_64
ld: warning: ignoring file /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/lib/libsundials_idas.a, building for macOS-arm64 but attempting to link with file built for macOS-x86_64
ld: warning: ignoring file /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/lib/libsundials_nvecserial.a, building for macOS-arm64 but attempting to link with file built for macOS-x86_64
ld: warning: ignoring file /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/lib/libtbb.dylib, building for macOS-arm64 but attempting to link with file built for macOS-x86_64
ld: warning: ignoring file /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/lib/libtbbmalloc.dylib, building for macOS-arm64 but attempting to link with file built for macOS-x86_64
ld: warning: ignoring file /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/lib/libtbbmalloc_proxy.dylib, building for macOS-arm64 but attempting to link with file built for macOS-x86_64
ld: warning: direct access in function 'long double boost::math::detail::bessel_j0<long double>(long double)' from file '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/stan_services.o' to global weak symbol 'long double boost::math::detail::bessel_j0<long double>(long double)::Q2' from file 'build/temp.macosx-10.9-universal2-3.10/Users/bennett/Library/Caches/httpstan/4.8.0/models/oeggh5yh/model_oeggh5yh.o' means the weak symbol cannot be overridden at runtime. This was likely caused by different translation units being compiled with different visibility settings.
ld: warning: direct access in function 'long double boost::math::detail::bessel_j0<long double>(long double)' from file '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/stan_services.o' to global weak symbol 'long double boost::math::detail::bessel_j0<long double>(long double)::Q2' from file 'build/temp.macosx-10.9-universal2-3.10/Users/bennett/Library/Caches/httpstan/4.8.0/models/oeggh5yh/model_oeggh5yh.o' means the weak symbol cannot be overridden at runtime. This was likely caused by different translation units being compiled with different visibility settings.
ld: warning: direct access in function 'long double boost::math::detail::bessel_j0<long double>(long double)' from file '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/stan_services.o' to global weak symbol 'long double boost::math::detail::bessel_j0<long double>(long double)::P2' from file 'build/temp.macosx-10.9-universal2-3.10/Users/bennett/Library/Caches/httpstan/4.8.0/models/oeggh5yh/model_oeggh5yh.o' means the weak symbol cannot be overridden at runtime. This was likely caused by different translation units being compiled with different visibility settings.
ld: warning: direct access in function 'long double boost::math::detail::bessel_j0<long double>(long double)' from file '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/stan_services.o' to global weak symbol 'long double boost::math::detail::bessel_j0<long double>(long double)::P2' from file 'build/temp.macosx-10.9-universal2-3.10/Users/bennett/Library/Caches/httpstan/4.8.0/models/oeggh5yh/model_oeggh5yh.o' means the weak symbol cannot be overridden at runtime. This was likely caused by different translation units being compiled with different visibility settings.
ld: warning: direct access in function 'long double boost::math::detail::bessel_j0<long double>(long double)' from file '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/stan_services.o' to global weak symbol 'long double boost::math::detail::bessel_j0<long double>(long double)::Q1' from file 'build/temp.macosx-10.9-universal2-3.10/Users/bennett/Library/Caches/httpstan/4.8.0/models/oeggh5yh/model_oeggh5yh.o' means the weak symbol cannot be overridden at runtime. This was likely caused by different translation units being compiled with different visibility settings.
ld: warning: direct access in function 'long double boost::math::detail::bessel_j0<long double>(long double)' from file '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/stan_services.o' to global weak symbol 'long double boost::math::detail::bessel_j0<long double>(long double)::Q1' from file 'build/temp.macosx-10.9-universal2-3.10/Users/bennett/Library/Caches/httpstan/4.8.0/models/oeggh5yh/model_oeggh5yh.o' means the weak symbol cannot be overridden at runtime. This was likely caused by different translation units being compiled with different visibility settings.
ld: warning: direct access in function 'long double boost::math::detail::bessel_j0<long double>(long double)' from file '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/stan_services.o' to global weak symbol 'long double boost::math::detail::bessel_j0<long double>(long double)::P1' from file 'build/temp.macosx-10.9-universal2-3.10/Users/bennett/Library/Caches/httpstan/4.8.0/models/oeggh5yh/model_oeggh5yh.o' means the weak symbol cannot be overridden at runtime. This was likely caused by different translation units being compiled with different visibility settings.
ld: warning: direct access in function 'long double boost::math::detail::bessel_j0<long double>(long double)' from file '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/stan_services.o' to global weak symbol 'long double boost::math::detail::bessel_j0<long double>(long double)::P1' from file 'build/temp.macosx-10.9-universal2-3.10/Users/bennett/Library/Caches/httpstan/4.8.0/models/oeggh5yh/model_oeggh5yh.o' means the weak symbol cannot be overridden at runtime. This was likely caused by different translation units being compiled with different visibility settings.

(and several other warnings (comprising more characters than I’m able to post in a single comment) of the form ld: warning: direct access in function [..] from file 'build/temp.macosx-10.9-universal2-3.10/Users/bennett/Library/Caches/httpstan/4.8.0/models/oeggh5yh/model_oeggh5yh.o' means the weak symbol cannot be overridden at runtime. This was likely caused by different translation units being compiled with different visibility settings.)

Those errors do look a little odd.

Is this an M1 or M2 machine? If so, you’ll need to install httpstan from source before trying to install pystan.

Instructions for installing httpstan from source are available here: Installation — httpstan 4.7.1 documentation

@ariddell I’m running an i5 processor – still worth my uninstalling pystan → installing httpstan → reinstalling pystan?

I think this is something M1 machines do. They run either on arm or with rosetta on x86. This was somehow controlled by the terminal.

There is httpstan in conda too, which is compiled against x86?

I’ve proactively uninstalled httpstan/pystan and then re-installed (in that order); when I look to re-build my model in python, I’m still thrown a series of warnings (44 total) of the form

ld: warning: ignoring file /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/lib/[...], building for macOS-arm64 but attempting to link with file built for macOS-x86_64

and

ld: warning: direct access in function [...] from file 'build/temp.macosx-10.9-universal2-3.10/Users/bennett/Library/Caches/httpstan/4.8.0/models/ap4ngjnu/model_ap4ngjnu.o' means the weak symbol cannot be overridden at runtime. This was likely caused by different translation units being compiled with different visibility settings.

@bgb-cu Thanks for these details.

I don’t think you should be seeing these errors but, as a non-mac user, I don’t really understand what’s going on.

Since we haven’t seen these errors before, I wonder if there isn’t a problem with our wheel-building setup that arises only on macOS 12.

Did you install httpstan from source? If so, I’m very surprised the warnings are still showing up. Perhaps there’s a bug in our httpstan Makefile that builds things incorrectly on macOS 12.

@ariddell just rebuilt from source (had been using pip), when I build my model I’m now thrown a new first warning:

ld: warning: object file (/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/stan_services.o) was built for newer macOS version (12.0) than being linked (11.0)

before being greeted with various [...] building for macOS-arm64 but attempting to link with file built for macOS-x86_64 pings.

Backing up, when I ran the make command from the CLI after installing poetry during the source installation, the CLI output flagged a number of warnings (33 total) of the form:

httpstan/include/stan/math/prim/err/check_matching_dims.hpp:56:23: warning: comparison of integers of different signs: 'int' and
      'std::vector<int>::size_type' (aka 'unsigned long') [-Wsign-compare]
    for (int i = 0; i < y1_d.size(); i++) {
                    ~ ^ ~~~~~~~~~~~
httpstan/include/stan/math/rev/fun/beta.hpp:70:32: warning: lambda capture 'b' is not used [-Wunused-lambda-capture]
                           [a, b, digamma_ab](auto& vi) mutable {
                             ~~^

etc. (Not sure to what extent the later bit of context helps diagnose what’s going on here, but figure I’d share both).

Thanks. All of this looks in order. These particular warnings can be ignored, I think. Thanks for posting them here though.

I take it everything is working, ld warnings aside?

Thanks for clarifying how best to consider the warnings here.

The model broadly looks correct when I execute sampling – still seeing a few warnings about initialization for the ordered logit cut-points violating the ordering constraint (these parameters converge to the proper ordering structure), but nothing else to write home about.

@ariddell/@ahartikainen/@rok_cesnovar unfortunately need to reopen this one: I’m intermittently getting thrown the following error for arbitrary .stan scripts, with the error seemingly occurring at random and then dissipating on its own after multiple attempts at executing the same script (i.e. with no change in underlying content of the .stan file).

Error message:

Error handling request
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/aiohttp/web_protocol.py", line 435, in _handle_request
    resp = await request_handler(request)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/aiohttp/web_app.py", line 504, in _handle
    resp = await handler(request)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/views.py", line 103, in handle_create_model
    _, stanc_warnings = httpstan.compile.compile(program_code, stan_model_name)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/compile.py", line 37, in compile
    completed_process = subprocess.run(run_args, capture_output=True, timeout=1)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/subprocess.py", line 503, in run
    stdout, stderr = process.communicate(input, timeout=timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/subprocess.py", line 1152, in communicate
    stdout, stderr = self._communicate(input, endtime, timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/subprocess.py", line 2004, in _communicate
    self._check_timeout(endtime, orig_timeout, stdout, stderr)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/subprocess.py", line 1196, in _check_timeout
    raise TimeoutExpired(
subprocess.TimeoutExpired: Command '[PosixPath('/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/stanc'), '--name', 'model_76j45xe2', '--warn-pedantic', '--print-cpp', '/var/folders/9t/53m4vvyn28d08r7hr7_h9xf80000gn/T/httpstan_y3wq9uwn/model_76j45xe2.stan']' timed out after 1 seconds
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [10], in <cell line: 1>()
----> 1 posterior = stan.build(script, data = stan_data, random_seed = rs)

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/stan/model.py:518, in build(program_code, data, random_seed)
    515         return Model(model_name, program_code, data, param_names, constrained_param_names, dims, random_seed)
    517 try:
--> 518     return asyncio.run(go())
    519 except KeyboardInterrupt:
    520     return

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/nest_asyncio.py:35, in _patch_asyncio.<locals>.run(main, debug)
     33 task = asyncio.ensure_future(main)
     34 try:
---> 35     return loop.run_until_complete(task)
     36 finally:
     37     if not task.done():

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/nest_asyncio.py:89, in _patch_loop.<locals>.run_until_complete(self, future)
     86 if not f.done():
     87     raise RuntimeError(
     88         'Event loop stopped before Future completed.')
---> 89 return f.result()

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/futures.py:201, in Future.result(self)
    199 self.__log_traceback = False
    200 if self._exception is not None:
--> 201     raise self._exception
    202 return self._result

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/tasks.py:232, in Task.__step(***failed resolving arguments***)
    228 try:
    229     if exc is None:
    230         # We use the `send` method directly, because coroutines
    231         # don't have `__iter__` and `__next__` methods.
--> 232         result = coro.send(None)
    233     else:
    234         result = coro.throw(exc)

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/stan/model.py:485, in build.<locals>.go()
    482 resp = task.result()
    484 if resp.status != 201:
--> 485     match = re.search(r"""ValueError\(['"](.*)['"]\)""", resp.json()["message"])
    486     if not match:  # unknown error, should not happen
    487         raise RuntimeError(resp.json()["message"])

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/stan/common.py:25, in HTTPResponse.json(self)
     23 def json(self) -> dict:
     24     # mypy 0.961 complains that simdjson lacks a `loads`.
---> 25     return simdjson.loads(self.content)

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/simdjson/__init__.py:61, in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kwargs)
     58     s = s.encode('utf-8')
     60 parser = Parser()
---> 61 return parser.parse(s, True)

ValueError: The JSON document has an improper structure: missing or superfluous commas, braces, missing keys, etc.

The only learning I’ve gathered so far (I’m running PyStan through an .ipynb notebook on Jupyter Lab) is:

  1. If I restart my kernel and rerun my notebook, the error persists, and
  2. If I shutdown my Jupyter Lab session, close the browser window through which I accessed my notebook server, launch a new Jupyter Lab session from terminal, and rerun my notebook, the error also persists, but
  3. If I shutdown my Jupyter Lab session, leave the original broser tab open, launch a new Jupyter Lab session from terminal, and rerun my notebook, the .stan script builds without error

Not sure quite what’s going on here (especially where the source error is coming from) – based on earlier discourse, I imagine that these issues may be related to the httpstan <> python 3.10 interface?

I’m also sometimes thrown this error (seemingly at random), though the issue tends to dissipate after I immediately rerun the same script that tripped the error in the first place:

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Input In [10], in <cell line: 1>()
----> 1 posterior = stan.build(script, data = stan_data, random_seed = rs)

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/stan/model.py:518, in build(program_code, data, random_seed)
    515         return Model(model_name, program_code, data, param_names, constrained_param_names, dims, random_seed)
    517 try:
--> 518     return asyncio.run(go())
    519 except KeyboardInterrupt:
    520     return

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/nest_asyncio.py:35, in _patch_asyncio.<locals>.run(main, debug)
     33 task = asyncio.ensure_future(main)
     34 try:
---> 35     return loop.run_until_complete(task)
     36 finally:
     37     if not task.done():

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/nest_asyncio.py:89, in _patch_loop.<locals>.run_until_complete(self, future)
     86 if not f.done():
     87     raise RuntimeError(
     88         'Event loop stopped before Future completed.')
---> 89 return f.result()

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/futures.py:201, in Future.result(self)
    199 self.__log_traceback = False
    200 if self._exception is not None:
--> 201     raise self._exception
    202 return self._result

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/tasks.py:232, in Task.__step(***failed resolving arguments***)
    228 try:
    229     if exc is None:
    230         # We use the `send` method directly, because coroutines
    231         # don't have `__iter__` and `__next__` methods.
--> 232         result = coro.send(None)
    233     else:
    234         result = coro.throw(exc)

File /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/stan/model.py:487, in build.<locals>.go()
    485 match = re.search(r"""ValueError\(['"](.*)['"]\)""", resp.json()["message"])
    486 if not match:  # unknown error, should not happen
--> 487     raise RuntimeError(resp.json()["message"])
    488 exception_body = match.group(1).encode().decode("unicode_escape")
    489 error_type_match = re.match(r"(Semantic|Syntax) error", exception_body)

RuntimeError: Exception while building model extension module: `TimeoutExpired([PosixPath('/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/stanc'), '--name', 'model_qyya5xjz', '--warn-pedantic', '--print-cpp', '/var/folders/9t/53m4vvyn28d08r7hr7_h9xf80000gn/T/httpstan_a70fyn59/model_qyya5xjz.stan'], 1)`, traceback: `['  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/views.py", line 114, in handle_create_model\n    compiler_output = await httpstan.models.build_services_extension_module(program_code)\n', '  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/models.py", line 121, in build_services_extension_module\n    cpp_code, _ = httpstan.compile.compile(program_code, stan_model_name)\n', '  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/httpstan/compile.py", line 37, in compile\n    completed_process = subprocess.run(run_args, capture_output=True, timeout=1)\n', '  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/subprocess.py", line 503, in run\n    stdout, stderr = process.communicate(input, timeout=timeout)\n', '  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/subprocess.py", line 1152, in communicate\n    stdout, stderr = self._communicate(input, endtime, timeout)\n', '  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/subprocess.py", line 2004, in _communicate\n    self._check_timeout(endtime, orig_timeout, stdout, stderr)\n', '  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/subprocess.py", line 1196, in _check_timeout\n    raise TimeoutExpired(\n']`

If you’re installing from source, this seems like an odd error to see. No 11.0 objects should be involved. I wonder if fully removing everything and then re-installing httpstan would eliminate this message and the other problems.

Sorry I can’t be of more help.

Unfortunately, I’d already fully uninstalled PyStan before I performed httpstan installation from source, so still stuck here.

ASCII whitespace of 1 or more character is all treated uniformly by the Stan parser. Might PyStan be doing something to interfere? RStan does that in some cases, which causes problems with some models that would otherwise run in CmdStan.

You could also try cmdstanpy if you don’t need log densities or gradients within your code. It’s a bit easier to install without a binary dependency to Python.

Thanks for the pointer! WIll take a look at refactoring to CmdStanPy as capacity allows.