Skip to content

feature / condition-varying parameters - #165

Closed
harrisonritz wants to merge 1 commit into
depasquale-lab:devfrom
harrisonritz:claude/parameter-ancillary-dependencies-6bqeo5
Closed

harrisonritz wants to merge 1 commit into
depasquale-lab:devfrom
harrisonritz:claude/parameter-ancillary-dependencies-6bqeo5

Conversation

@harrisonritz

Copy link
Copy Markdown
Collaborator

Every AbstractStateModel and AbstractObservationModel gains a depends_on field (default nothing). Setting it to a NamedTuple of per-trial label vectors makes the named parameters be estimated separately for each group of trials, while everything else stays pooled:

obs.depends_on = (C = session, R = session)

That is the stitching setup for combining recording sessions that observe different neurons in the same animal: latent dynamics shared by the animal, emission parameters specific to the session.

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.

Keys canonicalize to the same groups fit_bool uses, since those parameters are fit jointly as one regression: :A/:b/:B name one group, :C/:d/:D another. Labels may be Symbols, integers or strings. Different parameters may use different label vectors.

Per-group values live in a new variants field holding one model object per parameter-group combination, with non-varying parameters shared by reference so a single M-step write covers all of them. They are read back with the new exported group_labels and group_parameter.

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. update_Q!, update_R! and update_initial_state_covariance! were refactored into accumulate/finalize halves so the grouped and ungrouped paths share one implementation.

Supported for the Gaussian LDS, the Poisson LDS and the SLDS across fit!, smooth, elbo, loglikelihood and rand, each of which also accepts a depends_on keyword overriding the model's stored labels so a held-out set with a different trial count can be scored without mutating the model. For an SLDS every regime must declare the same labels (the trial partition is a property of the data); x0/P0 stay tied across regimes.

With depends_on unset, every entry point takes its original code path.

Every AbstractStateModel and AbstractObservationModel gains a `depends_on`
field (default `nothing`). Setting it to a NamedTuple of per-trial label
vectors makes the named parameters be estimated separately for each group of
trials, while everything else stays pooled:

    obs.depends_on = (C = session, R = session)

That is the stitching setup for combining recording sessions that observe
different neurons in the same animal: latent dynamics shared by the animal,
emission parameters specific to the session.

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.

Keys canonicalize to the same groups fit_bool uses, since those parameters are
fit jointly as one regression: :A/:b/:B name one group, :C/:d/:D another.
Labels may be Symbols, integers or strings. Different parameters may use
different label vectors.

Per-group values live in a new `variants` field holding one model object per
parameter-group combination, with non-varying parameters shared by reference so
a single M-step write covers all of them. They are read back with the new
exported `group_labels` and `group_parameter`.

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. `update_Q!`, `update_R!` and `update_initial_state_covariance!` were
refactored into accumulate/finalize halves so the grouped and ungrouped paths
share one implementation.

Supported for the Gaussian LDS, the Poisson LDS and the SLDS across `fit!`,
`smooth`, `elbo`, `loglikelihood` and `rand`, each of which also accepts a
`depends_on` keyword overriding the model's stored labels so a held-out set
with a different trial count can be scored without mutating the model. For an
SLDS every regime must declare the same labels (the trial partition is a
property of the data); x0/P0 stay tied across regimes.

With `depends_on` unset, every entry point takes its original code path.

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

Copy link
Copy Markdown
Collaborator Author

Discussed in #98

solution here is to combine parameters into cells, and then run each cell through the standard fitting procedure

@rsenne

rsenne commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator

Can we break this up into separate PRs? Its a bit big as is

harrisonritz pushed a commit that referenced this pull request Aug 13, 2026
Pure refactor ahead of condition-dependent parameters (#165): no behavior
change, no new API, no new tests. Each of the three covariance updates is
split into an accumulate half and a finalize half so a single covariance can
later be fitted from the pooled residual scatter of several models, each
contributing with its own regression matrix:

  update_initial_state_covariance!  ->  _accumulate_init_scatter!
                                        _accumulate_x0_prior_scatter!
                                        _finalize_P0!
  update_Q!                         ->  _accumulate_dyn_scatter!
                                        _accumulate_ab_prior_scatter!
                                        _finalize_Q!
  update_R!                         ->  _accumulate_obs_scatter!
                                        _accumulate_cd_prior_scatter!
                                        _finalize_R!

The accumulators add into the scatter matrix instead of overwriting it, and
the public entry points now zero the scratch, call the halves in the original
order, and finalize — so the single-model path is arithmetically unchanged.
Packing the stacked regressions `[A b B]` and `[C d D]` into a workspace
buffer becomes `_pack_dyn_W!` / `_pack_obs_V!`, which the prior-scatter and
log-density paths share.

Two per-trial loops are lifted out of their enclosing ELBO functions with
their bodies unchanged: `_poisson_q_obs_total` from the Poisson `elbo!` and
`_slds_trial_elbo` from the SLDS `elbo!`, so a trial can be evaluated against
a parameter set that differs from its neighbours'.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
harrisonritz pushed a commit that referenced this pull request Aug 13, 2026
First half of condition-dependent parameters (#165): the declaration side,
with no change to how any model is fitted.

Every `AbstractStateModel` and `AbstractObservationModel` gains a `depends_on`
field (default `nothing`). Setting it to a NamedTuple of per-trial label
vectors declares that the named parameters are to be estimated separately for
each group of trials, while everything else stays pooled:

    obs.depends_on = (C = session, R = session)

That is the stitching setup for combining recording sessions that observe
different neurons in the same animal: latent dynamics shared by the animal,
emission parameters specific to the session.

Keys canonicalize to the same groups `fit_bool` uses, since those parameters
are fit jointly as one regression: :A/:b/:B name one group, :C/:d/:D another.
Labels may be Symbols, integers or strings, and different parameters may use
different label vectors — the trial partition is their common refinement, so a
*cell* is a maximal set of trials sharing every parameter.

Per-group values live in a new `variants` field holding one model object per
parameter-group combination, with non-varying parameters shared by reference
so a single M-step write covers all of them. They are read back with the newly
exported `group_labels` and `group_parameter`. `show` reports the declared
groups, and `validate_LDS` resolves both sub-models' declarations so a
malformed one is reported at construction rather than at the first `fit!`.

The grouped E/M-step that consumes the partition lands in follow-ups. Until it
does, `_reject_unsupported_dependence` makes `fit!`, `smooth`, `elbo`,
`loglikelihood` and `rand` throw on a model that declares `depends_on`, rather
than silently fitting one pooled parameter set; each entry point drops that
call as its grouped path arrives.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
harrisonritz pushed a commit that referenced this pull request Aug 13, 2026
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 pushed a commit that referenced this pull request Aug 13, 2026
Extends condition-dependent parameters (#165) to the Poisson model family:
`fit!`, `smooth` and `elbo` now honour a Poisson LDS's `depends_on` instead of
rejecting it.

The state side is identical to the Gaussian path — per-cell Laplace E-step,
pooled sufficient statistics per parameter version — so it reuses
`grouped_em.jl` unchanged. Only the emission differs: the Poisson likelihood is
non-conjugate and has no sufficient-statistic form, so the M-step runs one
LBFGS solve per version of `[C d D]`, over the trials of every cell that shares
that version. A `[C d D]` shared across cells is therefore still fit from all
of their data.

The ELBO mirrors `_grouped_estep_elbo_gaussian!` with the observation-side
Q-term left as the per-trial loop extracted in the first PR of this series, and
adds one prior term per distinct `[C d D]` — the bare quadratic the LBFGS
emission objective penalizes, since a Poisson emission has no noise covariance
to pair the MN prior with.

The SLDS keeps the interim guard until its own follow-up.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
harrisonritz pushed a commit that referenced this pull request Aug 13, 2026
Completes condition-dependent parameters (#165): `fit!`, `elbo` and `rand` now
honour an SLDS's `depends_on`, and the interim guard introduced with the
declaration API is gone.

The trial partition is a property of the dataset, so it must be identical
across regimes; only the parameter values differ per regime. Every regime must
therefore declare the same labels, and a disagreement (including one regime
declaring nothing) is an error. Given that, each cell is governed by one
ordinary SLDS whose sub-LDSs hold that cell's parameter arrays and which shares
the transition matrix and initial distribution by reference, so the existing
smoother and weighted aggregator run on it unchanged. Regime constants are
refreshed once per cell rather than once per trial, and forward-backward stays
global since the discrete chain is shared by all trials.

M-step. The work is one gamma-weighted sufficient statistic per (regime, cell).
Dynamics and emissions are per regime, so they pool across the cells that share
a version *within* a regime; x0/P0 are tied across regimes, so they pool across
every (regime, cell) unit that shares a version — which is valid because the
regime responsibilities at t=1 sum to one, so summing the per-regime weighted
init statistics reproduces the unit-weight statistic the ungrouped path uses.
Units are laid out regime-major so the first unit of any version belongs to
regime 1, where the update writes; the tie is then restored by copying regime
1's initial state into the others, before the P0 update as well as after, since
the P0 scatter reads each unit's own x0.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
harrisonritz pushed a commit that referenced this pull request Aug 13, 2026
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 pushed a commit that referenced this pull request Aug 13, 2026
Extends condition-dependent parameters (#165) to the Poisson model family:
`fit!`, `smooth` and `elbo` now honour a Poisson LDS's `depends_on` instead of
rejecting it.

The state side is identical to the Gaussian path — per-cell Laplace E-step,
pooled sufficient statistics per parameter version — so it reuses
`grouped_em.jl` unchanged. Only the emission differs: the Poisson likelihood is
non-conjugate and has no sufficient-statistic form, so the M-step runs one
LBFGS solve per version of `[C d D]`, over the trials of every cell that shares
that version. A `[C d D]` shared across cells is therefore still fit from all
of their data.

The ELBO mirrors `_grouped_estep_elbo_gaussian!` with the observation-side
Q-term left as the per-trial loop extracted in the first PR of this series, and
adds one prior term per distinct `[C d D]` — the bare quadratic the LBFGS
emission objective penalizes, since a Poisson emission has no noise covariance
to pair the MN prior with.

The SLDS keeps the interim guard until its own follow-up.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
harrisonritz pushed a commit that referenced this pull request Aug 13, 2026
Completes condition-dependent parameters (#165): `fit!`, `elbo` and `rand` now
honour an SLDS's `depends_on`, and the interim guard introduced with the
declaration API is gone.

The trial partition is a property of the dataset, so it must be identical
across regimes; only the parameter values differ per regime. Every regime must
therefore declare the same labels, and a disagreement (including one regime
declaring nothing) is an error. Given that, each cell is governed by one
ordinary SLDS whose sub-LDSs hold that cell's parameter arrays and which shares
the transition matrix and initial distribution by reference, so the existing
smoother and weighted aggregator run on it unchanged. Regime constants are
refreshed once per cell rather than once per trial, and forward-backward stays
global since the discrete chain is shared by all trials.

M-step. The work is one gamma-weighted sufficient statistic per (regime, cell).
Dynamics and emissions are per regime, so they pool across the cells that share
a version *within* a regime; x0/P0 are tied across regimes, so they pool across
every (regime, cell) unit that shares a version — which is valid because the
regime responsibilities at t=1 sum to one, so summing the per-regime weighted
init statistics reproduces the unit-weight statistic the ungrouped path uses.
Units are laid out regime-major so the first unit of any version belongs to
regime 1, where the update writes; the tie is then restored by copying regime
1's initial state into the others, before the P0 update as well as after, since
the P0 scatter reads each unit's own x0.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
harrisonritz pushed a commit that referenced this pull request Aug 13, 2026
First half of condition-dependent parameters (#165): the declaration side,
with no change to how any model is fitted.

Every `AbstractStateModel` and `AbstractObservationModel` gains a `depends_on`
field (default `nothing`). Setting it to a NamedTuple of per-trial label
vectors declares that the named parameters are to be estimated separately for
each group of trials, while everything else stays pooled:

    obs.depends_on = (C = session, R = session)

That is the stitching setup for combining recording sessions that observe
different neurons in the same animal: latent dynamics shared by the animal,
emission parameters specific to the session.

Keys canonicalize to the same groups `fit_bool` uses, since those parameters
are fit jointly as one regression: :A/:b/:B name one group, :C/:d/:D another.
Labels may be Symbols, integers or strings, and different parameters may use
different label vectors — the trial partition is their common refinement, so a
*cell* is a maximal set of trials sharing every parameter.

Per-group values live in a new `variants` field holding one model object per
parameter-group combination, with non-varying parameters shared by reference
so a single M-step write covers all of them. They are read back with the newly
exported `group_labels` and `group_parameter`. `show` reports the declared
groups, and `validate_LDS` resolves both sub-models' declarations so a
malformed one is reported at construction rather than at the first `fit!`.

The grouped E/M-step that consumes the partition lands in follow-ups. Until it
does, `_reject_unsupported_dependence` makes `fit!`, `smooth`, `elbo`,
`loglikelihood` and `rand` throw on a model that declares `depends_on`, rather
than silently fitting one pooled parameter set; each entry point drops that
call as its grouped path arrives.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
harrisonritz pushed a commit that referenced this pull request Aug 13, 2026
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 pushed a commit that referenced this pull request Aug 13, 2026
Extends condition-dependent parameters (#165) to the Poisson model family:
`fit!`, `smooth` and `elbo` now honour a Poisson LDS's `depends_on` instead of
rejecting it.

The state side is identical to the Gaussian path — per-cell Laplace E-step,
pooled sufficient statistics per parameter version — so it reuses
`grouped_em.jl` unchanged. Only the emission differs: the Poisson likelihood is
non-conjugate and has no sufficient-statistic form, so the M-step runs one
LBFGS solve per version of `[C d D]`, over the trials of every cell that shares
that version. A `[C d D]` shared across cells is therefore still fit from all
of their data.

The ELBO mirrors `_grouped_estep_elbo_gaussian!` with the observation-side
Q-term left as the per-trial loop extracted in the first PR of this series, and
adds one prior term per distinct `[C d D]` — the bare quadratic the LBFGS
emission objective penalizes, since a Poisson emission has no noise covariance
to pair the MN prior with.

The SLDS keeps the interim guard until its own follow-up.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
harrisonritz pushed a commit that referenced this pull request Aug 13, 2026
Completes condition-dependent parameters (#165): `fit!`, `elbo` and `rand` now
honour an SLDS's `depends_on`, and the interim guard introduced with the
declaration API is gone.

The trial partition is a property of the dataset, so it must be identical
across regimes; only the parameter values differ per regime. Every regime must
therefore declare the same labels, and a disagreement (including one regime
declaring nothing) is an error. Given that, each cell is governed by one
ordinary SLDS whose sub-LDSs hold that cell's parameter arrays and which shares
the transition matrix and initial distribution by reference, so the existing
smoother and weighted aggregator run on it unchanged. Regime constants are
refreshed once per cell rather than once per trial, and forward-backward stays
global since the discrete chain is shared by all trials.

M-step. The work is one gamma-weighted sufficient statistic per (regime, cell).
Dynamics and emissions are per regime, so they pool across the cells that share
a version *within* a regime; x0/P0 are tied across regimes, so they pool across
every (regime, cell) unit that shares a version — which is valid because the
regime responsibilities at t=1 sum to one, so summing the per-regime weighted
init statistics reproduces the unit-weight statistic the ungrouped path uses.
Units are laid out regime-major so the first unit of any version belongs to
regime 1, where the update writes; the tie is then restored by copying regime
1's initial state into the others, before the P0 update as well as after, since
the P0 scatter reads each unit's own x0.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
harrisonritz pushed a commit that referenced this pull request Aug 14, 2026
First half of condition-dependent parameters (#165): the declaration side,
with no change to how any model is fitted.

Every `AbstractStateModel` and `AbstractObservationModel` gains a `depends_on`
field (default `nothing`). Setting it to a NamedTuple of per-trial label
vectors declares that the named parameters are to be estimated separately for
each group of trials, while everything else stays pooled:

    obs.depends_on = (C = session, R = session)

That is the stitching setup for combining recording sessions that observe
different neurons in the same animal: latent dynamics shared by the animal,
emission parameters specific to the session.

Keys canonicalize to the same groups `fit_bool` uses, since those parameters
are fit jointly as one regression: :A/:b/:B name one group, :C/:d/:D another.
Labels may be Symbols, integers or strings, and different parameters may use
different label vectors — the trial partition is their common refinement, so a
*cell* is a maximal set of trials sharing every parameter.

Per-group values live in a new `variants` field holding one model object per
parameter-group combination, with non-varying parameters shared by reference
so a single M-step write covers all of them. They are read back with the newly
exported `group_labels` and `group_parameter`. `show` reports the declared
groups, and `validate_LDS` resolves both sub-models' declarations so a
malformed one is reported at construction rather than at the first `fit!`.

The grouped E/M-step that consumes the partition lands in follow-ups. Until it
does, `_reject_unsupported_dependence` makes `fit!`, `smooth`, `elbo`,
`loglikelihood` and `rand` throw on a model that declares `depends_on`, rather
than silently fitting one pooled parameter set; each entry point drops that
call as its grouped path arrives.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
harrisonritz pushed a commit that referenced this pull request Aug 14, 2026
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 pushed a commit that referenced this pull request Aug 14, 2026
Extends condition-dependent parameters (#165) to the Poisson model family:
`fit!`, `smooth` and `elbo` now honour a Poisson LDS's `depends_on` instead of
rejecting it.

The state side is identical to the Gaussian path — per-cell Laplace E-step,
pooled sufficient statistics per parameter version — so it reuses
`grouped_em.jl` unchanged. Only the emission differs: the Poisson likelihood is
non-conjugate and has no sufficient-statistic form, so the M-step runs one
LBFGS solve per version of `[C d D]`, over the trials of every cell that shares
that version. A `[C d D]` shared across cells is therefore still fit from all
of their data.

The ELBO mirrors `_grouped_estep_elbo_gaussian!` with the observation-side
Q-term left as the per-trial loop extracted in the first PR of this series, and
adds one prior term per distinct `[C d D]` — the bare quadratic the LBFGS
emission objective penalizes, since a Poisson emission has no noise covariance
to pair the MN prior with.

The SLDS keeps the interim guard until its own follow-up.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
harrisonritz pushed a commit that referenced this pull request Aug 14, 2026
Completes condition-dependent parameters (#165): `fit!`, `elbo` and `rand` now
honour an SLDS's `depends_on`, and the interim guard introduced with the
declaration API is gone.

The trial partition is a property of the dataset, so it must be identical
across regimes; only the parameter values differ per regime. Every regime must
therefore declare the same labels, and a disagreement (including one regime
declaring nothing) is an error. Given that, each cell is governed by one
ordinary SLDS whose sub-LDSs hold that cell's parameter arrays and which shares
the transition matrix and initial distribution by reference, so the existing
smoother and weighted aggregator run on it unchanged. Regime constants are
refreshed once per cell rather than once per trial, and forward-backward stays
global since the discrete chain is shared by all trials.

M-step. The work is one gamma-weighted sufficient statistic per (regime, cell).
Dynamics and emissions are per regime, so they pool across the cells that share
a version *within* a regime; x0/P0 are tied across regimes, so they pool across
every (regime, cell) unit that shares a version — which is valid because the
regime responsibilities at t=1 sum to one, so summing the per-regime weighted
init statistics reproduces the unit-weight statistic the ungrouped path uses.
Units are laid out regime-major so the first unit of any version belongs to
regime 1, where the update writes; the tie is then restored by copying regime
1's initial state into the others, before the P0 update as well as after, since
the P0 scatter reads each unit's own x0.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
harrisonritz pushed a commit that referenced this pull request Aug 14, 2026
First half of condition-dependent parameters (#165): the declaration side,
with no change to how any model is fitted.

Every `AbstractStateModel` and `AbstractObservationModel` gains a `depends_on`
field (default `nothing`). Setting it to a NamedTuple of per-trial label
vectors declares that the named parameters are to be estimated separately for
each group of trials, while everything else stays pooled:

    obs.depends_on = (C = session, R = session)

That is the stitching setup for combining recording sessions that observe
different neurons in the same animal: latent dynamics shared by the animal,
emission parameters specific to the session.

Keys canonicalize to the same groups `fit_bool` uses, since those parameters
are fit jointly as one regression: :A/:b/:B name one group, :C/:d/:D another.
Labels may be Symbols, integers or strings, and different parameters may use
different label vectors — the trial partition is their common refinement, so a
*cell* is a maximal set of trials sharing every parameter.

Per-group values live in a new `variants` field holding one model object per
parameter-group combination, with non-varying parameters shared by reference
so a single M-step write covers all of them. They are read back with the newly
exported `group_labels` and `group_parameter`. `show` reports the declared
groups, and `validate_LDS` resolves both sub-models' declarations so a
malformed one is reported at construction rather than at the first `fit!`.

The grouped E/M-step that consumes the partition lands in follow-ups. Until it
does, `_reject_unsupported_dependence` makes `fit!`, `smooth`, `elbo`,
`loglikelihood` and `rand` throw on a model that declares `depends_on`, rather
than silently fitting one pooled parameter set; each entry point drops that
call as its grouped path arrives.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
harrisonritz pushed a commit that referenced this pull request Aug 14, 2026
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 pushed a commit that referenced this pull request Aug 14, 2026
Extends condition-dependent parameters (#165) to the Poisson model family:
`fit!`, `smooth` and `elbo` now honour a Poisson LDS's `depends_on` instead of
rejecting it.

The state side is identical to the Gaussian path — per-cell Laplace E-step,
pooled sufficient statistics per parameter version — so it reuses
`grouped_em.jl` unchanged. Only the emission differs: the Poisson likelihood is
non-conjugate and has no sufficient-statistic form, so the M-step runs one
LBFGS solve per version of `[C d D]`, over the trials of every cell that shares
that version. A `[C d D]` shared across cells is therefore still fit from all
of their data.

The ELBO mirrors `_grouped_estep_elbo_gaussian!` with the observation-side
Q-term left as the per-trial loop extracted in the first PR of this series, and
adds one prior term per distinct `[C d D]` — the bare quadratic the LBFGS
emission objective penalizes, since a Poisson emission has no noise covariance
to pair the MN prior with.

The SLDS keeps the interim guard until its own follow-up.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
harrisonritz pushed a commit that referenced this pull request Aug 14, 2026
Completes condition-dependent parameters (#165): `fit!`, `elbo` and `rand` now
honour an SLDS's `depends_on`, and the interim guard introduced with the
declaration API is gone.

The trial partition is a property of the dataset, so it must be identical
across regimes; only the parameter values differ per regime. Every regime must
therefore declare the same labels, and a disagreement (including one regime
declaring nothing) is an error. Given that, each cell is governed by one
ordinary SLDS whose sub-LDSs hold that cell's parameter arrays and which shares
the transition matrix and initial distribution by reference, so the existing
smoother and weighted aggregator run on it unchanged. Regime constants are
refreshed once per cell rather than once per trial, and forward-backward stays
global since the discrete chain is shared by all trials.

M-step. The work is one gamma-weighted sufficient statistic per (regime, cell).
Dynamics and emissions are per regime, so they pool across the cells that share
a version *within* a regime; x0/P0 are tied across regimes, so they pool across
every (regime, cell) unit that shares a version — which is valid because the
regime responsibilities at t=1 sum to one, so summing the per-regime weighted
init statistics reproduces the unit-weight statistic the ungrouped path uses.
Units are laid out regime-major so the first unit of any version belongs to
regime 1, where the update writes; the tie is then restored by copying regime
1's initial state into the others, before the P0 update as well as after, since
the P0 scatter reads each unit's own x0.

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

Copy link
Copy Markdown
Collaborator Author

Can we break this up into separate PRs? Its a bit big as is

You probably saw, but now split up into multiple PRs: #166, #167, #168, #169, #170, #172

They are passing (besides a JET issue that should be addressed #173), ready for review at your leisure

@rsenne rsenne closed this Aug 24, 2026
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.

3 participants