Skip to content

Stitching: per-session observation dimensions - #172

Open
harrisonritz wants to merge 16 commits into
claude/split-pr-165-incremental-t8k2s5-5from
claude/split-pr-165-incremental-t8k2s5-6
Open

harrisonritz wants to merge 16 commits into
claude/split-pr-165-incremental-t8k2s5-5from
claude/split-pr-165-incremental-t8k2s5-6

Conversation

@harrisonritz

@harrisonritz harrisonritz commented Aug 14, 2026 •

Copy link
Copy Markdown
Collaborator

Draft — opened for CI. Stacked on the grouped-EM SLDS branch.

Lets each group of trials carry its own obs_dim, so recording sessions that observe different numbers of neurons can be pooled into one fit with shared latent dynamics. The latent dimension stays shared. Gaussian, Poisson and SLDS paths are all wired.

Design

obs_dim is a property of the [C d D] group rather than of the model: C is obs_dim × latent_dim, d is obs_dim, D is obs_dim × uy_dim, R is obs_dim × obs_dim. Two consequences drive the implementation:

  • Every observation group must be constant in obs_dim within a slot. A shared :R beside a per-session :C has no well-defined size, and mixed widths under one label cannot be one matrix. Both are rejected with a message naming the fix.
  • Dimensions come from the data. Each slot's obs_dim is the row count of the trials assigned to it. A slot whose shape matches the template still copies it; a slot that differs is seeded from its own trials — d at the per-channel mean (its log for Poisson, the natural scale for λ = exp(Cx + d)), R at the per-channel variance, and C by cycling the template's rows so the M-step starts at the template's magnitude rather than at zero.

The cell abstraction already did the hard part: a cell is a maximal set of trials sharing every parameter, gets its own LinearDynamicalSystem, and runs the ordinary smoother on its sub-Data. So per-session obs_dim never reaches the smoothing kernels.

Buffer organisation

A cell's E-step runs across the whole workspace pool in parallel, so each cell needs a pool, not a single workspace — every entry owns the block-tridiagonal storage its task writes through. The split is by what the buffer's shape depends on: anything sized by latent_dim and tsteps is shared by reference; anything sized by obs_dim is per cell.

flowchart LR
    subgraph base["Pool entry i · allocated once per fit"]
        direction TB
        BTD["<b>btd</b><br/>BlockTridiagonalWorkspace<br/><i>O(D²·T)</i>"]
        PSM["<b>agg.p_smooth_shared</b><br/><b>agg.p_smooth_tt1_shared</b><br/><i>O(D²·T)</i>"]
        LLT["<b>ll_tmp</b> (SLDS only)<br/><i>O(T)</i>"]
    end

    subgraph cells["Per cell · sized by that session's width pᶜ"]
        direction TB
        C1["<b>Cell 1 · p₁ channels</b><br/>consts · opt · reg · elbo<br/>agg: obs_xy, obs_yy_const, obs_xy_const<br/><i>O(p₁²) + O(p₁·D)</i>"]
        C2["<b>Cell 2 · p₂ channels</b><br/>consts · opt · reg · elbo<br/>agg: obs_xy, obs_yy_const, obs_xy_const<br/><i>O(p₂²) + O(p₂·D)</i>"]
        CN["<b>Cell n · pₙ channels</b><br/>⋯"]
    end

    BTD -. "shared by reference" .-> C1
    BTD -. " " .-> C2
    BTD -. " " .-> CN
    PSM -. " " .-> C1
    PSM -. " " .-> C2
    PSM -. " " .-> CN
    LLT -. " " .-> C1
    LLT -. " " .-> C2
    LLT -. " " .-> CN
Loading

Sharing is safe for the same reason sharing the pool across cells already was: cells run one at a time, and a cell's smoothed covariances and Hessian blocks are consumed by its own aggregation before the next cell overwrites them.

Shared across cells Allocated per cell
LDS (_cell_workspace) btd, agg.p_smooth_shared, agg.p_smooth_tt1_shared consts, opt, reg, elbo, agg's obs_* blocks
SLDS E-step (_cell_slds_workspace) btd, ll_tmp per-regime consts, opt
SLDS M-step (_slds_cell_mstep_workspaces) as LDS regression buffers for [Cₖ dₖ Dₖ], R scatter

