Stan, stanr, and brms running client-side in the browser via webR

Hi all,

I’ve been experimenting with running Stan inside webR and wanted to share a working proof-of-concept.

Thanks to @seantalts’ work on stanli (the Stan interpreter/runtime) and @andrjohns’ work on stanr and his stanli-backend fork of brms, it is now fully possible to compile/interpret and sample Stan models completely client-side in the browser.

I set up Wasm builds of the brms fork and the stanli R package in R-universe and tested the workflow across three levels:(EDIT: replaced with @seantalts’s R-universe for the stanli package)


1. Setup & Core Runtime (stanli)

stanli provides the lightweight runtime/interpreter for Stan in WebAssembly.

Workaround for browser CORS: In webR, dynamically downloading the precompiled runtime via stanli::stanli_install() currently gets blocked by browser CORS restrictions. The simple workaround for now is to grab stanli-runtime-emscripten-wasm32.tar.gz, unpack libstanli.so, and upload/mount it into the virtual root (/libstanli.so). Note that this isn’t needed for using stanr, since stanr bundles the runtime for stanli directly.

# Install stanli from r-universe
install.packages("stanli", repos = "https://seantalts.r-universe.dev")

# Point to the uploaded runtime
# Sys.setenv(STANLI_RUNTIME = "/libstanli.so")
# Not relevant anymore, the wasm build includes the stanli runtime

library(stanli)
# on non wasm: stanli_install()
stopifnot(stanli_available())

Direct sampling with stanli:

model_code <- "
data {
  int<lower=0> N;
  vector[N] y;
}
parameters {
  real mu;
  real<lower=0> sigma;
}
model {
  mu ~ normal(0, 10);
  sigma ~ exponential(1);
  y ~ normal(mu, sigma);
}
"

model_data <- list(
  N = 8L,
  y = c(28, 8, -3, 7, -1, 1, 18, 12)
)

model <- stanli_model(code = model_code, data = model_data)
fit <- sample_model(model, chains = 2, warmup = 250, samples = 2500, seed = 123)
Chain [1] Iteration:    1 / 2750 [  0%]  (Warmup)
Chain [1] Iteration:  100 / 2750 [  3%]  (Warmup)
Chain [1] Iteration:  200 / 2750 [  7%]  (Warmup)
Chain [1] Iteration:  250 / 2750 [  9%]  (Warmup)
Chain [1] Iteration:  251 / 2750 [  9%]  (Sampling)
Chain [1] Iteration:  350 / 2750 [ 12%]  (Sampling)
Chain [1] Iteration:  450 / 2750 [ 16%]  (Sampling)
Chain [1] Iteration:  550 / 2750 [ 20%]  (Sampling)
Chain [1] Iteration:  650 / 2750 [ 23%]  (Sampling)
Chain [1] Iteration:  750 / 2750 [ 27%]  (Sampling)
Chain [1] Iteration:  850 / 2750 [ 30%]  (Sampling)
Chain [1] Iteration:  950 / 2750 [ 34%]  (Sampling)
Chain [1] Iteration: 1050 / 2750 [ 38%]  (Sampling)
Chain [1] Iteration: 1150 / 2750 [ 41%]  (Sampling)
Chain [1] Iteration: 1250 / 2750 [ 45%]  (Sampling)
Chain [1] Iteration: 1350 / 2750 [ 49%]  (Sampling)
Chain [1] Iteration: 1450 / 2750 [ 52%]  (Sampling)
Chain [1] Iteration: 1550 / 2750 [ 56%]  (Sampling)
Chain [1] Iteration: 1650 / 2750 [ 60%]  (Sampling)
Chain [1] Iteration: 1750 / 2750 [ 63%]  (Sampling)
Chain [1] Iteration: 1850 / 2750 [ 67%]  (Sampling)
Chain [1] Iteration: 1950 / 2750 [ 70%]  (Sampling)
Chain [1] Iteration: 2050 / 2750 [ 74%]  (Sampling)
Chain [1] Iteration: 2150 / 2750 [ 78%]  (Sampling)
Chain [1] Iteration: 2250 / 2750 [ 81%]  (Sampling)
Chain [1] Iteration: 2350 / 2750 [ 85%]  (Sampling)
Chain [1] Iteration: 2450 / 2750 [ 89%]  (Sampling)
Chain [1] Iteration: 2550 / 2750 [ 92%]  (Sampling)
Chain [1] Iteration: 2650 / 2750 [ 96%]  (Sampling)
Chain [1] Iteration: 2750 / 2750 [100%]  (Sampling)
Chain [2] Iteration:    1 / 2750 [  0%]  (Warmup)
Chain [2] Iteration:  100 / 2750 [  3%]  (Warmup)
Chain [2] Iteration:  200 / 2750 [  7%]  (Warmup)
Chain [2] Iteration:  250 / 2750 [  9%]  (Warmup)
Chain [2] Iteration:  251 / 2750 [  9%]  (Sampling)
Chain [2] Iteration:  350 / 2750 [ 12%]  (Sampling)
Chain [2] Iteration:  450 / 2750 [ 16%]  (Sampling)
Chain [2] Iteration:  550 / 2750 [ 20%]  (Sampling)
Chain [2] Iteration:  650 / 2750 [ 23%]  (Sampling)
Chain [2] Iteration:  750 / 2750 [ 27%]  (Sampling)
Chain [2] Iteration:  850 / 2750 [ 30%]  (Sampling)
Chain [2] Iteration:  950 / 2750 [ 34%]  (Sampling)
Chain [2] Iteration: 1050 / 2750 [ 38%]  (Sampling)
Chain [2] Iteration: 1150 / 2750 [ 41%]  (Sampling)
Chain [2] Iteration: 1250 / 2750 [ 45%]  (Sampling)
Chain [2] Iteration: 1350 / 2750 [ 49%]  (Sampling)
Chain [2] Iteration: 1450 / 2750 [ 52%]  (Sampling)
Chain [2] Iteration: 1550 / 2750 [ 56%]  (Sampling)
Chain [2] Iteration: 1650 / 2750 [ 60%]  (Sampling)
Chain [2] Iteration: 1750 / 2750 [ 63%]  (Sampling)
Chain [2] Iteration: 1850 / 2750 [ 67%]  (Sampling)
Chain [2] Iteration: 1950 / 2750 [ 70%]  (Sampling)
Chain [2] Iteration: 2050 / 2750 [ 74%]  (Sampling)
Chain [2] Iteration: 2150 / 2750 [ 78%]  (Sampling)
Chain [2] Iteration: 2250 / 2750 [ 81%]  (Sampling)
Chain [2] Iteration: 2350 / 2750 [ 85%]  (Sampling)
Chain [2] Iteration: 2450 / 2750 [ 89%]  (Sampling)
Chain [2] Iteration: 2550 / 2750 [ 92%]  (Sampling)
Chain [2] Iteration: 2650 / 2750 [ 96%]  (Sampling)
Chain [2] Iteration: 2750 / 2750 [100%]  (Sampling)

