import modal
from cmdstanpy import CmdStanModel
= modal.App("stan-example")
app
= (
cmdstan_image ="3.13")
modal.Image.debian_slim(python_version"uv")
.pip_install("uv pip install --system --compile-bytecode cmdstanpy")
.run_commands("install_cmdstan")
.run_commands(
)
@app.function(image=cmdstan_image)
def run_cmdstan_model():
= """
eight_schools_stan_code data {
int<lower=0> J; // number of schools
array[J] real y; // estimated treatment effect (school j)
array[J] real<lower=0> sigma; // std err of effect estimate (school j)
}
parameters {
real mu;
array[J] real theta;
real<lower=0> tau;
}
model {
theta ~ normal(mu, tau);
y ~ normal(theta, sigma);
}
"""
= "eight_schools.stan"
eight_schools_file with open(eight_schools_file, "w") as f:
f.write(eight_schools_stan_code)
= {
schools_data "J": 8,
"y": [28, 8, -3, 7, -1, 1, 18, 12],
"sigma": [15, 10, 16, 11, 9, 11, 10, 18],
}
= CmdStanModel(stan_file=eight_schools_file)
eight_schools_model = eight_schools_model.sample(
eight_schools_fit =schools_data, chains=4, iter_sampling=1000
data
)print(eight_schools_fit.summary())
@app.local_entrypoint()
def main():
run_cmdstan_model.remote()
This is an example of running CmdStanPy using Modal on the Eight Schools, which examines coaching effects across eight schools.
Reuse
Citation
For attribution, please cite this work as:
Reynaldo Hutabarat, Farhan. 2025. “Stan Using Modal.” May
12, 2025. https://weaklyinformative.com/posts/2025-05-11_stan-using-modal/.