So the O(D²·T) storage stays single-instance no matter how many sessions are stitched. The per-cell cost is O(p²) and O(p·D) plus NewtonBuffers' O(D·T_max), i.e. linear in sessions and well under the shared term. Pools are built once per fit, never per iteration, and the per-slot pooling scratch is cached in a Dict keyed by width, so it is bounded by the number of distinct widths rather than by cells or iterations.

Non-breaking

Every new path is gated on shapes actually differing:

  • _obs_slot_specs returns (nothing, nothing) when all trials have the template width, so _build_variants! runs its original code and slot 1 still aliases the model's own arrays.
  • _cell_sws_pools returns the shared pool itself, and _slds_cell_workspaces / _slds_cell_mstep_workspaces return the base workspace (or nothing), when every cell has the parent's obs_dim.
  • The Data relaxation for ragged rows is behind _has_parameter_dependence.
  • cell_lds[c].obs_dim == lds.obs_dim whenever widths agree.

A fit without depends_on reaches none of it. There are tests pinning this.

Tests

test/LinearDynamicalSystems/Stitching.jl: per-slot shapes and per-cell obs_dim; both validation rules; the ragged-y data rule; a non-breaking test asserting no specs are computed, slot 1 stays aliased, and the shared pool is reused; diagnostics asserting by identity that the big buffers are shared while the obs_dim-shaped ones are not; the pool sized at the widest session; an end-to-end two-session Gaussian fit checking monotonicity, per-session widths and positive-definite R; a stitched-SLDS shape test showing all regimes of a cell share one width while the partition stays common across regimes; the SLDS workspace-sharing diagnostic; and an end-to-end stitched SLDS fit.

Status / caveats

  • None of this has been executed. There is no Julia toolchain in the environment I'm working in and the julialang download hosts are refused by the egress policy, so this is verified by reading only. CI is the first run — which is why it's a draft.
  • Also fixes a latent bug in the grouped SLDS M-step: sufficient statistics were sized from cell 1's LDS for every unit, which is only correct when all cells share a width.
  • The formatting and JET failures inherited from the branches below this one are pre-existing and being handled separately.

claude added 8 commits August 14, 2026 18:55
Under stitching, sessions observe different numbers of channels while sharing
one latent process. The cell machinery already gives each group its own
`LinearDynamicalSystem` and runs the E-step per cell, so the missing piece was
that every variant was built by copying one template array and therefore had
one fixed shape.

`obs_dim` is a property of the `[C d D]` group — `C` is `obs_dim x latent_dim`,
`d` is `obs_dim`, `D` is `obs_dim x uy_dim`, `R` is `obs_dim x obs_dim` — so
each observation group must be constant in `obs_dim` within a slot. A shared
`:R` next to a per-session `:C` has no well-defined size and is now rejected
with a message naming the fix, rather than failing later as a shape error.

Dimensions are inferred from the data: each slot's `obs_dim` is the row count
of the trials assigned to it, checked for consistency within the slot. A slot
whose shape matches the template still copies it, so datasets with a uniform
`obs_dim` produce bit-identical arrays and keep the previous code path. A slot
that differs is seeded from its own trials: `d` at the per-channel mean (its
log for Poisson, which is the natural scale for `lambda = exp(Cx + d)`), `R` at
the per-channel variance, and `C` by cycling the template's rows so the M-step
starts from the template's magnitude rather than from zero.

`_cell_lds` now takes each cell's `obs_dim` from its own emission, `Data`
accepts ragged row counts when the emission is group-dependent, and the
grouped workspace pool is sized at the widest session.

Scope: this is the declaration, shape and validation layer only. The grouped
EM kernels still index the pooled workspace buffers at full width, so a
ragged-`obs_dim` fit does not run end to end yet; the per-cell views, the
Poisson and SLDS entry points, and tests are still to come.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
These buffers hold one cell's `y`, which under stitching is one session's
channels. Equal to the parent's `obs_dim` whenever every session has the same
width, so the uniform case is unchanged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
A cell's E-step runs on the whole workspace pool in parallel, so each cell
needs a pool rather than a single workspace: every pool entry owns the
block-tridiagonal storage its task writes through.

`_cell_workspace` builds one entry by reusing the O(D^2*T) storage of the
corresponding base entry -- the block-tridiagonal solver and both
smoothed-covariance caches -- and allocating only what `obs_dim` shapes. That
is safe for the same reason sharing the pool across cells already was: a
cell's covariances are consumed by its own aggregation before the next cell
runs. The pools are built once per fit, not per iteration, so a long fit
allocates no more than a short one.

When every cell has the parent's `obs_dim` -- which covers every fit without
`depends_on`, and every grouped fit whose sessions have equal width --
`_cell_sws_pools` returns the shared pool itself, so nothing extra is
allocated and the previous code path is what runs.

Pooling sufficient statistics needed the same treatment: `obs_xy`'s column
count is the slot's channel count, so odd widths get scratch built on first
use and cached for the fit, bounded by the number of distinct widths.

Tests cover the per-slot shapes, the two validation rules (a shared `:R`
beside a per-session `:C`, and mixed widths under one label), the ragged-`y`
data rule, an end-to-end stitched fit, and diagnostics asserting that the big
buffers are shared by identity while the `obs_dim`-shaped ones are not -- plus
a non-breaking test pinning that a uniform-width fit computes no specs, keeps
slot 1 aliased to the model's own arrays, and reuses the shared pool.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
`_slds_parameter_grouping` now threads the observations to
`parameter_grouping`, so each regime resolves the same per-session widths from
the data. Every regime of one cell observes one session, so a cell has a single
width shared by all its regimes; the trial partition stays common across
regimes, as the existing agreement check requires.

Two workspaces are shaped by `obs_dim` on this path and both get a per-cell
version:

  * `_cell_slds_workspace` reuses the base workspace's block-tridiagonal
    storage and per-timestep log-density scratch -- the O(D^2*T) and O(T)
    parts, neither of which depends on `obs_dim` -- and allocates fresh
    per-regime constants and Newton buffers at the cell's width.
  * `_slds_cell_mstep_workspaces` does the same for the M-step's regression
    buffers via the LDS-side `_cell_workspace`, since `[Ck dk Dk]` and the
    scatter `R` accumulates into are both `obs_dim`-shaped.

Both return the base workspace (or `nothing`) when every cell has the parent's
width, so an SLDS that is not stitching runs exactly the code it ran before.
The grouped E-step, ELBO, warm-start and M-step take the per-cell workspace as
an optional argument defaulting to the single one.

Also fixes the grouped SLDS M-step's sufficient statistics, which were sized
from cell 1's LDS for every unit; that is only correct when all cells share a
width.

Tests cover the per-cell widths and the shared trial partition, an end-to-end
stitched SLDS fit, and a diagnostic asserting by identity that the
block-tridiagonal and log-density buffers are shared while the per-regime
constants are sized to the cell -- plus that an equal-width model gets the base
workspace back unchanged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
A method signature is evaluated when the method is defined, so the seeding
helpers could not name `ObsSlotSpec` while the struct was declared further
down the file. Precompilation failed with `UndefVarError: ObsSlotSpec`.

Also fixes the SLDS test helper: the per-session truth models were built with
a `depends_on` covering both sessions but sampled one session at a time, so
the label vector would not have matched the trial count.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
`_grouped_gaussian_obs_mstep!` ran every parameter version's `[C d D]`
regression and `R` scatter through the single pooled workspace. Both are
`obs_dim`-shaped, so under stitching a version narrower than the pool would
have written through mismatched buffers.

With uniform widths every entry of `cell_ws1` is `sws_pool[1]` itself, so this
changes nothing for a fit whose sessions have the same number of channels.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
`pd_lds` fixes `obs_dim` at `PD_OBS_DIM`, which is precisely the assumption
this feature removes, so every stitching helper was constructing a model whose
declared `obs_dim` contradicted its own `C`. Sampling then wrote a p-row `y`
into a 2-row buffer and each testset aborted on the first call.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
Two test problems, no production change beyond a comment.

`Data` is not exported into the test module, so the calls needed `SSD.`
qualification; three testsets aborted on it.

The shape assertions assumed one variant per session, but `variants` is
indexed by the Cartesian product of every group's slots: with `:C` and `:R`
both varying over two sessions it holds four entries, and the two cross terms
pair one session's `C` with another's `R`. Those are unreachable -- `_cell_lds`
indexes `grp.cell_obs`, and both groups take their width from the same
per-trial data, so every occupied combination has matching `C` and `R` widths
-- so the tests now assert over the occupied combinations and additionally
pin that `C` and `R` agree there. The property is documented alongside the
stitching design notes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MgmEbyHewqUYTJLFegAoK5
harrisonritz and others added 3 commits August 22, 2026 17:31
Re-lands 072a465, which was reverted from the grouped-Poisson PR because it
calls the pooled `_prepare_cell!(sws_pool, state, cell)` — the `Vector`
method, which only exists here, alongside the per-cell workspace pools. On
that branch only the scalar method is defined and the call is a MethodError.

