Skip to content

feature / grouped EM for the Gaussian LDS - #168

Open
harrisonritz wants to merge 9 commits into
claude/split-pr-165-incremental-t8k2s5-2from
claude/split-pr-165-incremental-t8k2s5-3
Open

harrisonritz wants to merge 9 commits into
claude/split-pr-165-incremental-t8k2s5-2from
claude/split-pr-165-incremental-t8k2s5-3

Conversation

@harrisonritz

Copy link
Copy Markdown
Collaborator

3 of 5 — splitting #165 into reviewable pieces. Stacked on #167 (which is stacked on #166); the diff here is only this PR's changes. Base retargets as the parents merge.

fit!, smooth, elbo, loglikelihood and rand now honour a Gaussian LDS's depends_on instead of rejecting it. The Poisson LDS and the SLDS keep the interim guard until PRs 4 and 5.

Design

A cell is a maximal set of trials sharing every parameter — the common refinement of all the label vectors. Trials in a cell are governed by a single LinearDynamicalSystem, so the E-step runs on each cell's sub-Data completely unchanged; only the M-step and the ELBO become group-aware.

Two consequences worth checking in review:

  • The equal-length shared-covariance fast path stays alive within each group. Parameters differ between cells, so their smoothed covariances genuinely differ — sharing one across the whole dataset would be wrong, sharing one per cell is exactly as valid as the ungrouped case.
  • The O(D²·T) workspace storage (block-tridiagonal + shared-covariance cache) is allocated once and reused across cells, so a grouped fit's memory tracks an ungrouped one's rather than scaling with the number of sessions. A cell's smoothed covariances are consumed by its own aggregation before the next cell overwrites them. What must survive between iterations is the small per-cell aggregator constants (Σyy', the bias/input blocks) — those have no tsteps dimension, so they are cached per cell and copied back in before each cell's aggregation.

SmoothWorkspace becomes mutable in its batched field only (every other field is const), so each cell's BLAS-3 mean-pass buffers can be swapped in while the expensive storage stays shared.

grouped_em.jl

Holds what PRs 4 and 5 also need. Everything is written against a flat list of units — a unit is one thing that produced a SufficientStatistics: a cell for an LDS, or a (regime, cell) pair for an SLDS. Parameters shared by several units are the same array object, so writing through any one of them updates all.

  • pooling per-cell sufficient statistics per parameter version. Only the blocks the regression updates read are pooled; the covariance updates never need a pooled *_yy, which also avoids a Cholesky of a possibly rank-deficient pooled obs_yy for a small group. A version backed by a single unit reuses that unit's statistics verbatim, which is what keeps singleton groups numerically identical to the ungrouped fit.
  • the grouped state-side and Gaussian-emission M-steps, built on the accumulate/finalize halves from refactor / split covariance M-steps and ELBO loops into reusable halves #166: residual scatter is summed cell by cell, each with its own regression matrix, so a grouping of C finer than that of R comes out right.
  • the grouped prior log-density: IW terms once per covariance version, MN terms once per distinct regression/covariance pair — consistent with the M-step, where the same pairs decide how often Wm Λ Wm' is folded into the IW scale.

Held-out scoring

Every entry point takes a depends_on keyword overriding the model's stored labels for that call, so a test set with a different trial count can be scored without mutating the model:

ll = loglikelihood(lds, Y_test; depends_on = (C = session_test, R = session_test))

Tests

The load-bearing check is test_fully_grouped_matches_independent_fits: with every parameter depending on the session label, the sessions share nothing, so a grouped fit over the pooled data must equal two independent fits — same summed ELBO trace and same fitted parameters, to floating point. Its mirror image is test_single_group_matches_ungrouped: a depends_on whose labels are all identical adds no parameters and must reproduce the ungrouped fit exactly. Everything else downstream shares that machinery.

Also: ragged trial lengths (which take the per-trial smoother fallback rather than the fast path), ELBO monotonicity, per-group noise recovery, grouped smooth returning per-cell-shared covariances, held-out scoring through the override, integer labels combined with priors, and the single-trial rand error.

Note on rand