Chain [1] Elapsed Time: 0.091 seconds (Warm-up)
                  0.169 seconds (Sampling)
                  0.260 seconds (Total)

Chain [2] Elapsed Time: 0.054 seconds (Warm-up)
                  0.232 seconds (Sampling)
                  0.287 seconds (Total)

EDIT: stanli now outputs the sampling progress.

Results

> summary(fit)
  variable     mean  mcse_mean       sd    mcse_sd       q5      q50      q95 ess_bulk ess_tail
1       mu 8.069115 0.05625743 2.668532 0.04914493 3.702832 8.108840 12.46221 2291.173 1948.553
2    sigma 7.739020 0.02743319 1.344503 0.02867524 5.810334 7.605246 10.16252 2536.218 2211.829
      rhat
1 1.000607
2 1.002873

> stanli_diagnose(fit)
No divergent transitions.
No transitions saturated the maximum treedepth of 10.
E-BFMI is above 0.3 in every chain.
R-hat is below 1.01 for every parameter (worst 1.003, sigma).
Bulk ESS is at least 100 per chain for every parameter (worst 2291, mu).
Tail ESS is at least 100 per chain for every parameter (worst 1949, mu).
No problems detected.

2. Modern Interface with stanr

Andrew’s stanr package gives a familiar cmdstanr-style API on top of stanli, with seamless integration into posterior and full diagnostics (note: stanr bundles the stanli runtime directly, so manual mounting or the stanli R package isn’t strictly required here):

install.packages("stanr", repos = c("https://andrjohns.r-universe.dev", "https://repo.r-wasm.org/"))
library(stanr)

mod <- stan_model(
  code = model_code,
  model_name = "normal_location_scale",
  backend = "stanli"
)

fit <- mod$sample(
  data = model_data,
  chains = 4,
  iter_warmup = 500,
  iter_sampling = 1000,
  seed = 123
)
## Prints sampling as usual
Gradient evaluation took 0.000315 seconds
1000 transitions using 10 leapfrog steps per transition would take 3.15 seconds.
Adjust your expectations accordingly!



Gradient evaluation took 1.5e-05 seconds
1000 transitions using 10 leapfrog steps per transition would take 0.15 seconds.
Adjust your expectations accordingly!



Gradient evaluation took 1e-05 seconds
1000 transitions using 10 leapfrog steps per transition would take 0.1 seconds.
Adjust your expectations accordingly!



Gradient evaluation took 1e-05 seconds
1000 transitions using 10 leapfrog steps per transition would take 0.1 seconds.
Adjust your expectations accordingly!