Handing `update_observation_model!` the cell's own prepared pool rather than
the raw pool means the solve sees that cell's batched buffers and cached
constant blocks, which is what the rest of the grouped M-step already does.

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.
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

❌ Patch coverage is 96.27907% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 96.80%. Comparing base (38bc606) to head (ece8ad9).

Files with missing lines Patch % Lines
src/lds/grouped_em.jl 86.11% 5 Missing ⚠️
src/lds/parameter_groups.jl 98.33% 2 Missing ⚠️
src/lds/fit_SLDS.jl 96.96% 1 Missing ⚠️
Additional details and impacted files
@@                             Coverage Diff                              @@
##           claude/split-pr-165-incremental-t8k2s5-5     #172      +/-   ##
============================================================================
- Coverage                                     96.87%   96.80%   -0.07%     
============================================================================
  Files                                            20       20              
  Lines                                          4224     4387     +163     
============================================================================
+ Hits                                           4092     4247     +155     
- Misses                                          132      140       +8     

☔ 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.

harrisonritz and others added 3 commits August 23, 2026 02:21
…meter

Patch coverage here was 95.37% against a 95.94% target.

The stitching tests were Gaussian throughout, but the per-session sizing is not
emission-agnostic everywhere: `d` is seeded at the per-channel mean for a
Gaussian emission and at its *log* for a Poisson one, since `λ = exp(Cx + d)`,
and that second branch had no caller. `test_stitching_poisson_fit` fits two
Poisson sessions of different widths over shared latents and checks each
session's `C` and `d` come out at its own channel count.

A shared observation parameter takes the one width the dataset has, which is
only well defined when the widths agree; `test_stitching_requires_grouped_R`
covers the rejection, nothing covered the acceptance. The test takes both
sides of it: a dataset matching the template, and one wider than the template
everywhere, where the shared `:R` and the varying `[C d]` all resize to the
data's width rather than the template's.

Stitching 94 -> 117 assertions. Patch coverage of the files this PR touches:
208/216 added executable lines (96.30%). What is left: `_obs_pool_target`'s
alternate-width branch, which needs a `[C d D]` shared across cells at a width
differing from the buffer prototype's — the configuration stitching rejects
elsewhere; `_slds_ws_for`'s `nothing` fallback; `_obs_stats`'s no-data method,
reachable only for a slot no trial selects; and `_seed_slot_d`'s signature
line, which Julia's instrumentation scores 0 while counting its body.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014wJNTtEFZwFUUFvgKbq4F7
Codecov's target is the base branch's coverage, so raising #170's raised this
PR's bar to 96.80% and 96.29% no longer cleared it.

The gap worth closing was `_obs_pool_target`'s alternate-width branch, the one
`GroupedSufBuffers`' own comment describes: pooling writes into a scratch
`obs_xy` whose column count is the slot's channel count, and the preallocated
one is sized from the model's `obs_dim`, so a slot shared across cells at some
other width needs its own. Reaching it takes all three of a shared `[C d D]`,
more than one cell pooling into it, and a dataset the model was not built at —
group `:R`, leave `[C d D]` shared, and hand a 3-channel template 5-channel
data. The test pins that the pooled emission comes out at the data's width and
stays shared by reference while each cell keeps its own resized `:R`.

Stitching 117 -> 128 assertions. Patch coverage 213/216 added executable lines
(98.61%). The three left are `_obs_stats`'s no-data method (reachable only for
a slot no trial selects), `_slds_ws_for`'s `nothing` fallback (a kwarg default
no caller in the package takes), and `_seed_slot_d`'s signature line, which
Julia's instrumentation scores 0 while counting its body.

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:33
harrisonritz and others added 2 commits August 23, 2026 18:14
The stitching per-cell workspaces and the GLS branch both land in
`_grouped_update_C_d!`: the pooled path keeps its per-unit workspace, and the
GLS path is taken on the same condition as elsewhere.
The stitching section header keeps the shape rule and the note that the
cross-product variants are unreachable, and drops the rest.

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