Stan Using Modal

Run Stan in the cloud.
Author
Published

May 12, 2025

Modified

May 12, 2025

This is an example of running CmdStanPy using Modal on the Eight Schools, which examines coaching effects across eight schools.

import modal
from cmdstanpy import CmdStanModel

app = modal.App("stan-example")

cmdstan_image = (
    modal.Image.debian_slim(python_version="3.13")
    .pip_install("uv")
    .run_commands("uv pip install --system --compile-bytecode cmdstanpy")
    .run_commands("install_cmdstan")
)


@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_file = "eight_schools.stan"
    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],
    }

    eight_schools_model = CmdStanModel(stan_file=eight_schools_file)
    eight_schools_fit = eight_schools_model.sample(
        data=schools_data, chains=4, iter_sampling=1000
    )
    print(eight_schools_fit.summary())


@app.local_entrypoint()
def main():
    run_cmdstan_model.remote()
Back to top

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/.