Skip to content

SLDS posteriors via smooth, tied_params, and a green suite - #11

Merged
harrisonritz merged 4 commits into
claude/poisson-slds-fa-hmm-vr5llofrom
claude/merge-ccn2026-posteriors-xfyp6p
Aug 24, 2026
Merged

harrisonritz merged 4 commits into
claude/poisson-slds-fa-hmm-vr5llofrom
claude/merge-ccn2026-posteriors-xfyp6p

Conversation

@harrisonritz

@harrisonritz harrisonritz commented Aug 22, 2026 •

Copy link
Copy Markdown
Owner

Four commits.

  1. af5a334 — the SLDS posterior work from CCN2026 (Add posterior function to estimate MLE/MAP elbo, responsibility, and smoothed states depasquale-lab/StateSpaceDynamics.jl#161).
  2. 04f126c — the test failures that were already here.
  3. b78287d — tie_emissions → tied_params, and the docs build.
  4. 3fcb50b — parameter names become literal; partial ties solved by GLS.

1. posterior → smooth

Both did the same job by the same coordinate ascent, differing in how the discrete layer is scored:

posterior (this branch) smooth (CCN2026)
discrete layer scored at a sample from q(x) the smoothed mean E_q[x]
reproducible only with a fixed rng yes, no rng at all
stopping fixed max_iter max|Δγ| < tol, capped at smoothing_iters
returns (x_smooth, p_smooth, γ, elbos) (; x, γ, elbo, p), p opt-in
  • smooth(slds, y; smoothing_iters=100, tol=1e-6, return_cov=false, progress=false, depends_on=nothing) returns one NamedTuple, following smooth(lds, y)'s shape convention. depends_on keeps the stitching path available.
  • elbo(slds, y) is that call's elbo field — deterministic, no rng (breaking).
  • loglikelihood(slds, y) returns the ELBO instead of throwing (breaking).
  • fit!(slds, y; smoothing_iters=n); the default of 1 leaves existing fits bit-identical.
  • posterior is removed.

The alternation is one _vem_alternate! shared by fit!'s E-step and smooth, with x_samples === nothing selecting the deterministic coupling.

One test needed more than a rename. test_SLDS_smooth_recovers_regimes separated its regimes only by dynamics at R = I against Q = 0.01·I — not identifiable, and not a regression either: the old test_SLDS_posterior_recovers_regimes standalone on claude/poisson-slds-fa-hmm-vr5llo gives 0.571, under its own > 0.7 bar. Now R = 0.01·I against Q = 0.05·I, asserting > 0.9 (observed 1.0) plus an occupancy check.


2. Getting the suite green

Four pre-existing failures. On claude/poisson-slds-fa-hmm-vr5llo itself: 1105 passing / 21 erroring, with Aqua / JET / JuliaFormatter skipped.

  • Multi-trial rand(lds, tsteps_per_trial) never ran. state_params/obs_params were assigned from two branches of an if and captured by the tforeach closure, so Julia boxed them and OhMyThreads rejected it. 19 of the 21 errors.
  • tie_emissions=true fitted the emission from an uninitialized workspace. The unit-weight aggregator seeds from data-only constant blocks only the LDS/PLDS fit! paths fill; reading undef, Szz_Ab/Szz_Cd came out indefinite (eigenvalues ≈ -8). Crashing was the lucky outcome — where it didn't throw, [C d D] and R were fitted from garbage.
  • JET: _slds_trial_elbo's ll scratch widened to a union with an Any-eltype branch. JuliaFormatter: eight files, six untouched by this branch.
  • docs/examples/SLDS.jl stopped reaching into estep! behind a warning that there is no public posterior-decoding API — which commit 1 adds.

3. tied_params

tie_emissions could only tie the emission. It becomes tied_params, taking a Symbol or a collection, and ties any parameter. tie_emissions is removed rather than deprecated, per your call.

The M-step expresses "tied across regimes" as a slot vector over the regimes and hands it to the same _grouped_update_*! helpers depends_on already uses. Both SLDS M-steps collapse onto that path, which let _update_tied_emission! and _update_tied_emission_grouped! go away; the grouped path also lost its per-regime loop.

A grouped-fit bug the same primitive closes. A grouped fit pooling a regression over units with different noise versions — depends_on = (R = session, …) with one emission across sessions — was solving the pooled normal equations, which do not maximize the ELBO there. Flagging it because it changes depends_on behavior beyond what you asked for; easy to revert.

Docs build. set_group_seeds! is exported and documented but was in no @docs block, so Documenter raised missing_docs plus four unresolved @refs.


4. Literal names, and partial ties

A name used to stand in for the group it is fitted with — :A meant [A b B], :C meant [C d D] — in depends_on as well as tied_params. Names now mean themselves everywhere.

depends_on (breaking)

depends_on = (C = session, R = session)                            # now an error
depends_on = (C = session, d = session, D = session, R = session)  # spell it out

The error names the missing members and the regression they belong to. A model with no observation input has no D to fit, so (C, d) is the whole group there — which is why most call sites gain one key rather than two.

group_labels, group_parameter and set_group_seeds! are unaffected: they look a parameter up rather than declaring anything, so an individual name is still exactly what they want.

Partial ties

tied_params = :C no longer widens to the emission. Naming part of a jointly fitted regression is a partial tie, and where there is a way to fit one, it is fitted rather than rejected:

fit!(slds, y; tied_params = (:C, :d, :D, :R))   # whole emission tied
fit!(slds, y; tied_params = :C)                 # C shared, d and D per regime

Sharing part of a regression is still linear, and it reduces to sharing all of it. Stationarity in a regime's free block gives that block in closed form — the regime's own covariance cancels, since only its term involves it. Substituting it into the shared block's condition leaves exactly the system _tied_gls_regression already solves, over statistics with the free columns projected out (Frisch–Waugh–Lovell), one extra |free|-square solve per regime:

$$\tilde S_{zz,k} = S_{zz,k}[t,t] - S_{zz,k}[t,f],S_{zz,k}[f,f]^{-1}S_{zz,k}[f,t]$$

So the pooled fit, the whole-regression GLS and the partial tie are one estimator at three levels of sharing — verified: the partial solver returns _tied_gls_regression's answer exactly when every column is tied, and that in turn returns mn_map's exactly when the covariances agree.

Tied Estimator Cost
regression and covariance pooled M-step O(m³)
covariance alone per-regime scatters, summed O(m³)
regression alone GLS O((p·m)³)
part of a regression free columns projected out, then that GLS O((p·m′)³)

An MN prior is split between the shared and free blocks when its column precision Λ does not couple them (a diagonal Λ always qualifies); one that does throws rather than dropping the cross term.

Two partial ties have no reduction and throw, per your "informative error unless GLS resolves it":

  • a Poisson [C d D], fitted by LBFGS rather than from sufficient statistics;
  • a partial tie alongside depends_on, which already splits the regression per group of trials, so the tie would have to partition columns and cells at once.

Both are fine with the whole regression tied.

Tests

Literal-name resolution; each name ties exactly its own parameter; depends_on rejects a group named only in part, on the model and as a call-site override; the two unfittable partial ties throw and their whole-regression forms work; a diagonal prior splits and a coupling one throws.

ELBO monotonicity now covers the partial ties — :A alone and :C alone are where a wrong estimator would surface, and eleven configurations hold.


Test results

base this PR
pass 1105 1871
fail / error 21 0
Aqua not run ✅
JuliaFormatter 1.0.62 ❌ (8 files) ✅
JET ❌ (2 errors) ✅
Docs examples not run ✅ (7/7)
docs/make.jl ❌ ✅

test/runtests.jl in full, 10m00s, no failures and no errors.

🤖 Generated with Claude Code

https://claude.ai/code/session_01PMU4PsNhFT7PUp3AGV37zY

claude added 2 commits August 22, 2026 18:10
…t it

Brings the SLDS posterior work from the CCN2026 branch (PR depasquale-lab#161) onto this
branch, replacing the `posterior` function this branch grew independently.

The two implementations did the same job by the same coordinate ascent, but
`posterior` scored the discrete layer against a *sample* from q(x) — the vLEM
Monte-Carlo E-step — so its `γ` carried Monte-Carlo noise and needed an `rng`
and a fixed iteration count. `smooth` scores it at the smoothed posterior mean
instead: deterministic, reproducible, and iterated to a `γ` fixed point.

- `smooth(slds, y; smoothing_iters, tol, return_cov, progress, depends_on)`
  returns one `NamedTuple` `(; x, γ, elbo, p)`, following the shape convention
  of `smooth(lds, y)` — matrix in, arrays out; vector or 3-D array in, per-trial
  vectors out. Covariances are opt-in (`return_cov`) because they are the large
  piece. `depends_on` keeps the stitching/grouped path available, and grouped
  datasets are evaluated cell by cell as before.
- `elbo(slds, y)` is now that call's `elbo` field rather than a one-shot
  Monte-Carlo E-step, so it is deterministic and takes no `rng`.
- `loglikelihood(slds, y)` returns the ELBO instead of throwing. The exact
  marginal is still intractable (a sum over K^T regime sequences); the docstring
  says so.
- `fit!(slds, y; smoothing_iters=n)` runs `n` alternations per E-step. The
  default of 1 is the standard vLEM update, so existing fits are unchanged.
- The alternation itself is now one `_vem_alternate!` shared by `fit!`'s E-step
  and `smooth`, with `x_samples === nothing` selecting the deterministic
  coupling. `estep!` and `_estep_grouped!` are thin wrappers over it, and the
  fill/smooth passes are factored into `_slds_fill_logL!` / `_slds_smooth_all!`
  so the grouped and ungrouped paths stop being written twice.

Tests: the eight `smooth`/`smoothing_iters` tests from CCN2026, plus the two
`posterior` tests rewritten against `smooth`. `test_SLDS_smooth_recovers_regimes`
now separates its regimes with emission noise small enough for the smoothed mean
to carry the dynamics — the old configuration (R = I against Q = 0.01·I) is not
identifiable, and the assertion it carried did not hold on this branch either.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PMU4PsNhFT7PUp3AGV37zY
…ting

Four pre-existing failures on this branch, none of them caused by the posterior
work in the previous commit. Verified against `claude/poisson-slds-fa-hmm-vr5llo`
itself: 1105 passing / 21 erroring there, with `Aqua`/`JET`/`JuliaFormatter`
skipped.

- **Multi-trial `rand(lds, tsteps_per_trial)` never ran.** `state_params` and
  `obs_params` were assigned from two branches of an `if` and then captured by
  the `tforeach` sampling closure, so Julia boxed them and OhMyThreads rejected
  the closure with `Attempted to capture and modify outer local variables`. They
  now come from `_per_trial_sample_params`, so each name is assigned once. This
  is what produced 19 of the 21 errors — every test that samples more than one
  trial from an LDS or PLDS.

- **`fit!(slds, y; tie_emissions=true)` read an uninitialized workspace.** The
  unit-weight aggregator seeds its buffers from the data-only constant blocks
  (`Σ y y'`, `Σ y`, the observation count, the `uy` blocks), which only the
  LDS/PLDS `fit!` entry points fill; the SLDS never reaches them, because its
  own M-step goes through the weighted aggregator, which rebuilds the data-side
  sums each E-step and needs no constants. The tied-emission update called the
  unit-weight aggregator anyway, so `Szz_Ab` and `Szz_Cd` came out indefinite
  (eigenvalues around -8) and the Cholesky threw `PosDefException` — and where
  it did not throw, the tied emission was fitted from garbage. Both the plain
  and the grouped tied-emission paths now fill the constants first.

- **JET.** `_slds_trial_elbo`'s `ll` scratch, analysed at the unspecialized
  signature, widened to a union with an `Any`-eltype branch that no
  `joint_loglikelihood!` method matches. Asserting the element type on the view
  drops the branch.

- **JuliaFormatter.** Ran 1.0.62 over the package; it rewrote eight files, six
  of them untouched by this branch's own work.

Also switched the SLDS docs example over to `smooth`. It was reaching into
`initialize_FilterSmooth` / `SLDSDiscreteLayer` / `estep!` behind a warning that
the package "does not yet expose a public posterior-decoding API for SLDS" —
which is exactly what the previous commit added.

Full suite now passes: 1775 tests, including Aqua, JuliaFormatter, JET, and all
seven docs examples.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PMU4PsNhFT7PUp3AGV37zY
@harrisonritz harrisonritz changed the title Fold posterior into smooth, and make elbo/loglikelihood report it Fold posterior into smooth, and get the test suite green Aug 22, 2026
## `tied_params`

`tie_emissions` could only tie `[C d D]` and `R`. It becomes `tied_params`,
which takes a `Symbol` or a collection of them and ties any parameter group:

    fit!(slds, y; tied_params = (:C, :R))   # was tie_emissions=true
    fit!(slds, y; tied_params = (:A, :Q))   # one set of dynamics, switching emissions
    fit!(slds, y; tied_params = :Q)         # shared process noise, switching A

Names follow `depends_on`/`fit_bool`: `[A b B]` is fit as one regression, so any
of `:A`/`:b`/`:B` names the whole group, likewise `:C`/`:d`/`:D` for `[C d D]`,
with `:Q` and `:R` groups of their own. `:x0`/`:P0` are accepted and dropped —
an SLDS ties its initial state across regimes unconditionally, so the keyword
carries the model's full vocabulary without implying a choice it doesn't
control. A name the model doesn't own throws, listing the ones it does.

`tie_emissions` is gone rather than deprecated: it never shipped, and lives only
on this branch.

## How a tied group is fitted

The M-step now expresses "tied across regimes" as a slot vector over the
regimes and hands it to the same `_grouped_update_*!` helpers `depends_on`
already uses — one slot for a tied group, one slot per regime otherwise. Both
SLDS M-steps (plain and grouped) collapse onto that one path, which is what let
`_update_tied_emission!` and `_update_tied_emission_grouped!` go away entirely.
The grouped path additionally drops its per-regime update loop: units are
already flat over (regime, cell), and a tie just removes the regime from the
slot, so a tied group stays a property of the cell — each session keeps its own
version, shared by every regime, which is what `tie_emissions` did.

Three cases, all exact:

- **Group tied with its noise** (`(:C, :R)`, `(:A, :Q)`) — the ordinary M-step
  on pooled statistics. The shared term doesn't depend on the regime and
  `Σₖ γₖ(t) = 1`, so the summed per-regime weighted objectives collapse to the
  unit-weight one.
- **Noise tied alone** (`:Q`, `:R`) — each regime contributes its own residual
  scatter, summed before the covariance is formed. Already how
  `_grouped_update_Q!`/`_grouped_update_R!` work.
- **Regression tied alone** (`:C` without `:R`) — the covariance no longer
  divides out of `∂/∂W`, the output rows couple, and the shared fit is a
  generalized least-squares solve. New: `_tied_gls_regression`.

`_tied_gls_regression` is written against a flat list of units rather than
anything SLDS-specific, so other callers with the same shape can use it. It
reduces to `mn_map` exactly when the covariances agree — verified in a test —
so the pooled path is a special case, not a second estimator. It costs
`O((p·m)³)`; callers reach for it only when the noise genuinely is not shared,
and both the docstring and the manual say to tie the pair when you can.

## Fixed alongside

A grouped fit that pooled a regression over units with *different* noise
versions — `depends_on = (R = session,)` with one emission over all sessions —
was solving the pooled normal equations, which do not maximize the ELBO there.
Same gap, same fix: those cases now take the GLS path.

The documentation build failed on `set_group_seeds!`, which is exported and
documented but was in no `@docs` block, so Documenter raised `missing_docs` plus
the unresolved `@ref`s pointing at it. Added to the api.md group-accessor block;
`docs/make.jl` now completes.

## Tests

Canonicalization (aliases, dedup, `:x0`/`:P0`, bad names, `:R` on a Poisson
emission); each group ties exactly itself and nothing else; pairs and
everything-tied; the GLS paths produce a shared regression with per-regime
covariances; frozen groups are untouched; `:x0`/`:P0` change nothing. The
load-bearing one is ELBO monotonicity across every tie configuration — a tied
group is only fitted right if it still maximizes the same bound, and a pooled
fit where GLS is needed would show up there as a decrease.

Full suite: 1855 passing, including Aqua, JuliaFormatter, JET and the docs
examples.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PMU4PsNhFT7PUp3AGV37zY
@harrisonritz harrisonritz changed the title Fold posterior into smooth, and get the test suite green SLDS posteriors via smooth, tied_params, and a green suite Aug 23, 2026
harrisonritz added a commit to depasquale-lab/StateSpaceDynamics.jl that referenced this pull request Aug 23, 2026
Pooling several units' sufficient statistics and solving the ordinary normal
equations maximizes the objective only when those units also share the residual
covariance: held fixed, it divides out of the score. When it does not, the
output rows couple and the pooled solve is simply the wrong estimator — the fit
walks downhill.

`depends_on = (R = session,)` with one emission over every session is exactly
that configuration, and it was reaching the pooled path. On two sessions whose
noise differs by a factor of 100 the ELBO fell on 16 of 29 iterations, worst
step -0.84. It now rises on every one, and converges higher (-474.3 against
-486.8).

`_tied_gls_regression` is the estimator, ported from harrisonritz#11 and kept
as a primitive over a flat list of units rather than anything grouping-specific.
`_shared_noise` picks between it and the pooled solve, so the cheap path still
runs whenever the covariance genuinely is shared — which, with `depends_on`
unset or with `(C = s, d = s, R = s)`, is every existing fit. The GLS solve
reduces to exactly `mn_map`'s answer when the covariances agree, with and
without a matrix-normal prior, so the two are one estimator rather than two;
that reduction is tested directly.

Both regressions get it: `[C d D]` against `R`, and `[A b B]` against `Q`. The
write-back halves of the two M-steps become `_unpack_obs_V!` / `_unpack_dyn_W!`
so the GLS path and the ordinary one share them.

Costs `O((p*m)^3)`, against `O(m^3)` for the pooled solve, so it is only
reached when the noise is not shared.

Ancillary parameter dependencies 131 -> 168 assertions; patch coverage of the
files this PR touches stays at 100%.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014wJNTtEFZwFUUFvgKbq4F7
A name used to stand in for the group it is fitted with: `:A` meant `[A b B]`
and `:C` meant `[C d D]`, in `depends_on` as well as `tied_params`. That reads
as a claim about one parameter while quietly acting on three, which is easy to
get wrong. Names now mean themselves everywhere.

## `depends_on` (breaking)

`depends_on = (C = session, R = session)` is now an error rather than shorthand
for grouping the whole emission regression. Name every member:

    depends_on = (C = session, d = session, D = session, R = session)

A model with no observation input has no `D` to fit, so `(C, d)` is the whole
group there — which is why most of the test and doc call sites gain one key
rather than two. `:A`/`:b`/`:B` the same. The error names the members that are
missing and the regression they belong to.

`group_labels`, `group_parameter` and `set_group_seeds!` are unaffected: they
look a parameter up rather than declaring anything, so an individual name is
still exactly what they want.

## `tied_params`

`tied_params = :C` no longer widens to the emission. Naming part of a jointly
fitted regression is a *partial tie*, and where there is a way to fit one, it is
fitted rather than rejected:

    fit!(slds, y; tied_params = (:C, :d, :D, :R))   # whole emission tied
    fit!(slds, y; tied_params = :C)                 # C shared, d and D per regime

Sharing part of a regression is still linear, and it reduces to sharing all of
it. Stationarity in a regime's free block gives that block in closed form, with
the regime's own covariance cancelling; substituting it into the shared block's
condition leaves exactly the system `_tied_gls_regression` already solves, over
statistics with the free columns projected out — Frisch–Waugh–Lovell, one extra
`|free|`-square solve per regime. So the pooled fit, the whole-regression GLS
and the partial tie are one estimator seen at three levels of sharing.

A matrix-normal prior is split between the shared block and the free ones, which
is available exactly when its column precision `Λ` does not couple them. A
diagonal `Λ` always qualifies; one that does not throws rather than dropping the
cross term.

Two partial ties have no such reduction and throw, per the "informative error
unless GLS resolves it" rule:

- a **Poisson** `[C d D]`, fitted by LBFGS rather than from sufficient
  statistics, so there is no shared-block solve to run; and
- a partial tie alongside **`depends_on`**, which already splits the regression
  into one version per group of trials, so the tie would have to partition
  columns and cells at once.

Both are fine with the whole regression tied.

## Tests

`_resolve_tied_params` returns literal names; each name ties exactly its own
parameter and nothing else; `depends_on` rejects a group named only in part
(both on the model and as a call-site override); the two partial ties that
cannot be fitted throw, and their whole-regression forms still work; a diagonal
prior splits and a coupling one throws.

ELBO monotonicity now covers the partial ties too — `:A` alone and `:C` alone
are where a wrong estimator would show up, and eleven configurations hold.

Full suite: 1871 passing, including Aqua, JuliaFormatter, JET and the docs
examples; `docs/make.jl` completes.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PMU4PsNhFT7PUp3AGV37zY
@harrisonritz
harrisonritz merged commit c6dc2d4 into claude/poisson-slds-fa-hmm-vr5llo Aug 24, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants