Fix ddm_st and ddm_normal_st fits that won't converge¶
ddm_st and ddm_normal_st add trial-to-trial variability in non-decision time to the
DDM. Both are fitted through a likelihood approximation network (LAN), a neural network
trained to return the model's log-density. Problems can appear as stuck chains or fits
that mix well but recover the wrong values.
This notebook illustrates troubleshooting steps on simulated data.
| # | symptom | cause |
|---|---|---|
| 1 | t biased, no error |
an HSSM older than 0.6.0 floors responses faster than t |
| 2 | HSSM refuses the data | negative simulated response times |
| 3 | clean diagnostics, wrong group means | the default prior on the group means |
| 4 | small, fixed bias that more data does not remove | a lapse term the data do not have |
| 5 | st values that disagree between the two models |
st means different things in each |
Prerequisites and saved results¶
Use HSSM 0.6.0 or later. It registers both models, reads the likelihood floor each one declares, and downloads their networks from franklab/HSSM on first use.
The saved tables and plots come from a full run (FULL_RUN=1: 12 subjects, 300 trials
each) with the versions and network files printed by the first cell. The default
FULL_RUN=0 is a smaller execution check; its estimates are too noisy for recovery
claims.
import hashlib
import os
import arviz as az
import bambi as bmb
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import ssms
from huggingface_hub import hf_hub_download
from ssms.basic_simulators.simulator import simulator
import hssm
from hssm.modelconfig import get_default_model_config
FULL_RUN = os.environ.get("FULL_RUN", "0") == "1"
if FULL_RUN:
N_SUBJECTS, N_TRIALS = 12, 300
SAMPLE_KWARGS = dict(chains=4, draws=1000, tune=1000)
else:
N_SUBJECTS, N_TRIALS = 6, 150
SAMPLE_KWARGS = dict(chains=2, draws=200, tune=200)
SAMPLE_KWARGS.update(
sampler="numpyro", cores=1, random_seed=0, idata_kwargs={"log_likelihood": False}
)
print(
f"hssm {hssm.__version__}, ssm-simulators {ssms.__version__}, FULL_RUN={FULL_RUN}"
)
for model in ("ddm_st", "ddm_normal_st"):
with open(hf_hub_download("franklab/HSSM", f"{model}.onnx"), "rb") as f:
print(f"{model}.onnx sha256 {hashlib.sha256(f.read()).hexdigest()[:12]}")
hssm 0.6.0, ssm-simulators 0.17.0, FULL_RUN=True ddm_st.onnx sha256 2e2aec297123
ddm_normal_st.onnx sha256 f110c0a73ee7
The model¶
On each trial the non-decision time tau is drawn from a kernel centred on t, and the
response time is tau plus the first-passage time of a Wiener process:
ddm_st: tau ~ Uniform(t - st, t + st) st is a half-width
ddm_normal_st: tau ~ Normal(t, st) st is a standard deviation
decision time, response = first passage with drift v, boundaries -a and +a,
starting point -a + 2 * a * z
rt = tau + decision time
HSSM evaluates, for each trial,
p(rt, response) = (1 - p_outlier) * f_LAN(rt, response | v, a, z, t, st)
+ p_outlier * Uniform(rt; 0, 20)
where f_LAN is the network's density, with a likelihood floor applied at or below the
declared edge (section 1). For ddm_st this is a hard support edge; for ddm_normal_st it
is a practical policy for an unbounded kernel.
We simulate ddm_st data for several subjects. v, a, z and t vary by subject;
st is shared. There are no lapses in these data.
rng = np.random.default_rng(2026)
ST_TRUE = 0.13
subjects = pd.Index([f"s{i}" for i in range(N_SUBJECTS)], name="subject")
truth = pd.DataFrame(
{
"v": np.clip(rng.normal(1.0, 0.30, N_SUBJECTS), -2.5, 2.5),
"a": np.clip(rng.normal(1.2, 0.20, N_SUBJECTS), 0.5, 2.0),
"z": np.clip(rng.normal(0.5, 0.05, N_SUBJECTS), 0.35, 0.65),
"t": np.clip(rng.normal(0.4, 0.05, N_SUBJECTS), 0.30, 0.55),
},
index=subjects,
)
frames = []
for i, (subject, row) in enumerate(truth.iterrows()):
sim = simulator(
model="ddm_st",
theta={**row.to_dict(), "st": ST_TRUE},
n_samples=N_TRIALS,
random_state=i,
)
frames.append(
pd.DataFrame(
{
"rt": sim["rts"].ravel(),
"response": sim["choices"].ravel(),
"subject": subject,
}
)
)
data = pd.concat(frames, ignore_index=True)
data = data[data["rt"] > 0].reset_index(drop=True) # section 2
print(f"{len(data)} trials from {N_SUBJECTS} subjects")
truth.round(3)
3600 trials from 12 subjects
| v | a | z | t | |
|---|---|---|---|---|
| subject | ||||
| s0 | 0.762 | 1.187 | 0.532 | 0.374 |
| s1 | 1.072 | 1.183 | 0.591 | 0.377 |
| s2 | 0.431 | 1.232 | 0.464 | 0.425 |
| s3 | 1.419 | 1.077 | 0.567 | 0.444 |
| s4 | 1.191 | 1.119 | 0.438 | 0.410 |
| s5 | 0.912 | 1.310 | 0.509 | 0.369 |
| s6 | 0.906 | 1.174 | 0.442 | 0.359 |
| s7 | 1.091 | 0.925 | 0.568 | 0.472 |
| s8 | 0.920 | 1.105 | 0.542 | 0.430 |
| s9 | 0.932 | 1.331 | 0.557 | 0.436 |
| s10 | 1.216 | 1.154 | 0.456 | 0.509 |
| s11 | 1.154 | 1.170 | 0.534 | 0.359 |
1. Responses faster than t¶
Symptom: t comes out biased, with no error and no warning.
Non-decision time varies around t, so a response can be faster than t whenever the
decision itself takes less time than the kernel shifts it. HSSM floors the likelihood of any
response at or below the declared edge. For a plain DDM that edge is t. ddm_st declares
the hard support edge t - st; ddm_normal_st uses a practical floor at t - 3 * st,
although its Normal kernel has no finite lower support edge. How many responses fall in
between depends on the design: none in the saved data above, and many when boundaries
are close and st is wide.
below_t = (data["rt"] < data["subject"].map(truth["t"])).mean()
print(f"simulated data above: {below_t:.1%} of responses faster than t")
close = {"v": 1.0, "a": 0.5, "z": 0.5, "t": 0.4, "st": 0.3}
for model in ("ddm_st", "ddm_normal_st"):
rts = simulator(model=model, theta=close, n_samples=100_000, random_state=0)["rts"]
share = np.mean(rts < close["t"])
print(f"{model:14s} at a=0.5, st=0.3: {share:.1%} of responses faster than t")
print()
for model in ("ddm_st", "ddm_normal_st"):
likelihood = get_default_model_config(model)["likelihoods"]["approx_differentiable"]
print(
f"{model:14s} likelihood floor at t - "
f"{likelihood['ndt_edge_shift']['scale']} * st"
)
simulated data above: 0.0% of responses faster than t
ddm_st at a=0.5, st=0.3: 18.0% of responses faster than t
ddm_normal_st at a=0.5, st=0.3: 24.6% of responses faster than t ddm_st likelihood floor at t - 1.0 * st ddm_normal_st likelihood floor at t - 3.0 * st
HSSM 0.6.0 and later read this declaration (#1292). Earlier versions floor every response
faster than t, discarding the density of the trials counted above. The fit still runs, t
moves to compensate, and the result looks like awkward sampler geometry.
Fix: use HSSM 0.6.0 or later.
2. Negative simulated response times¶
Symptom: HSSM refuses to build the model from data containing negative response times.
Where st is large and t small, the kernel reaches below zero, and so do some simulated
response times. At the corner of the training box:
corner = {"v": 0.0, "a": 0.3, "z": 0.5, "t": 0.25, "st": 0.35}
for model in ("ddm_st", "ddm_normal_st"):
rts = simulator(model=model, theta=corner, n_samples=100_000, random_state=0)["rts"]
print(f"{model:14s} {np.mean(rts <= 0):5.1%} of responses at or below zero")
bad = pd.DataFrame({"rt": [-0.05, 0.40, 0.55], "response": [1, -1, 1]})
try:
hssm.HSSM(data=bad, model="ddm_st")
except ValueError as err:
if str(err) != (
"You have negative response times in your dataset, which is not allowed."
):
raise
print(f"\n{type(err).__name__}: {err}")
else:
raise AssertionError("Expected the negative-RT validation error.")
ddm_st 4.1% of responses at or below zero ddm_normal_st 16.3% of responses at or below zero ValueError: You have negative response times in your dataset, which is not allowed.
Fix for this positive-RT simulation workflow: filter to rt > 0, as the simulation
cell above does. HSSM's input validator rejects negative RTs; it currently permits zero,
which this preprocessing also removes. This is a simulated-data check, not a general
rule for silently deleting recorded observations.
Keep every parameter inside the bounds the model declares. These are the networks' training box, rather than a guarantee of uniform approximation accuracy inside it:
BOUNDS = get_default_model_config("ddm_st")["likelihoods"]["approx_differentiable"][
"bounds"
]
pd.DataFrame(BOUNDS, index=["lower", "upper"])
| v | a | z | t | st | |
|---|---|---|---|---|---|
| lower | -3.0 | 0.3 | 0.3 | 0.25 | 0.001 |
| upper | 3.0 | 2.5 | 0.7 | 2.25 | 0.350 |
3. Clean diagnostics, wrong group means¶
Symptom: the hierarchical fit converges (r-hat near 1, no divergences) and the per-subject estimates look right, but the group-level means and spreads are wrong.
Each parameter is modelled on the link scale. With link_settings="log_logit" a parameter
bounded on both sides uses the generalized logit, so for parameter p with bounds (lo, hi):
p[subject] = lo + (hi - lo) / (1 + exp(-eta[subject]))
eta[subject] ~ Normal(mu_p, sigma_p)
mu_p ~ Normal(0, 0.25) HSSM's default for a group intercept
sigma_p ~ Weibull(1.5, 0.3)
The HSSM formula is p ~ 0 + (1|subject) for each of v, a, z, t. mu_p = 0 maps to
the midpoint of the bounds, so a narrow prior around 0 pulls every group mean toward that
midpoint.
PARAMS = ["v", "a", "z", "t"]
def hierarchical(prior=None, p_outlier=None):
"""ddm_st with a subject-level intercept on v, a, z and t; st shared."""
include = [
{
"name": p,
"formula": f"{p} ~ 0 + (1|subject)",
**({"prior": {"1|subject": prior}} if prior is not None else {}),
}
for p in PARAMS
]
return hssm.HSSM(
data=data,
model="ddm_st",
include=include,
p_outlier=p_outlier,
link_settings="log_logit",
prior_settings="safe",
noncentered=False,
)
idata_default = hierarchical().sample(**SAMPLE_KWARGS)
Model initialized successfully.
Using default initvals.
def diagnostics(idata, label):
"""Worst-case convergence numbers over every parameter in the posterior."""
summary = az.summary(idata)
return pd.Series(
{
"worst r_hat": summary["r_hat"].max(),
"min ESS bulk": summary["ess_bulk"].min(),
"divergent %": 100
* float(np.asarray(idata.sample_stats["diverging"]).mean()),
},
name=label,
)
def inv_link(eta, p):
"""Map link-scale values of parameter `p` back into its bounds."""
lo, hi = BOUNDS[p]
return lo + (hi - lo) / (1 + np.exp(-eta))
def population(idata, label, n_draws=400, n_subjects=4000, seed=0):
"""Estimate the population mean and SD on the natural scale.
The group distribution lives on the link scale, so it is pushed through the
inverse link by simulation; inv_link(mu_p) alone is the median, not the mean.
"""
rng = np.random.default_rng(seed)
post = idata.posterior
rows = {}
for p in PARAMS:
mu = np.asarray(post[f"{p}_1|subject_mu"]).ravel()
sigma = np.asarray(post[f"{p}_1|subject_sigma"]).ravel()
pick = rng.choice(mu.size, size=n_draws, replace=False)
x = inv_link(
rng.normal(mu[pick, None], sigma[pick, None], (n_draws, n_subjects)), p
)
rows[p] = {"mean": x.mean(), "SD": x.std(axis=1).mean()}
rows["st"] = {"mean": float(np.asarray(post["st"]).mean()), "SD": np.nan}
return pd.DataFrame(rows).T.add_prefix(f"{label} ")
TRUE_POP = pd.DataFrame(
{"true mean": [*truth.mean(), ST_TRUE], "true SD": [*truth.std(ddof=0), np.nan]},
index=[*PARAMS, "st"],
)
print(diagnostics(idata_default, "default prior").round(3).to_string())
pd.concat([TRUE_POP, population(idata_default, "default")], axis=1).round(3)
worst r_hat 1.004 min ESS bulk 1588.137 divergent % 0.000
| true mean | true SD | default mean | default SD | |
|---|---|---|---|---|
| v | 1.001 | 0.242 | 0.927 | 0.331 |
| a | 1.164 | 0.102 | 1.189 | 0.121 |
| z | 0.517 | 0.051 | 0.512 | 0.045 |
| t | 0.414 | 0.046 | 0.922 | 0.428 |
| st | 0.130 | NaN | 0.131 | NaN |
The diagnostics give no hint of a problem. The group mean of t has moved from 0.41 to 0.92,
more than halfway to the midpoint of its bounds (1.25), and its spread is inflated about nine
times, which keeps every subject reachable from the misplaced mean. v, a and z survive
on this dataset; on others v moves too.
Sensitivity check for this example: widen the group-mean prior while keeping
the other settings fixed. Choose priors using domain knowledge and prior-predictive
checks; Normal(0, 2) is not a universal remedy. See group priors.
group_prior = bmb.Prior(
"Normal",
mu=bmb.Prior("Normal", mu=0.0, sigma=2.0),
sigma=bmb.Prior("Weibull", alpha=1.5, beta=0.3),
)
idata_wide = hierarchical(group_prior).sample(**SAMPLE_KWARGS)
print(
pd.concat(
[
diagnostics(idata_default, "default prior"),
diagnostics(idata_wide, "Normal(0, 2)"),
],
axis=1,
)
.round(3)
.to_string()
)
pd.concat(
[
TRUE_POP,
population(idata_default, "default"),
population(idata_wide, "Normal(0, 2)"),
],
axis=1,
).round(3)
Model initialized successfully.
Using default initvals.
default prior Normal(0, 2) worst r_hat 1.004 1.004 min ESS bulk 1588.137 1100.093 divergent % 0.000 0.000
| true mean | true SD | default mean | default SD | Normal(0, 2) mean | Normal(0, 2) SD | |
|---|---|---|---|---|---|---|
| v | 1.001 | 0.242 | 0.927 | 0.331 | 1.003 | 0.320 |
| a | 1.164 | 0.102 | 1.189 | 0.121 | 1.174 | 0.111 |
| z | 0.517 | 0.051 | 0.512 | 0.045 | 0.513 | 0.046 |
| t | 0.414 | 0.046 | 0.922 | 0.428 | 0.415 | 0.048 |
| st | 0.130 | NaN | 0.131 | NaN | 0.127 | NaN |
In the saved run the wider prior recovers the group summaries: the group mean of t is
0.415 against a simulated 0.414, and its spread 0.048 against 0.046. The fit has no
divergent transitions (r-hat 1.004; the minimum bulk ESS is about 1,100, lower than under
the default prior). One dataset does not establish reliable inference in general. On your
own data, investigate divergent transitions even when r-hat and ESS look reassuring:
inspect their locations and the model geometry, compare an appropriate reparameterization
or a higher target_accept, then rerun and check the diagnostics. See
HMC divergence guidance.
The trace of each group mean shows the same thing. The dashed line is the median of the
true subject values, which is what inv_link(mu_p) estimates. Agreeing, well-mixed chains
far from that line are what a converged but wrong fit looks like.
def plot_group_medians(idata, title):
"""Plot each chain of inv_link(mu_p) against the median of the true values."""
fig, axes = plt.subplots(1, len(PARAMS), figsize=(14, 2.6))
post = idata.posterior
for ax, p in zip(axes, PARAMS):
for chain in np.asarray(post[f"{p}_1|subject_mu"]):
ax.plot(inv_link(chain, p), lw=0.5)
ax.axhline(truth[p].median(), color="k", ls="--")
ax.set_title(f"inv_link(mu_{p})")
ax.set_xlabel("draw")
fig.suptitle(title)
fig.tight_layout()
plot_group_medians(idata_default, "default prior Normal(0, 0.25): converged, and wrong")
plot_group_medians(idata_wide, "Normal(0, 2): converged, and right")
4. A lapse term the data do not have¶
Symptom: a small bias that does not shrink as the dataset grows.
p_outlier mixes a uniform lapse distribution into every trial. HSSM's default is 0.05; the
fits above used p_outlier=None because these simulated data contain no lapses. Fitting the
same data with the default lapse:
idata_lapse = hierarchical(group_prior, p_outlier=0.05).sample(**SAMPLE_KWARGS)
pd.concat(
[
TRUE_POP,
population(idata_wide, "p_outlier=None"),
population(idata_lapse, "p_outlier=0.05"),
],
axis=1,
).round(3)
Model initialized successfully.
Using default initvals.
| true mean | true SD | p_outlier=None mean | p_outlier=None SD | p_outlier=0.05 mean | p_outlier=0.05 SD | |
|---|---|---|---|---|---|---|
| v | 1.001 | 0.242 | 1.003 | 0.320 | 1.075 | 0.325 |
| a | 1.164 | 0.102 | 1.174 | 0.111 | 1.171 | 0.107 |
| z | 0.517 | 0.051 | 0.513 | 0.046 | 0.502 | 0.043 |
| t | 0.414 | 0.046 | 0.415 | 0.048 | 0.414 | 0.048 |
| st | 0.130 | NaN | 0.127 | NaN | 0.126 | NaN |
On one dataset the difference is small and could go either way. The systematic effect needs many datasets: on the plain DDM with its exact likelihood over 12 datasets, 94% intervals covered the truth 96% of the time without the lapse and 88% with 0.05, at 500 trials, and the gap grows with more trials (LAN_pipeline_minimal's recovery guide).
Fix: match the lapse to the data.
- Simulated data without lapses:
p_outlier=None. - Real data: choose and check a lapse model that matches the experiment. The default 0.05 is an assumption, not a measured lapse rate; inspect its effect on the fit.
The lapse does not unstick stuck chains. If the chains are stuck, look at sections 1 to 3.
5. st in ddm_normal_st¶
Everything above applies to ddm_normal_st too, with the same settings. Three things
differ. st is a standard deviation there and a half-width in ddm_st, so equal values are
not equal amounts of variability. The non-decision-time kernels of the two models, drawn
at the same st:
st = 0.2
for model in ("ddm_st", "ddm_normal_st"):
kernel = ssms.config.model_config[model]["simulator_param_mappings"]["t_dist"](st)
draws = kernel(size=200_000, random_state=0)
print(
f"{model:14s} st={st}: SD of the kernel {draws.std():.3f}, "
f"lowest draw {draws.min():+.3f}"
)
print(
f"\nst={st} in ddm_st has the spread of st={st / np.sqrt(3):.3f} in ddm_normal_st"
)
ddm_st st=0.2: SD of the kernel 0.116, lowest draw -0.200 ddm_normal_st st=0.2: SD of the kernel 0.200, lowest draw -0.970 st=0.2 in ddm_st has the spread of st=0.115 in ddm_normal_st
The other two differences were shown above: the practical likelihood floor is
t - 3 * st, rather than the uniform model's hard edge t - st (section 1), and the box
corner yields more non-positive response times (section 2).
Approximation error is network-specific. Consult the model card and validation/recovery reports for the exact ONNX file used in the fit; results from a superseded network do not establish the behavior of its replacement. Check persistent recovery errors against an exact reference before attributing them to sampler tuning or priors.
Checklist¶
- HSSM 0.6.0 or later. Record the HSSM and ssm-simulators versions and the networks' hashes.
- Simulated data: drop
rt <= 0; keep parameters inside the declared bounds. - Hierarchical fits: check prior sensitivity and group-level recovery as well as convergence; investigate divergent transitions.
p_outlier=Nonefor lapse-free simulated data; assess the lapse model for real data.- Do not compare
stacross the two models without converting.