Chain [1] Iteration:    1 / 1500 [  0%]  (Warmup)
Chain [1] Iteration:  100 / 1500 [  6%]  (Warmup)
Chain [1] Iteration:  200 / 1500 [ 13%]  (Warmup)
Chain [1] Iteration:  300 / 1500 [ 20%]  (Warmup)
Chain [1] Iteration:  400 / 1500 [ 26%]  (Warmup)
Chain [1] Iteration:  500 / 1500 [ 33%]  (Warmup)
Chain [1] Iteration:  501 / 1500 [ 33%]  (Sampling)
Chain [1] Iteration:  600 / 1500 [ 40%]  (Sampling)
Chain [1] Iteration:  700 / 1500 [ 46%]  (Sampling)
Chain [1] Iteration:  800 / 1500 [ 53%]  (Sampling)
Chain [1] Iteration:  900 / 1500 [ 60%]  (Sampling)
Chain [1] Iteration: 1000 / 1500 [ 66%]  (Sampling)
Chain [1] Iteration: 1100 / 1500 [ 73%]  (Sampling)
Chain [1] Iteration: 1200 / 1500 [ 80%]  (Sampling)
Chain [1] Iteration: 1300 / 1500 [ 86%]  (Sampling)
Chain [1] Iteration: 1400 / 1500 [ 93%]  (Sampling)
Chain [1] Iteration: 1500 / 1500 [100%]  (Sampling)

 Elapsed Time: 0.079 seconds (Warm-up)
               0.088 seconds (Sampling)
               0.167 seconds (Total)

Chain [2] Iteration:    1 / 1500 [  0%]  (Warmup)
Chain [2] Iteration:  100 / 1500 [  6%]  (Warmup)
Chain [2] Iteration:  200 / 1500 [ 13%]  (Warmup)
Chain [2] Iteration:  300 / 1500 [ 20%]  (Warmup)
Chain [2] Iteration:  400 / 1500 [ 26%]  (Warmup)
Chain [2] Iteration:  500 / 1500 [ 33%]  (Warmup)
Chain [2] Iteration:  501 / 1500 [ 33%]  (Sampling)
Chain [2] Iteration:  600 / 1500 [ 40%]  (Sampling)
Chain [2] Iteration:  700 / 1500 [ 46%]  (Sampling)
Chain [2] Iteration:  800 / 1500 [ 53%]  (Sampling)
Chain [2] Iteration:  900 / 1500 [ 60%]  (Sampling)
Chain [2] Iteration: 1000 / 1500 [ 66%]  (Sampling)
Chain [2] Iteration: 1100 / 1500 [ 73%]  (Sampling)
Chain [2] Iteration: 1200 / 1500 [ 80%]  (Sampling)
Chain [2] Iteration: 1300 / 1500 [ 86%]  (Sampling)
Chain [2] Iteration: 1400 / 1500 [ 93%]  (Sampling)
Chain [2] Iteration: 1500 / 1500 [100%]  (Sampling)

 Elapsed Time: 0.069 seconds (Warm-up)
               0.103 seconds (Sampling)
               0.172 seconds (Total)

Chain [3] Iteration:    1 / 1500 [  0%]  (Warmup)
Chain [3] Iteration:  100 / 1500 [  6%]  (Warmup)
Chain [3] Iteration:  200 / 1500 [ 13%]  (Warmup)
Chain [3] Iteration:  300 / 1500 [ 20%]  (Warmup)
Chain [3] Iteration:  400 / 1500 [ 26%]  (Warmup)
Chain [3] Iteration:  500 / 1500 [ 33%]  (Warmup)
Chain [3] Iteration:  501 / 1500 [ 33%]  (Sampling)
Chain [3] Iteration:  600 / 1500 [ 40%]  (Sampling)
Chain [3] Iteration:  700 / 1500 [ 46%]  (Sampling)
Chain [3] Iteration:  800 / 1500 [ 53%]  (Sampling)
Chain [3] Iteration:  900 / 1500 [ 60%]  (Sampling)
Chain [3] Iteration: 1000 / 1500 [ 66%]  (Sampling)
Chain [3] Iteration: 1100 / 1500 [ 73%]  (Sampling)
Chain [3] Iteration: 1200 / 1500 [ 80%]  (Sampling)
Chain [3] Iteration: 1300 / 1500 [ 86%]  (Sampling)
Chain [3] Iteration: 1400 / 1500 [ 93%]  (Sampling)
Chain [3] Iteration: 1500 / 1500 [100%]  (Sampling)

 Elapsed Time: 0.073 seconds (Warm-up)
               0.094 seconds (Sampling)
               0.167 seconds (Total)

