Skip to content

Add regularized Unified CEBRA: feature attribution map, faster unified inference, cleanup - #313

Open
CeliaBenquet wants to merge 24 commits into
AdaptiveMotorControlLab:mainfrom
CeliaBenquet:celia/unfied-xcebra
Open

CeliaBenquet wants to merge 24 commits into
AdaptiveMotorControlLab:mainfrom
CeliaBenquet:celia/unfied-xcebra

Conversation

@CeliaBenquet

@CeliaBenquet CeliaBenquet commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Unified solvers (cebra/solver/unified_session.py)

  • UnifiedSolverxCEBRA (registered as "unified-xcebra"): unified CEBRA with the xCEBRA Jacobian regularizer. It uses a single objective; it builds on the multi-objective base class only for the regularizer and its weight schedule.
  • solver.aligned_inputs(...) builds the unified model input for a session. One shared implementation replaces the copies we had in previous version.
  • transform(), for both unified solvers:
    • The previous version padded every batch separately. Rows near batch edges therefore saw padding instead of their neighbours; this is fixed. Also no longer fails for sessions shorter than twice batch_size.
    • random_ties added, to make sure if there are nearest-neighbor ties, this is sampled uniformly (until now, first one was the default).
  • split_outputs is removed from the unified transform(); it always returns the concatenated embedding, as multiple objectives was not implemented.

Feature attribution maps (cebra.attribution)

A new module, cebra/attribution/feature_map.py, computes how each input channel drives each behavioural or stimulus feature through the embedding, for models trained with the Jacobian regularizer. It exposes three functions:

  • fit_feature_readout(embedding, features, alpha=1.0, train_fraction=None, train_index=None): fits a ridge readout W (D × F) from the embedding to the features.
  • feature_attribution_map(solver, inputs, W, *, labels=None, session_id=None, indices=None, output_slice=None, average=True, random_ties=False, seed=0, ...): the signed map M = Jᵀ W, with J the Jacobian of the embedding with respect to the input window. average=True returns the time mean (N × F). It accepts single-session solvers, including one head of a subspace model via output_slice, and unified solvers. It accepts only solvers trained with the Jacobian regularizer.
  • average_feature_maps(maps): the mean of maps from several models. Each model needs its own W.

Cleanup and fixes

  • Dependencies and debug output:
    • Removed the hard wandb import and the stray print calls
    • torch_brain is imported only when the Perich loader needs it, and perich.py has its licence header.
  • Checkpoint loading:
    • Solver.load defaults to the safe path (weights_only=None, which is True on torch ≥ 2.6).
    • The allowed types now include numpy scalars and dtypes, so checkpoints saved under numpy 1 or 2 load safely.
  • Removed unused code: expand_index_forward and ForwardTensorDataset.
  • Masking: simplified by removing the combined-mask and noise-filling options.
  • Docs: API pages added for the unified solvers, masking, the unified datasets and loaders, and feature_map.

CeliaBenquet and others added 11 commits December 9, 2025 13:36
Remove pkg_resources usage and replace with modern alternatives

- Replace pkg_resources.parse_version() with packaging.version.parse()
- Replace pkg_resources.get_distribution() with importlib.metadata.distribution()
- Update imports in cebra/integrations/sklearn/cebra.py, cebra/helper.py, tests/test_sklearn.py, tests/test_plot.py
- Fixes deprecation warning: pkg_resources is deprecated as an API and slated for removal as early as 2025-11-30