Sampling lives in simulate.jl and is shared by the Gaussian and Poisson emissions, so a Poisson LDS can already be sampled with depends_on after this PR even though it cannot yet be fitted. That is intentional — it makes the synthetic multi-session dataset for PR 4's tests available — and PR 4 removes the remaining Poisson guards.

Follow-ups in this series

  1. Grouped EM for the Poisson LDS
  2. Grouped EM for the SLDS

Generated by Claude Code

@harrisonritz
harrisonritz force-pushed the claude/split-pr-165-incremental-t8k2s5-2 branch from 6b9b221 to 0e80aa0 Compare August 13, 2026 23:04
@harrisonritz
harrisonritz force-pushed the claude/split-pr-165-incremental-t8k2s5-3 branch 2 times, most recently from b21a602 to 8be149a Compare August 13, 2026 23:26
@harrisonritz
harrisonritz force-pushed the claude/split-pr-165-incremental-t8k2s5-2 branch from e1212f7 to d8cc83f Compare August 13, 2026 23:33
@harrisonritz
harrisonritz force-pushed the claude/split-pr-165-incremental-t8k2s5-3 branch from 8be149a to 91f13b5 Compare August 13, 2026 23:33
@harrisonritz
harrisonritz force-pushed the claude/split-pr-165-incremental-t8k2s5-2 branch from d8cc83f to 1f33318 Compare August 14, 2026 11:15
@harrisonritz
harrisonritz force-pushed the claude/split-pr-165-incremental-t8k2s5-3 branch from 91f13b5 to f4a73c3 Compare August 14, 2026 11:15
Second half of condition-dependent parameters (#165) for the Gaussian model
family: `fit!`, `smooth`, `elbo`, `loglikelihood` and `rand` now honour a
model's `depends_on` instead of rejecting it.

Design. A cell is a maximal set of trials sharing every parameter — the common
refinement of all the label vectors. Trials in a cell are governed by a single
LinearDynamicalSystem, so the E-step runs on each cell's sub-`Data` completely
unchanged; only the M-step and the ELBO become group-aware. This keeps the
equal-length shared-covariance fast path alive *within* each group (parameters
differ between cells, so their covariances genuinely differ), and the O(D^2*T)
workspace storage is allocated once and reused across cells, so a grouped fit's
memory tracks an ungrouped one's rather than scaling with the number of
sessions. The small per-cell aggregator constants are cached instead, and
swapped in before each cell's aggregation.

New `grouped_em.jl` holds the parts that are shared with the Poisson LDS and
the SLDS: pooling per-cell sufficient statistics per parameter version, the
grouped state-side and Gaussian-emission M-steps, and the grouped prior
log-density. Pooling is written against a flat list of units, so the same code
serves a cell of an LDS and a (regime, cell) pair of an SLDS.

The covariance updates accumulate their residual scatter cell by cell, each
with its own regression matrix, so a grouping of (say) C finer than that of R
comes out right; the MN/IW prior terms are counted once per distinct parameter
version. A version backed by a single cell reuses that cell's statistics
verbatim, which keeps singleton groups numerically identical to the ungrouped
fit.

Each entry point also accepts a `depends_on` keyword overriding the model's
stored labels for that call, so a held-out set with a different trial count can
be scored without mutating the model.

`SmoothWorkspace` becomes mutable in its `batched` field only, so a grouped fit
can swap in the BLAS-3 buffers sized for the cell it is about to smooth while
sharing the expensive block-tridiagonal and shared-covariance storage.

The Poisson LDS and the SLDS keep the interim guard until their own follow-ups.

Tests. The load-bearing check is that a fully grouped fit — every parameter
depending on the session label — reproduces independent per-session fits to
floating point, in both the ELBO trace and every fitted parameter; and that a
degenerate grouping with one label reproduces the ungrouped fit. On top of
that: ragged trial lengths, ELBO monotonicity, per-group noise recovery,
grouped `smooth`/`loglikelihood`, held-out scoring through the override,
integer labels with priors, and the single-trial `rand` error.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
@harrisonritz
harrisonritz force-pushed the claude/split-pr-165-incremental-t8k2s5-2 branch from 1f33318 to 57a9eb8 Compare August 14, 2026 11:35
@harrisonritz
harrisonritz force-pushed the claude/split-pr-165-incremental-t8k2s5-3 branch from f4a73c3 to a3f54f4 Compare August 14, 2026 11:35
harrisonritz and others added 3 commits August 22, 2026 17:25
`state_params` / `obs_params` are now assigned in both arms of the grouping
branch, which boxes those bindings; the `tforeach` closure below captures
them, and OhMyThreads rejects a boxed capture outright:

    rand(rng, lds, fill(20, 8))
    ERROR: Attempted to capture and modify outer local variables

Reproduced on 4 threads before this change and clean after. CI runs
single-threaded, where `ntasks == 1`, so the suite never reached it — but any
caller sampling multiple trials with `-t auto` does.

Rebinding both in a `let` before the closure removes the boxes, the same idiom
`fit_SLDS.jl`'s parallel E-step already uses.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014wJNTtEFZwFUUFvgKbq4F7
Runs JuliaFormatter v1.0.62 (the version test/Project.toml pins, blue style
with always_use_return) over the tree, so the "Code Formatting" test passes.
Mostly `for c in 1:(grp.ncells)` needing parens around the range bound.
Whitespace only, no logic changes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014wJNTtEFZwFUUFvgKbq4F7
@codecov

codecov Bot commented Aug 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.71%. Comparing base (7f928eb) to head (92da250).

Additional details and impacted files
@@                             Coverage Diff                              @@
##           claude/split-pr-165-incremental-t8k2s5-2     #168      +/-   ##
============================================================================
+ Coverage                                     96.00%   96.71%   +0.71%     
============================================================================
  Files                                            19       20       +1     
  Lines                                          3651     4018     +367     
============================================================================
+ Hits                                           3505     3886     +381     
+ Misses                                          146      132      -14     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Patch coverage here was 92.21%; the gaps were four distinct behaviours rather
than incidental lines, so each gets a test that asserts what it is for.

`_pool_obs!` summed observation sufficient statistics across the cells sharing
one `[C d D]` slot and was never reached: every grouped test varies `:C`, which
gives each cell its own emission and takes the `length(units) == 1` early
return. Grouping `:R` alone is the case that needs it — one pooled emission fit
from both cells' trials — and the test pins that the two cells share `C` and `d`
by reference while keeping their own `R`.

The matrix-normal priors contribute per *pair* of slots (`[A b B]` with `Q`,
`[C d D]` with `R`, `x0` with `P0`), which is a different code path from the
inverse-Wishart terms `test_grouped_integer_labels_and_priors` already covers.
The new test sets all three and checks the penalised ELBO lands below the
unpenalised one on the same data, so the terms are demonstrably in the
objective rather than merely evaluated.

`smooth` on a grouped model with a single trial passed as a plain matrix
returned one `x`/`P` pair through a dispatch nothing exercised; the test checks
it against the vector form of the same trial.

The EM loop's early return — `finish!` the meter, truncate `elbos` to the
iterations actually run — needed a fit that converges before `max_iter`, and
`progress=true` needed any caller at all. One test covers both, and asserts the
returned vector really is shorter and really did stop on the tolerance.

Ancillary parameter dependencies 108 -> 131 assertions. Patch coverage of the
files this PR touches: 347/347 added executable lines.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014wJNTtEFZwFUUFvgKbq4F7
@harrisonritz
harrisonritz marked this pull request as ready for review August 23, 2026 16:32
harrisonritz and others added 4 commits August 23, 2026 17:12
# Conflicts:
#	test/LinearDynamicalSystems/ParameterDependencies.jl
#	test/runtests.jl
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
# Conflicts:
#	src/lds/parameter_groups.jl
Motivation paragraphs out, technical reason kept. The GLS docstrings keep the
score equation and the vectorized system, which the code does not show, and
drop the prose around them.

67 comment lines out, 35 back.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014wJNTtEFZwFUUFvgKbq4F7

This branch has not been deployed

No deployments
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