Chain [4] Iteration:    1 / 1500 [  0%]  (Warmup)
Chain [4] Iteration:  100 / 1500 [  6%]  (Warmup)
Chain [4] Iteration:  200 / 1500 [ 13%]  (Warmup)
Chain [4] Iteration:  300 / 1500 [ 20%]  (Warmup)
Chain [4] Iteration:  400 / 1500 [ 26%]  (Warmup)
Chain [4] Iteration:  500 / 1500 [ 33%]  (Warmup)
Chain [4] Iteration:  501 / 1500 [ 33%]  (Sampling)
Chain [4] Iteration:  600 / 1500 [ 40%]  (Sampling)
Chain [4] Iteration:  700 / 1500 [ 46%]  (Sampling)
Chain [4] Iteration:  800 / 1500 [ 53%]  (Sampling)
Chain [4] Iteration:  900 / 1500 [ 60%]  (Sampling)
Chain [4] Iteration: 1000 / 1500 [ 66%]  (Sampling)
Chain [4] Iteration: 1100 / 1500 [ 73%]  (Sampling)
Chain [4] Iteration: 1200 / 1500 [ 80%]  (Sampling)
Chain [4] Iteration: 1300 / 1500 [ 86%]  (Sampling)
Chain [4] Iteration: 1400 / 1500 [ 93%]  (Sampling)
Chain [4] Iteration: 1500 / 1500 [100%]  (Sampling)

 Elapsed Time: 0.067 seconds (Warm-up)
               0.089 seconds (Sampling)
               0.156 seconds (Total)
# Summaries & Posterior draws
> fit$summary(variables = c("mu", "sigma"))
# A tibble: 2 × 10
  variable  mean median    sd   mad    q5   q95  rhat ess_bulk ess_tail
  <chr>    <dbl>  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>    <dbl>    <dbl>
1 mu        8.17   8.20  2.70  2.70  3.77  12.5 1.00     3176.    2325.
2 sigma     7.78   7.64  1.36  1.30  5.84  10.2 0.999    3037.    2627.
> 
> fit$diagnostic_summary()
$num_divergent
[1] 0 0 0 0

$num_max_treedepth
[1] 0 0 0 0

$ebfmi
[1] 1.1990484 0.9455147 0.9590174 1.1145598

> 
> draws <- fit$draws(variables = c("mu", "sigma"))
> 
> draws
# A draws_array: 1000 iterations, 4 chains, and 2 variables
, , mu

     1   2    3    4
1 10.2 5.4  9.5  6.3
2  6.2 9.0  7.9 10.3
3 12.8 7.7 10.0  9.9
4 10.8 6.6  8.2 10.6
5 11.6 8.6 10.0 15.6

, , sigma

     1   2   3   4
1  6.3 7.7 7.5 4.8
2  7.3 6.0 9.9 9.8
3  6.8 6.9 6.7 9.4
4  9.7 7.7 8.9 9.5
5 10.8 6.5 8.1 7.0

# ... with 995 more iterations

3. Full High-Level Modeling with brms

The best part: Andrew’s stanli backend branch for brms works right out of the box in webR:

install.packages("rstan", repos = c("https://stan-dev.r-universe.dev", "https://repo.r-wasm.org/"))
# brms fork built for wasm
install.packages("brms", repos = c("https://staffanbetner.r-universe.dev", "https://repo.r-wasm.org/"))

library(brms)

fit <- brm(
  formula = time ~ age * sex, 
  data = kidney, 
  backend = "stanli", 
  seed = 1234
)

# similar sampling output as above

summary(fit)

Result:

 Family: gaussian 
  Links: mu = identity 
Formula: time ~ age * sex 
   Data: kidney (Number of observations: 76) 
  Draws: 4 chains, each with iter = 2000; warmup = 1000; thin = 1;
         total post-warmup draws = 4000

Regression Coefficients:
              Estimate Est.Error l-95% CI u-95% CI Rhat Bulk_ESS Tail_ESS
Intercept        24.67     86.89  -147.60   196.37 1.00     1604     1985
age               0.68      1.91    -3.09     4.39 1.00     1585     1804
sexfemale       163.66    101.59   -35.78   357.08 1.00     1572     1978
age:sexfemale    -2.43      2.21    -6.79     1.96 1.00     1510     1833

Further Distributional Parameters:
      Estimate Est.Error l-95% CI u-95% CI Rhat Bulk_ESS Tail_ESS
sigma   128.73     10.80   109.72   151.57 1.00     2404     2594

Draws were sampled using sample(hmc). For each parameter, Bulk_ESS
and Tail_ESS are effective sample size measures, and Rhat is the potential
scale reduction factor on split chains (at convergence, Rhat = 1).

  • Current friction points / Next steps:
    • Finding a smoother way to distribute libstanli.so for the standalone stanli package in webR without hitting CORS restrictions (bundling the runtime directly in its Wasm build, similar to how stanr does it).
    • Chains run sequentially in single-threaded WebAssembly unless parallelized over Web Workers.
    • 32-bit wasm memory limits for larger models.

Massive credit to @seantalts for developing stanli and @andrjohns for stanr and the brms integration!

Disclaimer: English is not my first language. The code, experiments, and findings are my own, but I used an LLM to assist with formatting and structuring the post for clarity.

Minimal reproducible example with outputs:

in webR (https://webr.sh/):

install.packages(c('stanr', 'rstan', 'brms'), 
   repos = c('https://andrjohns.r-universe.dev', 
             'https://stan-dev.r-universe.dev', 
             'https://staffanbetner.r-universe.dev', 
             'https://repo.r-wasm.org/'))
Downloading webR package: R6
Downloading webR package: QuickJSR
Downloading webR package: abind
Downloading webR package: backports
Downloading webR package: checkmate
Downloading webR package: rlang
Downloading webR package: cli
Downloading webR package: lifecycle
Downloading webR package: magrittr
Downloading webR package: glue
Downloading webR package: utf8
Downloading webR package: vctrs
Downloading webR package: pillar
Downloading webR package: pkgconfig
Downloading webR package: tibble
Downloading webR package: tensorA
Downloading webR package: generics
Downloading webR package: numDeriv
Downloading webR package: distributional
Downloading webR package: matrixStats
Downloading webR package: posterior
Downloading webR package: withr
Downloading webR package: RcppParallel
Downloading webR package: StanHeaders
Downloading webR package: inline
Downloading webR package: gtable
Downloading webR package: gridExtra
Downloading webR package: Rcpp
Downloading webR package: loo
Downloading webR package: ps
Downloading webR package: processx
Downloading webR package: callr
Downloading webR package: desc
Downloading webR package: pkgbuild
Downloading webR package: isoband
Downloading webR package: S7
Downloading webR package: farver
Downloading webR package: labeling
Downloading webR package: RColorBrewer
Downloading webR package: viridisLite
Downloading webR package: scales
Downloading webR package: ggplot2
Downloading webR package: rstan
Downloading webR package: lattice
Downloading webR package: Matrix
Downloading webR package: nlme
Downloading webR package: mgcv
Downloading webR package: rstantools
Downloading webR package: tidyselect
Downloading webR package: dplyr
Downloading webR package: quadprog
Downloading webR package: ggdist
Downloading webR package: ggridges
Downloading webR package: plyr
Downloading webR package: stringi
Downloading webR package: stringr
Downloading webR package: reshape2
Downloading webR package: purrr
Downloading webR package: tidyr
Downloading webR package: bayesplot
Downloading webR package: mvtnorm
Downloading webR package: Brobdingnag
Downloading webR package: coda
Downloading webR package: bridgesampling
Downloading webR package: digest
Downloading webR package: codetools
Downloading webR package: globals
Downloading webR package: listenv
Downloading webR package: parallelly
Downloading webR package: future
Downloading webR package: future.apply
Downloading webR package: nleqslv
Downloading webR package: stanr
Downloading webR package: brms
# brms fork: "url": "https://github.com/andrjohns/brms",
#        "branch": "stanr-stanli"
 
library(brms)
Loading required package: Rcpp
Loading 'brms' package (version 2.23.1). Useful instructions
can be found by typing help('brms'). A more detailed introduction
to the package is available through vignette('brms_overview').

Attaching package: ‘brms’

The following object is masked from ‘package:stats’:

    ar
fit <- brm(time ~ age * sex, data = kidney, backend = 'stanli')
Start sampling

Gradient evaluation took 0.000445 seconds
1000 transitions using 10 leapfrog steps per transition would take 4.45 seconds.
Adjust your expectations accordingly!



Gradient evaluation took 4.5e-05 seconds
1000 transitions using 10 leapfrog steps per transition would take 0.45 seconds.
Adjust your expectations accordingly!



Gradient evaluation took 4e-05 seconds
1000 transitions using 10 leapfrog steps per transition would take 0.4 seconds.
Adjust your expectations accordingly!



Gradient evaluation took 5e-05 seconds
1000 transitions using 10 leapfrog steps per transition would take 0.5 seconds.
Adjust your expectations accordingly!


Chain [1] Iteration:    1 / 2000 [  0%]  (Warmup)
Chain [1] Iteration:  100 / 2000 [  5%]  (Warmup)
Chain [1] Iteration:  200 / 2000 [ 10%]  (Warmup)
Chain [1] Iteration:  300 / 2000 [ 15%]  (Warmup)
Chain [1] Iteration:  400 / 2000 [ 20%]  (Warmup)
Chain [1] Iteration:  500 / 2000 [ 25%]  (Warmup)
Chain [1] Iteration:  600 / 2000 [ 30%]  (Warmup)
Chain [1] Iteration:  700 / 2000 [ 35%]  (Warmup)
Chain [1] Iteration:  800 / 2000 [ 40%]  (Warmup)
Chain [1] Iteration:  900 / 2000 [ 45%]  (Warmup)
Chain [1] Iteration: 1000 / 2000 [ 50%]  (Warmup)
Chain [1] Iteration: 1001 / 2000 [ 50%]  (Sampling)
Chain [1] Iteration: 1100 / 2000 [ 55%]  (Sampling)
Chain [1] Iteration: 1200 / 2000 [ 60%]  (Sampling)
Chain [1] Iteration: 1300 / 2000 [ 65%]  (Sampling)
Chain [1] Iteration: 1400 / 2000 [ 70%]  (Sampling)
Chain [1] Iteration: 1500 / 2000 [ 75%]  (Sampling)
Chain [1] Iteration: 1600 / 2000 [ 80%]  (Sampling)
Chain [1] Iteration: 1700 / 2000 [ 85%]  (Sampling)
Chain [1] Iteration: 1800 / 2000 [ 90%]  (Sampling)
Chain [1] Iteration: 1900 / 2000 [ 95%]  (Sampling)
Chain [1] Iteration: 2000 / 2000 [100%]  (Sampling)

 Elapsed Time: 1.896 seconds (Warm-up)
               0.576 seconds (Sampling)
               2.472 seconds (Total)

Chain [2] Iteration:    1 / 2000 [  0%]  (Warmup)
Chain [2] Iteration:  100 / 2000 [  5%]  (Warmup)
Chain [2] Iteration:  200 / 2000 [ 10%]  (Warmup)
Chain [2] Iteration:  300 / 2000 [ 15%]  (Warmup)
Chain [2] Iteration:  400 / 2000 [ 20%]  (Warmup)
Chain [2] Iteration:  500 / 2000 [ 25%]  (Warmup)
Chain [2] Iteration:  600 / 2000 [ 30%]  (Warmup)
Chain [2] Iteration:  700 / 2000 [ 35%]  (Warmup)
Chain [2] Iteration:  800 / 2000 [ 40%]  (Warmup)
Chain [2] Iteration:  900 / 2000 [ 45%]  (Warmup)
Chain [2] Iteration: 1000 / 2000 [ 50%]  (Warmup)
Chain [2] Iteration: 1001 / 2000 [ 50%]  (Sampling)
Chain [2] Iteration: 1100 / 2000 [ 55%]  (Sampling)
Chain [2] Iteration: 1200 / 2000 [ 60%]  (Sampling)
Chain [2] Iteration: 1300 / 2000 [ 65%]  (Sampling)
Chain [2] Iteration: 1400 / 2000 [ 70%]  (Sampling)
Chain [2] Iteration: 1500 / 2000 [ 75%]  (Sampling)
Chain [2] Iteration: 1600 / 2000 [ 80%]  (Sampling)
Chain [2] Iteration: 1700 / 2000 [ 85%]  (Sampling)
Chain [2] Iteration: 1800 / 2000 [ 90%]  (Sampling)
Chain [2] Iteration: 1900 / 2000 [ 95%]  (Sampling)
Chain [2] Iteration: 2000 / 2000 [100%]  (Sampling)

 Elapsed Time: 1.833 seconds (Warm-up)
               0.743 seconds (Sampling)
               2.576 seconds (Total)

Chain [3] Iteration:    1 / 2000 [  0%]  (Warmup)
Chain [3] Iteration:  100 / 2000 [  5%]  (Warmup)
Chain [3] Iteration:  200 / 2000 [ 10%]  (Warmup)
Chain [3] Iteration:  300 / 2000 [ 15%]  (Warmup)
Chain [3] Iteration:  400 / 2000 [ 20%]  (Warmup)
Chain [3] Iteration:  500 / 2000 [ 25%]  (Warmup)
Chain [3] Iteration:  600 / 2000 [ 30%]  (Warmup)
Chain [3] Iteration:  700 / 2000 [ 35%]  (Warmup)
Chain [3] Iteration:  800 / 2000 [ 40%]  (Warmup)
Chain [3] Iteration:  900 / 2000 [ 45%]  (Warmup)
Chain [3] Iteration: 1000 / 2000 [ 50%]  (Warmup)
Chain [3] Iteration: 1001 / 2000 [ 50%]  (Sampling)
Chain [3] Iteration: 1100 / 2000 [ 55%]  (Sampling)
Chain [3] Iteration: 1200 / 2000 [ 60%]  (Sampling)
Chain [3] Iteration: 1300 / 2000 [ 65%]  (Sampling)
Chain [3] Iteration: 1400 / 2000 [ 70%]  (Sampling)
Chain [3] Iteration: 1500 / 2000 [ 75%]  (Sampling)
Chain [3] Iteration: 1600 / 2000 [ 80%]  (Sampling)
Chain [3] Iteration: 1700 / 2000 [ 85%]  (Sampling)
Chain [3] Iteration: 1800 / 2000 [ 90%]  (Sampling)
Chain [3] Iteration: 1900 / 2000 [ 95%]  (Sampling)
Chain [3] Iteration: 2000 / 2000 [100%]  (Sampling)

 Elapsed Time: 1.594 seconds (Warm-up)
               0.654 seconds (Sampling)
               2.248 seconds (Total)

Chain [4] Iteration:    1 / 2000 [  0%]  (Warmup)
Chain [4] Iteration:  100 / 2000 [  5%]  (Warmup)
Chain [4] Iteration:  200 / 2000 [ 10%]  (Warmup)
Chain [4] Iteration:  300 / 2000 [ 15%]  (Warmup)
Chain [4] Iteration:  400 / 2000 [ 20%]  (Warmup)
Chain [4] Iteration:  500 / 2000 [ 25%]  (Warmup)
Chain [4] Iteration:  600 / 2000 [ 30%]  (Warmup)
Chain [4] Iteration:  700 / 2000 [ 35%]  (Warmup)
Chain [4] Iteration:  800 / 2000 [ 40%]  (Warmup)
Chain [4] Iteration:  900 / 2000 [ 45%]  (Warmup)
Chain [4] Iteration: 1000 / 2000 [ 50%]  (Warmup)
Chain [4] Iteration: 1001 / 2000 [ 50%]  (Sampling)
Chain [4] Iteration: 1100 / 2000 [ 55%]  (Sampling)
Chain [4] Iteration: 1200 / 2000 [ 60%]  (Sampling)
Chain [4] Iteration: 1300 / 2000 [ 65%]  (Sampling)
Chain [4] Iteration: 1400 / 2000 [ 70%]  (Sampling)
Chain [4] Iteration: 1500 / 2000 [ 75%]  (Sampling)
Chain [4] Iteration: 1600 / 2000 [ 80%]  (Sampling)
Chain [4] Iteration: 1700 / 2000 [ 85%]  (Sampling)
Chain [4] Iteration: 1800 / 2000 [ 90%]  (Sampling)
Chain [4] Iteration: 1900 / 2000 [ 95%]  (Sampling)
Chain [4] Iteration: 2000 / 2000 [100%]  (Sampling)

 Elapsed Time: 1.678 seconds (Warm-up)
               0.623 seconds (Sampling)
               2.301 seconds (Total)

Loading required namespace: rstan
summary(fit)
 Family: gaussian 
  Links: mu = identity 
Formula: time ~ age * sex 
   Data: kidney (Number of observations: 76) 
  Draws: 4 chains, each with iter = 2000; warmup = 1000; thin = 1;
         total post-warmup draws = 4000

Regression Coefficients:
              Estimate Est.Error l-95% CI u-95% CI Rhat Bulk_ESS Tail_ESS
Intercept        23.88     91.17  -151.05   206.01 1.00     1242     1863
age               0.72      1.99    -3.16     4.60 1.00     1191     2031
sexfemale       164.13    107.15   -45.73   370.96 1.00     1134     1526
age:sexfemale    -2.46      2.33    -6.97     2.03 1.00     1116     1441

Further Distributional Parameters:
      Estimate Est.Error l-95% CI u-95% CI Rhat Bulk_ESS Tail_ESS
sigma   128.60     10.61   109.89   151.58 1.00     2627     2357

Draws were sampled using sample(hmc). For each parameter, Bulk_ESS
and Tail_ESS are effective sample size measures, and Rhat is the potential
scale reduction factor on split chains (at convergence, Rhat = 1).

Note that the stanli version in stanr, at the time of writing, is a bit old, so brms models with e.g. random effects doesn’t work there, yet.

Thanks for posting.

I’m surprised @WardBrian hasn’t weighed in as he has experience with this with Stan Playground. Here’s the forum link:

And here’s the project link:

If you’re serious about supporting this longer term, I’d suggest coordinating with @andrjohns and @seantalts on design as I don’t think anything’s settled yet there. I believe the Stan developers are discussing whether to roll stanr into Stan, at which point the API would become as stable as we could make it for backward compatibility.

Stan Playground definitely “cheats” a little by having compilation done by a server — I could see that part of it being updated at some point down the line as these projects mature.

I just tried the minimal reproducible example by @StaffanBetner, however, it would appear rstan is currently broken?

Running

install.packages(c('stanr', 'rstan', 'brms'), 
   repos = c('https://andrjohns.r-universe.dev', 
             'https://stan-dev.r-universe.dev', 
             'https://staffanbetner.r-universe.dev', 
             'https://repo.r-wasm.org/'))

library(brms)

fit <- brm(time ~ age * sex, data = kidney, backend = 'stanli')

Results in

Chain [4] Iteration: 2000 / 2000 [100%]  (Sampling)

 Elapsed Time: 0.097 seconds (Warm-up)
               0.036 seconds (Sampling)
               0.133 seconds (Total)

Loading required namespace: rstan
Failed with error:  ‘unable to load shared object '/usr/lib/R/library/rstan/libs/rstan.so':
  could not load dynamic lib: /usr/lib/R/library/rstan/libs/rstan.so
TypeError: resolved is not a function’
Error in .requirePackage(package) : 
  unable to load required package ‘rstan’

for me now?

I suspect it is something with the development version of rstan.

This turned out to be a bit of a rabbit hole. The initial problem was caused by mismatched RcppParallel versions. After loading a newer version, I ran into a separate issue with stanr.

Yesterday, I spent some time vibe-coding a workaround using stanli directly (with some additional helper functions for LOO with e.g. moment matching):

First, install the required packages:

install.packages(
  c("RcppParallel", "rstan", "stanli", "loo", "brms"),
  repos = c(
    "https://rcppcore.r-universe.dev",
    "https://stan-dev.r-universe.dev",
    "https://seantalts.r-universe.dev",
    "https://repo.r-wasm.org/"
  )
)

Then copy and source the contents of brm_stanli.R. For example, this now works in webR:

library(stanli)
library(brms)

fit <- brm_stanli(
  rating ~ period + carry + cs(treat),
  data = inhaler,
  family = sratio("logit"),
  prior = set_prior("normal(0, 5)"),
  chains = 2,
  cores = 4,
  control = list(adapt_delta = 0.99)
)

This was made possible by the recent addition of as_stanfit() to the stanli package.

This is only an experimental workaround, not a polished package or a proposed upstream solution, but it may be useful to anyone wanting to run brms models with Stanli in webR, or without compiling Stan models locally on a desktop system. That said, installing rstan is generally much easier on desktop platforms. 🙂

@wds15 and I were inspired by this and built an exercise environment for the Bayes pre-conference course in Leiden. The course material (slides, exercises) is open-source at Applied Modelling in Drug Development , and we wanted to have something where participants can follow along without installing anything (especially a compiler toolchain).

Our approach was a bit different in that we inject code in to brms at runtime through the stanliWebR package provided with the exercise environment such that the exercise code runs unchanged. The environment also supports running multiple chains multi-core in the browser through a similar code injection approach in the miraiWebR package.

You can try the environment at https://webr-for-brms.pages.dev, and the source code is at GitHub - luwidmer/bamdd-webr: webR for Bayesian Applied Drug Development - a Browser-Based Training Environment · GitHub

What I found even more interesting is that the results are bit-wise reproducible between my x64 and ARM64 laptops and even my phone (see webr-examples/reproducibility.R).

Also tagging @seantalts for awareness, thanks a lot for your work on stanli that enabled this!

Whoa, super cool! Thanks for tagging me. Let me know if you have any issues or feature requests. And hi @wds15 :)

Thanks so much for building this and writing it up! It’s really cool to see stanli running a whole course in the browser, and the cross-device reproducibility check is a lovely touch.

I went through stanliWebR to see what you had to work around, and stanli 0.24.0 (on R-universe now) should let you drop a good chunk of it:

  • sample_model(chain_id = k): each chain uses the same random stream as in a multi-chain run, so chains spread across webR workers now match a sequential fit exactly.
  • The data writer handles arrays of any rank and unnamed lists, so rbmi’s lists of covariance matrices go straight in.
  • extract() no longer touches your R random stream; its permutation comes from the fit’s seed.
  • parameter_names(model), and unconstrain(..., ignore_unknown = TRUE) for rstan-style init lists.
  • sort_asc/sort_desc/sort_indices_*/rank are supported (for OncoBayes2).
  • while loops whose counters size later declarations, and reject() inside functions that compute data sizes, now compile. rbmi’s MMRM model runs unmodified.
  • as_stanfit() fits now count as having a model for brms, so it won’t try to recompile them.
  • as_stanmodel(code) makes rstan::sampling() and vb() run on stanli without patching rstan. optimizing() isn’t supported yet.

I’d also love to see a backend = "stanli" in brms itself, and I’ll try to get one in upstream. Packages that ship precompiled rstan models (RBesT, OncoBayes2) still need your patching approach for now.