Resolves AdaptiveMotorControlLab#271
- Added `output_batch_size` parameter to `compute_jacobian` for chunked processing, reducing peak GPU memory usage.
- Refactored Jacobian computation logic to handle smaller output batches efficiently.
- Introduced `_normalize_selected_result_keys` function to validate selected attribution result keys.
- Updated `JFMethodBased` and `JFMethodBasedBatched` classes to support new output batch size functionality.
- Implemented `UnifiedxCEBRADataset` for flexible per-objective label handling in multi-objective learning.
- Enhanced `MultiSessionLoader` and `UnifiedContrastiveMultiObjectiveLoader` for improved device management and sampling.
- Added `UnifiedSampler` to streamline sampling across multiple sessions with shared reference and negative samples.
- Updated `Solver` and `MultiobjectiveSolver` classes to support unified multi-objective training with a single shared model.
@cla-bot cla-bot Bot added the CLA signed label Nov 13, 2026
- Introduced feature map attribution methods in `cebra.attribution.feature_map`.
- Updated documentation for attribution and solvers to include new feature map methods.
- Added tests for feature map functionality
- Handled tensor operations and added checks for input shapes in various test cases.
@CeliaBenquet CeliaBenquet changed the title Add regularized Unified CEBRA and feature attribution map Add regularized Unified CEBR: feature attribution map, faster unified inference, cleanup Nov 13, 2026
@CeliaBenquet CeliaBenquet changed the title Add regularized Unified CEBR: feature attribution map, faster unified inference, cleanup Add regularized Unified CEBRA: feature attribution map, faster unified inference, cleanup Nov 13, 2026

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved critical defects can leak masks across datasets, make subsampled inference depend on batch size, and break learning-rate scheduler progression and checkpoint restoration.

8 open issues
What changed in this PR

This PR extends CEBRA’s PyTorch APIs with regularized unified-session training and feature attribution maps, while improving unified inference and checkpoint handling.

Changes:

  • Add unified xCEBRA training and signed feature maps linking input channels to features through embeddings.
  • Rework unified inference and nearest-label sampling, including reproducible tie handling and batching improvements.
  • Add scheduler support, masking and dataset utilities, regression tests, and API documentation.
File Description
tests/​test_solver.py Test unified inference, alignment, and checkpoint loading.
tests/​test_models.py Test Jacobian regularizer values and gradients.
tests/​test_integration_xcebra.py Move embeddings to CPU for NumPy comparisons.
tests/​test_feature_map.py Test readouts, feature maps, and solver dispatch.
tests/​test_distributions.py Test tie sampling and optimized nearest-label search.
tests/​test_data_masking.py Test session-block masking.
tests/​test_attribution.py Test optimized attribution and output batching.
docs/​source/​api/​pytorch/​solvers.rst Document unified solvers and link multi-objective APIs.
docs/​source/​api/​pytorch/​data.rst Add unified-data and masking references.
docs/​source/​api/​pytorch/​attribution.rst Expose feature-map API documentation.
cebra/​solver/​unified_session.py Share alignment logic, revise inference, and add unified xCEBRA.
cebra/​solver/​multiobjective.py Link unified solvers and normalize logged NumPy scalars.
cebra/​solver/​base.py Add checkpoint allowlisting and learning-rate scheduler support.
cebra/​models/​multiobjective.py Remove debug prints.
cebra/​models/​jacobian_regularizer.py Create projection tensors on the input device.
cebra/​distributions/​multisession.py Add device-aware sampling and optimized tie handling.
cebra/​distributions/​__init__.py Export UnifiedSampler.
cebra/​datasets/​allen/​single_session_ca.py Add configurable cortex and neuron-type loading.
cebra/​datasets/​__init__.py Whitespace-only cleanup.
cebra/​data/​multiobjective.py Add unified contrastive loading and sampling configuration.
cebra/​data/​multi_session.py Move sampled indices to the loader device.
cebra/​data/​masking.py Add list-based configuration and session-block masks.
cebra/​data/​datasets.py Extend device transfers and add unified xCEBRA batches.
cebra/​attribution/​feature_map.py Implement ridge readouts and signed feature attribution maps.
cebra/​attribution/​attribution_models.py Add optimized Jacobian batching and lazy optional imports.
cebra/​attribution/​_jacobian.py Add output-dimension chunking for Jacobian computation.
cebra/​attribution/​__init__.py Export the feature-map functions.

Review effort: Balanced

Comment thread cebra/data/masking.py Resolved
Comment thread cebra/solver/base.py Resolved
Comment thread cebra/solver/base.py Resolved
Comment thread cebra/solver/base.py Resolved
Comment thread cebra/solver/unified_session.py Resolved
Comment thread cebra/attribution/_jacobian.py Resolved
Comment thread cebra/data/multiobjective.py Resolved
Comment thread cebra/data/multiobjective.py Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants