8000 An LNR program that keeps cogmod's log density and runs faster on CmdStan and stanli · Issue #5 · DominiqueMakowski/cogmod · GitHub
[go: up one dir, main page]

Skip to content

An LNR program that keeps cogmod's log density and runs faster on CmdStan and stanli #5

Open

Description

@seantalts

Thanks for cogmod, and for the careful LNR report on stanli (seantalts/stanli#422). While working on it we wrote a version of the LNR program that keeps cogmod's numerics but runs faster on both CmdStan and stanli. It may be useful as a starting point, so here it is with what we measured. It is an experiment on one benchmark, not a drop-in replacement for the family.

The starting point is the program brms generates for the LNR benchmark from that issue (speed_acc, participants 1 to 3, N = 4620, sigmabias = 0), compared with that program and with your select version.

What changes

  • Observations are split by dec in transformed data, so winner and loser parameters are an exact gather instead of a per-observation branch.
  • The likelihood is computed with vector operations over each dec group instead of a per-observation function call.
  • Each parameter-dependent branch becomes a blend w * a + (1 - w) * b with w exactly 0 or 1, decided by the same comparison as the original (t <= 0, x > 0, x < -25). Each arm is evaluated on an input clamped into its own domain, so the arm not taken is finite and contributes exactly 0. All three arms of cogmod_log_Phi are kept, including log1p(-0.5 * erfc(x / sqrt2)) above 0 and the asymptotic series below -25.
  • The time cutoff keeps log(poutlier) + lp_out exactly for t <= 0.
  • The argument checks are kept, as a branch-free expression that returns -inf when they fail.
  • The per-observation values are summed in the original order, so the log density matches the original exactly.

Speed

Per gradient during NUTS sampling (seed 1, 50 warmup and 50 draws, one chain, warmup included, wall time over leapfrog steps), Apple M-series, medians of repeated runs:

engine brms program select version this rewrite
CmdStan 1.29 ms 2.02 ms 1.09 ms
stanli (main) 0.85 ms 0.64 ms 0.57 ms

On CmdStan with warm fixed-point gradients the rewrite was also 1.15x (stanc O0) to 1.23x (O1) faster than the brms program.

Precision

Compared with the brms program at 135 points (posterior draws and random points) and 147 edge points (x = -25, 0 and neighbouring floats, Y = ndt and its neighbours, every Y below ndt, an empty dec group, extreme links):

  • Log density: identical to the last bit on CmdStan at every point; within 48 ULP on stanli.
  • Gradients: not bitwise. The largest differences are on Intercept_sigmaone, Intercept_sigmazero and poutlier, up to about 4.7e4 ULP; the other components are within about 1.6e3 ULP. These gradients are sums over 4620 observations with heavy cancellation, and the brms program itself is up to about 5e4 ULP from a 50-digit reference on the same components, so the rewrite is in the same range. Against that reference it is somewhat noisier than the original on Intercept_sigmaone, b_ndt and poutlier (for example the median error on b_ndt is 78 ULP against 25), and within about 2x on the rest.

Where it differs from the brms program

  • At poutlier exactly 1 the poutlier gradient is NaN where the original's is finite (0 * inf through log1m).
  • Where the log density is -inf, the gradient is 0.
  • Domain errors that the original raises inside lognormal_lpdf or log_mix show up as a non-finite log density instead of an exception. NUTS rejects those points either way.
  • It is specific to this benchmark: scalar sigmazero, sigmaone and poutlier, and sigmabias fixed at 0. A general version for the family would need the vector-parameter cases and the start-point variability path.
The program
// The LNR benchmark program from brms 2.23.0, rewritten by hand (see above).
functions {
  vector lnr_log_Phi(vector x, int n) {
    vector[n] wh = ceil(fmin(fmax(x, 0.0), 1.0));
    vector[n] he = 0.5 * erfc(((2 * wh - 1) .* fmax(x, -25.0)) * 0.7071067811865476);
    vector[n] res = (1 - wh) .* log(he + wh) + wh .* log1p(-he);
    if (min(x) < -25.0) {
      vector[n] wl = ceil(fmin(fmax(-25.0 - x, 0.0), 1.0));
      vector[n] xl = fmin(x, -25.0);
      vector[n] z = inv_square(xl);
      vector[n] series = 1 + z .* (-1 + z .* (3 + z .* (-15 + z .* (105 - 945 * z))));
      res = wl .* (-0.5 * square(xl) - log(-xl) - 0.91893853320467274 + log(series))
            + (1 - wl) .* res;
    }
    return res;
  }

  vector lnr_group(int n, vector Yg, vector lpout, vector nu_w, real s_w, vector nu_l,
                   real s_l, vector ndt, real lp, real l1mp, real tfloor,
                   vector ones) {
    vector[n] t = Yg - ndt;
    vector[n] w = ceil(fmin(fmax(t, 0.0), 1.0));
    vector[n] lt = log(fmax(t, tfloor));
    vector[n] sw = s_w * ones;
    vector[n] isq = square(inv(sw));
    vector[n] lognorm = -0.91893853320467274 - 0.5 * (square(lt + nu_w) .* isq)
                        - log(sw) - lt;
    vector[n] lpdec = lognorm + lnr_log_Phi((-nu_l - lt) ./ (s_l * ones), n);
    vector[n] a = lp * ones + lpout;
    vector[n] mix = log_sum_exp(a, l1mp * ones + lpdec);
    return w .* mix + (1 - w) .* a;
  }
}
data {
  int<lower=1> N;  // total number of observations
  vector[N] Y;  // response variable
  array[N] int<lower=0,upper=1> dec;  // decisions
  int<lower=1> K;  // number of population-level effects
  matrix[N, K] X;  // population-level design matrix
  int<lower=1> Kc;  // number of population-level effects after centering
  int<lower=1> K_nuone;  // number of population-level effects
  matrix[N, K_nuone] X_nuone;  // population-level design matrix
  int<lower=1> Kc_nuone;  // number of population-level effects after centering
  int<lower=1> K_ndt;  // number of population-level effects
  matrix[N, K_ndt] X_ndt;  // population-level design matrix
  int<lower=1> Kc_ndt;  // number of population-level effects after centering
  int prior_only;  // should the likelihood be ignored?
}

transformed data {
  real min_Y = min(Y);
  matrix[N, Kc] Xc;  // centered version of X without an intercept
  vector[Kc] means_X;  // column means of X before centering
  matrix[N, Kc_nuone] Xc_nuone;  // centered version of X_nuone without an intercept
  vector[Kc_nuone] means_X_nuone;  // column means of X_nuone before centering
  matrix[N, Kc_ndt] Xc_ndt;  // centered version of X_ndt without an intercept
  vector[Kc_ndt] means_X_ndt;  // column means of X_ndt before centering
  for (i in 2:K) {
    means_X[i - 1] = mean(X[, i]);
    Xc[, i - 1] = X[, i] - means_X[i - 1];
  }
  for (i in 2:K_nuone) {
    means_X_nuone[i - 1] = mean(X_nuone[, i]);
    Xc_nuone[, i - 1] = X_nuone[, i] - means_X_nuone[i - 1];
  }
  for (i in 2:K_ndt) {
    means_X_ndt[i - 1] = mean(X_ndt[, i]);
    Xc_ndt[, i - 1] = X_ndt[, i] - means_X_ndt[i - 1];
  }
  int n_bad = 0;
  int N1 = 0;
  for (n in 1:N) {
    if (Y[n] <= 0) n_bad += 1;
    else N1 += dec[n];
  }
  int N0 = N - n_bad - N1;
  array[N0] int idx0;
  array[N1] int idx1;
  {
    int k0 = 0;
    int k1 = 0;
    for (n in 1:N) {
      if (Y[n] > 0) {
        if (dec[n] == 0) {
          k0 += 1;
          idx0[k0] = n;
        } else {
          k1 += 1;
          idx1[k1] = n;
        }
      }
    }
  }
  vector[N0] Y0 = Y[idx0];
  vector[N1] Y1 = Y[idx1];
  vector[N0] lpout0 = 0.6904993792294275 - 12.5 * square(Y0);
  vector[N1] lpout1 = 0.6904993792294275 - 12.5 * square(Y1);
  vector[N0] ones0 = rep_vector(1.0, N0);
  vector[N1] ones1 = rep_vector(1.0, N1);
  real tfloor = 1e-300;
  if (N0 + N1 > 0) tfloor = fmax(1e-300, min(append_row(Y0, Y1)) * 8.673617379884035e-19);
}
parameters {
  vector[Kc] b;  // regression coefficients
  real Intercept;  // temporary intercept for centered predictors
  vector[Kc_nuone] b_nuone;  // regression coefficients
  real Intercept_nuone;  // temporary intercept for centered predictors
  real Intercept_sigmazero;  // temporary intercept for centered predictors
  real Intercept_sigmaone;  // temporary intercept for centered predictors
  vector[Kc_ndt] b_ndt;  // regression coefficients
  real Intercept_ndt;  // temporary intercept for centered predictors
  real<lower=0,upper=1> poutlier;
}
transformed parameters {
  real sigmabias = 0;
  // prior contributions to the log posterior
  real lprior = 0;
  lprior += student_t_lpdf(Intercept | 3, 0.6, 2.5);
  lprior += normal_lpdf(b_nuone | 0, 0.5);
  lprior += normal_lpdf(Intercept_nuone | 0.7, 1.5);
  lprior += normal_lpdf(Intercept_sigmazero | 0, 1);
  lprior += normal_lpdf(Intercept_sigmaone | 0, 1);
  lprior += normal_lpdf(b_ndt | 0, 0.2);
  lprior += normal_lpdf(Intercept_ndt | -1.2, 0.5);
  lprior += exponential_lpdf(poutlier | 100)
    - 1 * exponential_lcdf(1 | 100);
}
model {
  // likelihood including constants
  if (!prior_only) {
    vector[N] mu = Intercept + Xc * b;
    vector[N] nuone = Intercept_nuone + Xc_nuone * b_nuone;
    vector[N] ndt = exp(Intercept_ndt + Xc_ndt * b_ndt);
    real sigmazero = log1p_exp(Intercept_sigmazero);
    real sigmaone = log1p_exp(Intercept_sigmaone);
    if (n_bad > 0) {
      target += negative_infinity();
    } else {
      int bad = sigmazero <= 0 || sigmaone <= 0 || sigmabias < 0 || poutlier < 0
                || poutlier > 1 || (poutlier <= 0 && max(ndt - Y) >= 0);
      real ok = 1 - bad;
      real sz = sigmazero * ok + bad;
      real so = sigmaone * ok + bad;
      real pout = (poutlier + (poutlier <= 0) * 4.9406564584124654e-324) * ok
                  + 0.5 * bad;
      real lp = log(pout);
      real l1mp = log1m(pout);
      vector[N] per;
      per[idx0] = lnr_group(N0, Y0, lpout0, mu[idx0], sz, nuone[idx0], so,
                            ndt[idx0], lp, l1mp, tfloor, ones0);
      per[idx1] = lnr_group(N1, Y1, lpout1, nuone[idx1], so, mu[idx1], sz,
                            ndt[idx1], lp, l1mp, tfloor, ones1);
      target += ok * sum(per) + log(ok);
    }
  }
  // priors including constants
  target += lprior;
}
generated quantities {
  // actual population-level intercept
  real b_Intercept = Intercept - dot_product(means_X, b);
  // actual population-level intercept
  real b_nuone_Intercept = Intercept_nuone - dot_product(means_X_nuone, b_nuone);
  // actual population-level intercept
  real b_sigmazero_Intercept = Intercept_sigmazero;
  // actual population-level intercept
  real b_sigmaone_Intercept = Intercept_sigmaone;
  // actual population-level intercept
  real b_ndt_Intercept = Intercept_ndt - dot_product(means_X_ndt, b_ndt);
}

The harness and point sets are available if they would help.

Activity

  1. DominiqueMakowski commented on Oct 4, 2026

    @DominiqueMakowski
    Owner

    Thanks a lot @seantalts for digging into our code; making these heavy models more efficient is really a work in progress and any small improvements yields massive benefits in practice

    We double-checked the numbers:

    • Exact, as you said: on CmdStan it gives the brms program's log density bit for bit at all 46 points we tried (36 around the init, 9 edge points, one trial at x = -65), on Windows and on Linux. The gradient agrees to 3e-13, and the finiteness differences are the ones you listed.
    • Faster, but on CmdStan the gain is in the sigmas, not the likelihood. The rewrite changes two things at once: 1) it declares sigmazero and sigmaone as reals (one softplus each instead of one per trial), and 2) it rewrites the likelihood. To separate them we added two variants: the brms program with only the sigmas made real (same log density, bit for bit), and your rewrite with brms's vector sigmas. Time per gradient relative to the version without the change (lower is faster):
    change CmdStan, Windows CmdStan, Linux stanli 0.19.1
    sigmas as reals 0.70 0.80-0.85 0.82-0.87
    rewritten likelihood 1.05-1.10 0.92-1.02 0.83-0.94
    both (your program as posted) 0.75 0.75-0.84 0.75-0.79

    On CmdStan the sigmas are the whole gain, and on stanli the two add up.

    So I'm tempted to keep the family's looped likelihood for now. On CmdStan the likelihood rewrite buys at most 8% on linux, but comes with some limitations: as a vectorised custom family it would also need a signature per formula, would lose weights()/cens()/trunc() features, and would misalign dec under brms threading (we measured this route before).

    The sigmas, though, are a real win, for every brms model and not only cogmod's, so we've suggested it to brms: paul-buerkner/brms#1945, with a PR in paul-buerkner/brms#1946.

    Thanks again, much appreciated you chiming in ☺️ !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      0