If anything breaks or behaves differently from your shims, please open an issue. I’d love to hear how the course goes!

Really nice to see this working end to end. For teaching it’s a big deal: the compiler toolchain is usually the first hour lost in any workshop, and the cross-device reproducibility check in the Leiden environment is a great touch.

One practical thing from my side (I mostly work on browser-heavy web apps): the first load of the Wasm packages is the slow part, so serving them with long cache headers or pre-caching them in a service worker makes repeat visits feel almost instant. Has anyone measured how much of the start-up time is downloading packages versus initialising the runtime?

@seantalts Superb! I was about to summarize what I had to have patched for the env to work, but looks like you were way ahead already :) Let me upgrade and then get back to you. The course went well I’d say. No “I can’t compile this”, and the feedback so far was very positive!

@colorfulcms: there is already a long-lived cache header sent for the library. In terms of start-up time that really depends on your connection (personally I’m a fan of https://www.init7.net/en) :)

@seantalts I upgraded the environment to stanli 0.25.0 (and removed some of the workarounds) + ran the test suite of the installed packages, and it’s looking good (stuff that needs a shell or deep stacks still fails due to webR, but the only failing OncoBayes2 test is now due to the behavior of mis-spelled arguments to RStan: bamdd-webr/lib/TEST-SKIPS.tsv at main · luwidmer/bamdd-webr · GitHub )