From c3cd4074b547794ba91b0c7ec951f8c30c43ebfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Tue, 9 Dec 2025 13:36:43 +0100 Subject: [PATCH 01/27] Add unified cebra datasets and session masking --- cebra/__init__.py | 1 + cebra/data/base.py | 85 ++++-- cebra/data/datasets.py | 37 +++ cebra/data/masking.py | 301 ++++++++++++++++++++-- cebra/datasets/__init__.py | 4 + cebra/datasets/allen/single_session_ca.py | 48 ++++ cebra/datasets/make_nlb_data.py | 170 ++++++++++++ cebra/datasets/nlb_data.py | 248 ++++++++++++++++++ cebra/datasets/perich.py | 133 ++++++++++ cebra/datasets/poyo_data.py | 58 +++++ cebra/integrations/sklearn/decoder.py | 82 ++++++ cebra/solver/base.py | 78 +++++- 12 files changed, 1194 insertions(+), 51 deletions(-) create mode 100644 cebra/datasets/make_nlb_data.py create mode 100644 cebra/datasets/nlb_data.py create mode 100644 cebra/datasets/perich.py create mode 100644 cebra/datasets/poyo_data.py diff --git a/cebra/__init__.py b/cebra/__init__.py index a8631b51..b1c76f2b 100644 --- a/cebra/__init__.py +++ b/cebra/__init__.py @@ -31,6 +31,7 @@ from cebra.integrations.sklearn.cebra import CEBRA from cebra.integrations.sklearn.decoder import KNNDecoder from cebra.integrations.sklearn.decoder import L1LinearRegressor + from cebra.integrations.sklearn.decoder import MLPDecoder is_sklearn_available = True except ImportError: diff --git a/cebra/data/base.py b/cebra/data/base.py index 51199cec..d2f5651e 100644 --- a/cebra/data/base.py +++ b/cebra/data/base.py @@ -22,6 +22,7 @@ """Base classes for datasets and loaders.""" import abc +from typing import List import literate_dataclasses as dataclasses import torch @@ -145,14 +146,21 @@ def expand_index(self, index: torch.Tensor) -> torch.Tensor: return index[:, None] + offset[None, :] - def expand_index_in_trial(self, index, trial_ids, trial_borders): - """When the neural/behavior is in discrete trial, e.g) Monkey Reaching Dataset - the slice should be defined within the trial. - trial_ids is in size of a length of self.index and indicate the trial id of the index belong to. - trial_borders is in size of a length of self.idnex and indicate the border of each trial. + def expand_index_in_trial(self, index: torch.Tensor, trial_ids: List[int], + trial_borders: List[int]) -> torch.Tensor: + """ + + Note: + When the neural/behavior is in discrete trial, e.g) Monkey Reaching Dataset + the slice should be defined within the trial. + + Args: + index: A one-dimensional tensor of type long containing indices + to select from the dataset. + trial_ids: Indicate the trial id to which the index belong to, + size of ``len(self.index)``. + trial_borders: Indicate the border of each trial, size of ``len(self.index)``. - Todo: - - rewrite """ # TODO(stes) potential room for speed improvements by pre-allocating these tensors/ @@ -160,16 +168,59 @@ def expand_index_in_trial(self, index, trial_ids, trial_borders): offset = torch.arange(-self.offset.left, self.offset.right, device=index.device) - index = torch.tensor( - [ - torch.clamp( - i, - trial_borders[trial_ids[i]] + self.offset.left, - trial_borders[trial_ids[i] + 1] - self.offset.right, - ) for i in index - ], - device=self.device, - ) + + index = torch.tensor([ + torch.clamp( + i, + trial_borders[trial_ids[i]] + self.offset.left, + trial_borders[trial_ids[i] + 1] - self.offset.right, + ) for i in index + ], + device=index.device) + + print(index) + return index[:, None] + offset[None, :] + + def expand_index_in_trial_padding(self, index: torch.Tensor, + trial_ids: List[int], + trial_borders: List[int]) -> torch.Tensor: + offset = torch.arange(-self.offset.left, + self.offset.right, + device=index.device) + + base = index[:, None] + offset[None, :] + + trial_borders = torch.tensor(trial_borders, device=index.device) + trial_ids = torch.tensor(trial_ids, device=index.device) + + trial_start = trial_borders[trial_ids[index]] + trial_end = trial_borders[trial_ids[index] + 1] - 1 + + return torch.minimum(torch.maximum(base, trial_start[:, None]), + trial_end[:, None]) + + def expand_index_forward(self, index: torch.Tensor) -> torch.Tensor: + """Expand the index to include the offset in the forward direction only. + + Args: + index: A one-dimensional tensor of type long containing indices + to select from the dataset. + + Returns: + An expanded index of shape ``(len(index), len(self.offset))``. + + + Note: + Requires the :py:attr:`offset` to be set. + + """ + offset = torch.arange(self.offset.left + self.offset.right + 1, + device=index.device) + + index = torch.clamp( + index, 0, + len(self) - (self.offset.right + self.offset.left + 1)) + return index[:, None] + offset[None, :] @abc.abstractmethod diff --git a/cebra/data/datasets.py b/cebra/data/datasets.py index 8549000f..689452cf 100644 --- a/cebra/data/datasets.py +++ b/cebra/data/datasets.py @@ -165,6 +165,43 @@ def _assert_datasets_same_device( return devices.pop() +class ForwardTensorDataset(TensorDataset): + """A dataset that returns items on the range [idx, idx + offset). + + Note: + This is useful for training models on predictive neural activity (e.g., grid cells, place cells). + """ + + def __getitem__(self, index: torch.Tensor) -> torch.Tensor: + index = self.expand_index_forward(index) + return self.neural[index].transpose(2, 1) + + +class TrialTensorDataset(TensorDataset): + """A dataset that returns items on the range [idx, idx + offset). + + Note: + This is useful for training models on predictive neural activity (e.g., grid cells, place cells). + """ + + def __init__(self, + neural: Union[torch.Tensor, npt.NDArray], + continuous: Union[torch.Tensor, npt.NDArray] = None, + discrete: Union[torch.Tensor, npt.NDArray] = None, + offset: Offset = Offset(0, 1), + device: str = "cpu", + trial_ids: Union[torch.Tensor, npt.NDArray] = None, + trial_borders: Union[torch.Tensor, npt.NDArray] = None): + super().__init__(neural, continuous, discrete, offset, device) + self.trial_ids = trial_ids + self.trial_borders = trial_borders + + def __getitem__(self, index: torch.Tensor) -> torch.Tensor: + index = self.expand_index_in_trial_padding(index, self.trial_ids, + self.trial_borders) + return self.neural[index].transpose(2, 1) + + class DatasetCollection(cebra_data.MultiSessionDataset): """Multi session dataset made up of a list of datasets. diff --git a/cebra/data/masking.py b/cebra/data/masking.py index 90faf51e..ca8d1901 100644 --- a/cebra/data/masking.py +++ b/cebra/data/masking.py @@ -15,14 +15,14 @@ # import abc import random -from typing import Dict, List, Optional, Tuple, Union +from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import torch __all__ = [ "MaskedMixin", "Mask", "RandomNeuronMask", "RandomTimestepMask", - "NeuronBlockMask", "TimeBlockMask" + "NeuronBlockMask", "TimeBlockMask", "SessionBlockMask" ] @@ -37,29 +37,118 @@ class MaskedMixin: """ _masks = [] # a list of Mask instances - def set_masks(self, masking: Optional[Dict[str, float]] = None) -> None: - """Set the mask type and probability for the dataset. + def set_masks( + self, + masking: Optional[Union[ + Dict[str, Any], + List[Union[Tuple[str, Any], Dict[str, Any]]], + ]] = None, + apply_multiple_masks: bool = False, + fill_with_noise: bool = False, + ) -> None: + """Set the mask types and parameters for the dataset. + + Supports two input formats: + - Dict[str, params]: One instance per mask type; replaces any previous + instance of the same class (backward compatible). + - List[ (name, params) | {name: params} ]: Adds one instance per entry, + allowing multiple instances of the same mask with different params. Args: - masking (Dict[str, float]): A dictionary of masking types and their - corresponding required masking values. The keys are the names - of the Mask instances. + masking: Mask configuration. See formats above. + apply_multiple_masks: When True, `apply_mask` will randomly pick a + number of configured masks and apply them all in a single call + (combined). When False, a single mask is sampled per call + (default/legacy behavior). + fill_with_noise: When True, masked positions are filled with Gaussian + noise sampled from per-neuron mean and std (computed from unmasked + values). When False, masked positions are zeroed (default/legacy behavior). Note: - By default, no masks are applied. + - By default, no masks are applied. + - When using the dict format, existing instances of the same mask + class are replaced. When using the list format, entries are + appended, allowing duplicates with different parameters. """ - if masking is not None: - for mask_key in masking: + # Store strategy + self._apply_multiple_masks = bool(apply_multiple_masks) + self._fill_with_noise = bool(fill_with_noise) + + if masking is None: + return + + # Helper to resolve and create a mask instance by name and params + def _create_mask(mask_key: str, params: Any) -> None: + # First try exact match + if mask_key in globals(): + cls = globals()[mask_key] + self._masks.append(cls(params)) + return + + # Try fuzzy match: find mask classes that start with mask_key + # e.g., "SessionBlockMask2" -> match "SessionBlockMask" + for available_mask in __all__: + if available_mask == "MaskedMixin" or available_mask == "Mask": + continue + if mask_key.startswith(available_mask): + cls = globals()[available_mask] + self._masks.append(cls(params)) + return + + # No match found + raise ValueError( + f"Mask type {mask_key} not supported. Supported types are {__all__}" + ) + + # Dict mode: replace-by-class semantics (backward compatible) + if isinstance(masking, dict): + for mask_key, params in masking.items(): + # Resolve the actual mask class (supports fuzzy matching) + cls = None if mask_key in globals(): cls = globals()[mask_key] - self._masks = [ - m for m in self._masks if not isinstance(m, cls) - ] - self._masks.append(cls(masking[mask_key])) + else: + # Try fuzzy match + for available_mask in __all__: + if available_mask == "MaskedMixin" or available_mask == "Mask": + continue + if mask_key.startswith(available_mask): + cls = globals()[available_mask] + break + + if cls is None: + raise ValueError( + f"Mask type {mask_key} not supported. Supported types are {__all__}" + ) + + # Remove previous instances of this class, then add one + self._masks = [m for m in self._masks if not isinstance(m, cls)] + _create_mask(mask_key, params) + return + + # List mode: append semantics; allow duplicates of the same mask class + if isinstance(masking, list): + for entry in masking: + if isinstance(entry, tuple) and len(entry) == 2: + mask_key, params = entry + _create_mask(mask_key, params) + elif isinstance(entry, dict): + if len(entry) != 1: + raise ValueError( + "Each dict entry in the masking list must have exactly one key." + ) + mask_key, params = next(iter(entry.items())) + _create_mask(mask_key, params) else: raise ValueError( - f"Mask type {mask_key} not supported. Supported types are {masking.keys()}" + "List masking entries must be either (name, params) tuples or {name: params} dicts." ) + return + + # Unsupported type + raise ValueError( + "masking must be either a dict{name: params} or a list of (name, params)/{name: params} entries." + ) def apply_mask(self, data: torch.Tensor, @@ -94,17 +183,53 @@ def apply_mask(self, if not self._masks: return data - sampled_mask = random.choice(self._masks) - mask = sampled_mask.apply_mask(data) + # Compute the mask to apply (single or combined) + if getattr(self, "_apply_multiple_masks", False): + # Randomly choose how many masks to apply (at least one, at most all) + num_to_apply = random.randint(1, len(self._masks)) + selected_masks = random.sample(self._masks, num_to_apply) - num_chunks = (data.shape[0] + chunk_size - - 1) // chunk_size # Compute number of chunks + # Start with all-ones mask and combine multiplicatively (logical AND) + mask = torch.ones_like(data, dtype=torch.int) + for m in selected_masks: + mask = mask.mul(m.apply_mask(data)) + else: + sampled_mask = random.choice(self._masks) + mask = sampled_mask.apply_mask(data) + + # Apply masking strategy: zeros or Gaussian noise + if getattr(self, "_fill_with_noise", False): + # Fill masked positions with per-neuron Gaussian noise + # mask: (batch_size, n_neurons, offset) with 1=keep, 0=mask + inverse_mask = (mask == 0) # True where we need to fill + + # Compute per-neuron mean and std from unmasked values + # Shape: (batch_size, n_neurons) + masked_data = data * mask # Zero out masked positions + sum_unmasked = masked_data.sum(dim=2) # Sum over time + count_unmasked = mask.sum(dim=2).clamp( + min=1) # Count valid timesteps + mean_per_neuron = sum_unmasked / count_unmasked # (batch_size, n_neurons) + + # Compute std + squared_diff = ((data - mean_per_neuron.unsqueeze(2))**2) * mask + var_per_neuron = squared_diff.sum(dim=2) / count_unmasked + std_per_neuron = var_per_neuron.sqrt().clamp( + min=1e-6) # Avoid div by zero + + # Generate Gaussian noise and fill masked positions + noise = torch.randn_like(data) * std_per_neuron.unsqueeze( + 2) + mean_per_neuron.unsqueeze(2) + data = torch.where(inverse_mask, noise, data) + else: + # Legacy behavior: multiply by mask (zeros out masked positions) + num_chunks = (data.shape[0] + chunk_size - + 1) // chunk_size # Compute number of chunks - for i in range(num_chunks): - start, end = i * chunk_size, min((i + 1) * chunk_size, - data.shape[0]) - data[start:end].mul_( - mask[start:end]) # apply mask in-place to save memory + for i in range(num_chunks): + start, end = i * chunk_size, min((i + 1) * chunk_size, + data.shape[0]) + data[start:end].mul_(mask[start:end]) # in-place for memory return data @@ -245,7 +370,7 @@ def apply_mask(self, data: torch.Tensor) -> torch.Tensor: batch_idx, n_neurons, offset_length = data.shape mask_ratio = self._select_masking_params() - # Random mask: shape [batbatch_idxch_size, offset_length], different per batch and timestamp + # Random mask: shape [batch_idx, offset_length], different per batch and timestamp masked = torch.rand(batch_idx, offset_length, device=data.device) < mask_ratio return (~masked).int().unsqueeze(1).expand(-1, n_neurons, @@ -346,6 +471,132 @@ def _select_masking_params(self) -> float: return selected_value +class SessionBlockMask(Mask): + + def __init__(self, masking_value: Union[List[int], Tuple[List[int], int]]): + super().__init__(masking_value) + # Handle both list and tuple (list, num_sessions) formats + if isinstance(masking_value, tuple): + self.num_neurons = masking_value[0] + self.fixed_num_sessions = masking_value[1] + else: + self.num_neurons = masking_value + self.fixed_num_sessions = None + + def __name__(self): + return "SessionBlockMask" + + def apply_mask(self, data: torch.Tensor) -> torch.Tensor: + """ Apply masking to contiguous blocks of neurons corresponding to sessions. + + Args: + data: batch of size (batch_size, n_neurons, offset). + self.mask_prop: Proportion of neurons to mask. The neurons are masked in a + contiguous block. + + Returns: + torch.Tensor: The mask, a tensor of the same size as the input data with the + masked neurons set to 1. + """ + batch_size, n_neurons, offset_length = data.shape + + if sum(self.num_neurons) != n_neurons: + raise ValueError( + f"Sum of num_neurons {sum(self.num_neurons)} defined at init does not match " + f"the number of neurons in the data {n_neurons}.") + + num_mask, start_idx = self._select_masking_params() + mask = torch.ones((batch_size, n_neurons), + dtype=torch.int, + device=data.device) + + for i in range(len(num_mask)): + end_idx = min(start_idx[i] + num_mask[i], n_neurons) + mask[:, start_idx[i]:end_idx] = 0 # set masked neurons to 0 + + return mask.unsqueeze(2).expand( + -1, -1, offset_length) # Expand to all timesteps + + def _select_masking_params(self) -> Tuple[List[int], List[int]]: + """ + Select which sessions to mask. + If fixed_num_sessions is set (from tuple input), use that exact number. + Otherwise, randomly pick between 1 and len(num_neurons)-1 sessions. + """ + if isinstance(self.num_neurons, list): + # Determine number of sessions to mask + if self.fixed_num_sessions is not None: + select_num_sessions = self.fixed_num_sessions + else: + # Select the # of sessions to mask randomly + select_num_sessions = random.randint(1, + len(self.num_neurons) - 1) + + # Select session indices to mask + select_idxs = random.sample(range(len(self.num_neurons)), + select_num_sessions) + num_mask, start_idx = [], [] + for select_idx in select_idxs: + num_mask.append(self.num_neurons[select_idx]) + start_idx.append(sum(self.num_neurons[:select_idx])) + else: + raise ValueError( + f"Number of neurons {self.num_neurons} for {self.__name__()} " + "should be a list of the number of neurons in each session.") + + return num_mask, start_idx + + def _check_masking_parameters(self, masking_value: Union[List[int], + Tuple[List[int], + int]]): + """ + The masking values are the number of neurons per session to mask. + It can be: + - A list of positive integers (one per session) + - A tuple of (list of positive integers, int) where the int is the fixed number of sessions to mask + """ + if isinstance(masking_value, tuple): + # Validate tuple format: (list, int) + if len(masking_value) != 2: + raise ValueError( + f"Tuple format for {self.__name__()} should be (list, int), " + f"got tuple of length {len(masking_value)}.") + neuron_list, num_sessions = masking_value + + # Validate the list part + if not isinstance(neuron_list, list): + raise ValueError( + f"First element of tuple for {self.__name__()} should be a list, " + f"got {type(neuron_list)}.") + if not all(isinstance(n, int) for n in neuron_list) or any( + n <= 0 for n in neuron_list): + raise ValueError( + f"Neuron list {neuron_list} for {self.__name__()} " + "should be a list of positive integers.") + + # Validate the int part + if not isinstance(num_sessions, int) or num_sessions <= 0: + raise ValueError( + f"Second element of tuple for {self.__name__()} should be a positive integer, " + f"got {num_sessions}.") + if num_sessions >= len(neuron_list): + raise ValueError( + f"Number of sessions to mask ({num_sessions}) must be less than " + f"total number of sessions ({len(neuron_list)}).") + + elif isinstance(masking_value, list): + # Validate list format + if not all(isinstance(n, int) for n in masking_value) or any( + n <= 0 for n in masking_value): + raise ValueError( + f"Number of neurons {masking_value} for {self.__name__()} " + "should be a list of positive integers.") + else: + raise ValueError( + f"Masking value for {self.__name__()} should be either a list of positive integers " + f"or a tuple of (list, int), got {type(masking_value)}.") + + class TimeBlockMask(Mask): def __init__(self, masking_value: Union[float, List[float], Tuple[float]]): diff --git a/cebra/datasets/__init__.py b/cebra/datasets/__init__.py index 5716e399..c1b30311 100644 --- a/cebra/datasets/__init__.py +++ b/cebra/datasets/__init__.py @@ -97,6 +97,10 @@ def get_datapath(path: str = None) -> str: from cebra.datasets.hippocampus import * from cebra.datasets.monkey_reaching import * from cebra.datasets.synthetic_data import * + from cebra.datasets.nlb_data import * + from cebra.datasets.poyo_data import * + from cebra.datasets.perich import * + except ModuleNotFoundError as e: warnings.warn(f"Could not initialize one or more datasets: {e}. " f"For using the datasets, consider installing the " diff --git a/cebra/datasets/allen/single_session_ca.py b/cebra/datasets/allen/single_session_ca.py index 794de602..46388141 100644 --- a/cebra/datasets/allen/single_session_ca.py +++ b/cebra/datasets/allen/single_session_ca.py @@ -116,6 +116,54 @@ def __getitem__(self, index): return self.neural[index].transpose(2, 1) +class SingleSessionAllenCaCortex(SingleSessionAllenCa): + """A single mouse 30Hz calcium events dataset during the allen MOVIE1 stimulus. + + A dataset of a single mouse 30Hz calcium events from the excitatory neurons in the primary visual cortex + during the 10 repeats of the MOVIE1 stimulus in session type A. The preprocessed data from *Deitch et al. (2021) are used. + The continuous labels corresponding to a DINO embedding of each stimulus frame. + + Args: + session_id: The integer value to pick a session among 4 sessions with the largest number of recorded neruons. Choose between 0-3. + frame_feature_path: The path of the movie frame features. + + """ + + def __init__( + self, + session_id: int = 680156909, + frame_feature_path: str = pathlib.Path(_DEFAULT_DATADIR) / "allen" / + "features" / "allen_movies" / "vit_base" / "8" / + "movie_one_image_stack.npz" / "testfeat.pth", + cortex: str = "VISp", + neuron_type: str = "calcium_excitatory", + ): + self.path = pathlib.Path( + _DEFAULT_DATADIR + ) / "allen" / "visual_drift" / "data" / f'{neuron_type}' / f'{cortex}' / f"{session_id}.mat" + traces = scipy.io.loadmat(self.path) + + neural = traces["filtered_traces_days_events"][0, 0].transpose(1, 0) + self.neural = torch.from_numpy(neural).float() + frame_feature = torch.load(frame_feature_path) + self.index = frame_feature.repeat(10, 1) + + def __len__(self): + return self.neural.size(0) + + @property + def continuous_index(self): + return self.index + + @property + def input_dimension(self): + return self.neural.size(1) + + def __getitem__(self, index): + index = self.expand_index(index) + return self.neural[index].transpose(2, 1) + + @parametrize( "allen-movie1-ca-single-session-corrupt-{session_id}", session_id=range(len(_SINGLE_SESSION_CA)), diff --git a/cebra/datasets/make_nlb_data.py b/cebra/datasets/make_nlb_data.py new file mode 100644 index 00000000..66a632d8 --- /dev/null +++ b/cebra/datasets/make_nlb_data.py @@ -0,0 +1,170 @@ +""" +Example on how to run in folder cebra/datasets: +``` +python make_nlb_data.py --dataset_name mc_maze_large +``` +""" + +import argparse +import os +import pathlib + +import joblib as jl +import numpy as np +import scipy.signal as signal +from nlb_tools.make_tensors import make_eval_input_tensors +from nlb_tools.make_tensors import make_eval_target_tensors +from nlb_tools.make_tensors import make_train_input_tensors +from nlb_tools.nwb_interface import NWBDataset + +dataset_dict = { + "mc_maze": "000128/sub-Jenkins/", + "mc_maze_small": "000140/sub-Jenkins/", + "mc_maze_medium": "000139/sub-Jenkins/", + "mc_maze_large": "000138/sub-Jenkins/", + "mc_rtt": "000129/sub-Indy", + "area2_bump": "000127/sub-Han/", + "dmfc_rsg": "000130/sub-Haydn", +} + +parser = argparse.ArgumentParser() +parser.add_argument("--datapath", type=str, default="/data/celia/nlb") +parser.add_argument("--dataset_name", type=str, required=True) +parser.add_argument("--savepath", + type=str, + default="/mnt/data_storage/celia/nlb/data") +parser.add_argument("--bin_width", type=int, default=5) +parser.add_argument("--smoothing_width", type=int, default=50) +parser.add_argument("--split", type=str, default="train") + +args = parser.parse_args() +args.datapath = pathlib.Path(args.datapath) +args.savepath = pathlib.Path(args.savepath) + +if args.dataset_name not in dataset_dict.keys(): + raise NotImplementedError(f"{args.dataset_name}") + +if args.split == "full-train": + prefix = "" + phase = "test" + +elif args.split != "test": + prefix = "*train" + phase = "val" + +elif args.split == "test": + prefix = "*test" + phase = "test" + +dataset = NWBDataset(args.datapath / dataset_dict[args.dataset_name], prefix) +dataset.resample(args.bin_width) + +suffix = "" if (args.bin_width == 5) else f"_{int(round(args.bin_width))}" + +if args.smoothing_width != 0: + smoothing_tag = f"_smth{args.smoothing_width}" +else: + smoothing_tag = "" + + +def smoothing(kern_sd, spikes, bin_size_ms): + window = signal.gaussian(int(6 * kern_sd / bin_size_ms), + int(kern_sd / bin_size_ms), + sym=True) + window /= np.sum(window) + + def filt(x): + return np.convolve(x, window, "same") + + if kern_sd != 0: + convolved = np.apply_along_axis(filt, 1, spikes) + print(np.any(np.isnan(convolved))) + return convolved + else: + return spikes + + +eval_dict = make_eval_input_tensors(dataset, + dataset_name=args.dataset_name, + trial_split=phase, + save_file=False) +eval_spikes_heldin = eval_dict["eval_spikes_heldin"] + +if args.split != "test": + train_trial_split = "train" if (phase == "val") else ["train", "val"] + train_dict = make_train_input_tensors( + dataset, + dataset_name=args.dataset_name, + trial_split=train_trial_split, + save_file=False, + include_behavior=True, + include_forward_pred=False, + ) + + train_spikes_heldin = train_dict["train_spikes_heldin"] + train_spikes_heldout = train_dict["train_spikes_heldout"] + + # Generate target data + target_dict = make_eval_target_tensors( + dataset, + dataset_name=args.dataset_name, + train_trial_split="train", + eval_trial_split="val", + include_psth=False, + save_file=False, + ) + + train_behavior = target_dict[f"{args.dataset_name}{suffix}"][ + "train_behavior"] + + if args.split == "train": + eval_spikes_heldout = eval_dict["eval_spikes_heldout"] + eval_behavior = target_dict[f"{args.dataset_name}{suffix}"][ + "eval_behavior"] + data_dict = { + "train_behavior": + train_behavior, + "eval_behavior": + eval_behavior, + "train_neural_heldin": + smoothing(args.smoothing_width, train_spikes_heldin, + args.bin_width), + "eval_neural_heldin": + smoothing(args.smoothing_width, eval_spikes_heldin, + args.bin_width), + "train_neural_heldout": + train_spikes_heldout, + "eval_neural_heldout": + eval_spikes_heldout, + } + elif args.split == "full-train": + data_dict = { + "train_behavior": + train_behavior, + "train_neural_heldin": + smoothing(args.smoothing_width, train_spikes_heldin, + args.bin_width), + "train_neural_heldout": + train_spikes_heldout, + "eval_neural_heldin": + smoothing(args.smoothing_width, eval_spikes_heldin, + args.bin_width), + } + +elif args.split == "test": + data_dict = { + "eval_neural_heldin": + smoothing(args.smoothing_width, eval_spikes_heldin, args.bin_width) + } + +jl.dump( + data_dict, + args.savepath / + f"{args.dataset_name}_{args.split}{suffix}{smoothing_tag}.jl", +) + +if args.split != "test": + jl.dump( + target_dict, + args.savepath / f"target_dict_{args.dataset_name}{suffix}.jl", + ) diff --git a/cebra/datasets/nlb_data.py b/cebra/datasets/nlb_data.py new file mode 100644 index 00000000..8c0d688e --- /dev/null +++ b/cebra/datasets/nlb_data.py @@ -0,0 +1,248 @@ +import os + +import joblib as jl +import numpy as np +import scipy.stats +import sklearn.cluster +import torch + +import cebra.data +import cebra.io +from cebra.datasets import get_datapath +from cebra.datasets import parametrize + +_DEFAULT_DATADIR = get_datapath() + + +class NLBDataset(cebra.data.SingleSessionDataset): + + def __init__(self, bin_width, split="train"): + super().__init__() + self.bin_width = int(bin_width) + self.split_tag = split + + def define_dataset(self, bin_width, smoothing, split): + if bin_width == str(5): + name_bin = "" + else: + name_bin = f"_{bin_width}" + + if smoothing != 0: + smth = f"_smth{smoothing}" + else: + smth = "" + + if split == "valid": + self.split = "eval" + file_name = "train" + elif split == "train": + self.split = "train" + file_name = "train" + elif split == "test": + self.split = "eval" + file_name = "test" + elif split == "train+valid": + self.split = "train" + file_name = "full-train" + + return name_bin, smth, file_name + + def __getitem__(self, index): + index = self.expand_index_in_trial(index, + trial_ids=self.trial_ids, + trial_borders=self.trial_borders) + return self.neural[index].transpose(2, 1) + + def __len__(self): + return len(self.neural) + + @property + def input_dimension(self): + return self.neural.size(1) + + @property + def continuous_index(self): + if self.split_tag != "test": + return self.index + else: + return None + + @property + def discrete_index(self): + if self.split_tag != "test": + return self.trial_type + else: + return None + + +@parametrize("mc-maze-{size}-{bin_width}", + size=["standard", "small", "medium", "large"], + bin_width=["20", "5"]) +class MCMazeDataset(NLBDataset): + + def __init__(self, + size, + bin_width, + smoothing=50, + split="train", + zscored_index=False): + super().__init__(bin_width=bin_width, split=split) + if size == "standard" or size == "": + name_size = "" + else: + name_size = f"_{size}" + + self.name_size = name_size + name_bin, smth, file_name = self.define_dataset(bin_width=bin_width, + smoothing=smoothing, + split=split) + + dataset_name = f"mc_maze{name_size}_{file_name}{name_bin}{smth}.jl" + data_dict = jl.load(os.path.join(_DEFAULT_DATADIR, dataset_name)) + + self.neural_trial = torch.from_numpy( + data_dict[f"{self.split}_neural_heldin"]).float() + self.neural = self.neural_trial.reshape(-1, self.neural_trial.shape[-1]) + self.trial_len = self.neural_trial.shape[1] + self.num_trials = self.neural_trial.shape[0] + self.trial_ids = np.concatenate( + [[n] * self.trial_len for n in range(self.num_trials)]) + self.trial_borders = [ + self.trial_len * i for i in range(self.num_trials + 1) + ] + self.trial_indices = np.concatenate( + [np.arange(self.trial_len) for n in range(self.num_trials)]) + + if self.split_tag != "test": + self.neural_trial_heldout = torch.from_numpy( + data_dict[f"{self.split}_neural_heldout"]).float() + self.neural_heldout = self.neural_trial_heldout.reshape( + -1, self.neural_trial_heldout.shape[-1]) + self.index_trial = torch.from_numpy( + data_dict[f"{self.split}_behavior"]).float() + self.index = self.index_trial.reshape(-1, + self.index_trial.shape[-1]) + if zscored_index: + self.index = scipy.stats.zscore(self.index) + + self.index = torch.from_numpy(self.index).float() + + def __repr__(self): + return f"MC-Maze{self.name_size}" + + +@parametrize("area2-bump-{bin_width}", bin_width=["20", "5"]) +class AREA2Dataset(NLBDataset): + + def __init__(self, + bin_width, + smoothing=40, + split="train", + zscored_index=False): + super().__init__(bin_width=bin_width, split=split) + name_bin, smth, file_name = self.define_dataset(bin_width=bin_width, + smoothing=smoothing, + split=split) + + dataset_name = f"area2_bump_{file_name}{name_bin}{smth}.jl" + data_dict = jl.load(os.path.join(_DEFAULT_DATADIR, dataset_name)) + + self.neural_trial = torch.from_numpy( + data_dict[f"{self.split}_neural_heldin"]).float() + self.neural = self.neural_trial.reshape(-1, self.neural_trial.shape[-1]) + self.trial_len = self.neural_trial.shape[1] + self.num_trials = self.neural_trial.shape[0] + self.trial_ids = np.concatenate( + [[n] * self.trial_len for n in range(self.num_trials)]) + self.trial_borders = [ + self.trial_len * i for i in range(self.num_trials + 1) + ] + self.trial_indices = np.concatenate( + [np.arange(self.trial_len) for n in range(self.num_trials)]) + self.timepoint_labels = torch.from_numpy( + np.linspace(0, 10, + self.trial_len).reshape(1, -1).repeat(self.num_trials, + axis=0).flatten()) + + if self.split_tag != "test": + self.neural_trial_heldout = torch.from_numpy( + data_dict[f"{self.split}_neural_heldout"]).float() + self.neural_heldout = self.neural_trial_heldout.reshape( + -1, self.neural_trial_heldout.shape[-1]) + self.index_trial = torch.from_numpy( + data_dict[f"{self.split}_behavior"]).float() + self.pos_trial = self.index_trial.cumsum(axis=1) + kmeans = sklearn.cluster.KMeans(9) + X = self.pos_trial[:, -10:].mean(1) + kmeans.fit(X) + trial_labels = kmeans.predict(X) + passive_idx = np.linalg.norm(kmeans.cluster_centers_, + axis=1).argmin() + active_trials = trial_labels != passive_idx + self.trial_type = torch.from_numpy( + active_trials.reshape(1, -1).repeat(self.trial_len, + axis=1).flatten()).long() + self.index = self.index_trial.reshape(-1, + self.index_trial.shape[-1]) + if zscored_index: + self.index = scipy.stats.zscore(self.index) + + self.index = torch.from_numpy(self.index).float() + + def __repr__(self): + return f"Area2-Bump" + + +@parametrize("mc-rtt-{bin_width}", bin_width=["20", "5"]) +class MCRTTDataset(NLBDataset): + + def __init__(self, + bin_width, + smoothing=40, + split="train", + zscored_index=False): + super().__init__(bin_width=bin_width, split=split) + name_bin, smth, file_name = self.define_dataset(bin_width=bin_width, + smoothing=smoothing, + split=split) + + dataset_name = f"mc_rtt_{file_name}{name_bin}{smth}.jl" + data_dict = jl.load(os.path.join(_DEFAULT_DATADIR, dataset_name)) + + self.neural_trial = torch.from_numpy( + data_dict[f"{self.split}_neural_heldin"]).float() + self.neural = self.neural_trial.reshape(-1, self.neural_trial.shape[-1]) + self.trial_len = self.neural_trial.shape[1] + self.num_trials = self.neural_trial.shape[0] + self.trial_ids = np.concatenate( + [[n] * self.trial_len for n in range(self.num_trials)]) + self.trial_borders = [ + self.trial_len * i for i in range(self.num_trials + 1) + ] + self.trial_indices = np.concatenate( + [np.arange(self.trial_len) for n in range(self.num_trials)]) + + if self.split_tag != "test": + self.neural_trial_heldout = torch.from_numpy( + data_dict[f"{self.split}_neural_heldout"]).float() + self.neural_heldout = self.neural_trial_heldout.reshape( + -1, self.neural_trial_heldout.shape[-1]) + self.index_trial = torch.from_numpy( + data_dict[f"{self.split}_behavior"]).float() + self.index = self.index_trial.reshape(-1, + self.index_trial.shape[-1]) + if zscored_index: + self.index = scipy.stats.zscore(self.index) + + self.index = torch.from_numpy(self.index).float() + + self.trial_ids = np.concatenate( + [[n] * self.trial_len for n in range(self.num_trials)]) + self.trial_borders = [ + self.trial_len * i for i in range(self.num_trials + 1) + ] + self.trial_indices = np.concatenate( + [np.arange(self.trial_len) for n in range(self.num_trials)]) + + def __repr__(self): + return f"MC-RTT" diff --git a/cebra/datasets/perich.py b/cebra/datasets/perich.py new file mode 100644 index 00000000..7ab2f5e3 --- /dev/null +++ b/cebra/datasets/perich.py @@ -0,0 +1,133 @@ +import pathlib +from enum import Enum +from typing import Union + +import joblib as jl +import numpy as np +import pandas as pd +from torch_brain.data import Dataset # Migrated from poyo to torch_brain + +import cebra.data +import cebra.io +from cebra.datasets import get_datapath + +_DEFAULT_DATADIR = get_datapath() + + +class Task(Enum): + CO = 0 + RT = 1 + + +class PerichDataset(cebra.data.SingleSessionDataset): + + def __init__(self, + file: Union[pathlib.Path, str], + drop_outliers: bool = True): + super().__init__() + + dataset = self.load_dataset(path=file) + + # Extract recording_id from path for data retrieval + path_obj = pathlib.Path(file) + if path_obj.suffix == '.h5': + recording_id = f"{path_obj.parent.name}/{path_obj.stem}" + else: + raise ValueError("File path must point to an h5 file") + + # Get the full recording data using brain_torch API + # brain_torch.Dataset.get_recording_data() returns full data without slicing + data = dataset.get_recording_data(recording_id) + + self.trial_id = self.get_trial_numbers(data) + trial_mask = (self.trial_id != -1) + + self.subtask_index = data.cursor.subtask_index + if drop_outliers: + subtask_mask = self.subtask_index != 5 + else: + subtask_mask = np.ones_like(self.subtask_index, dtype=bool) + + self.neural, self.index = self.get_neural_and_vel_data(data) + self.neural = self.neural[trial_mask & subtask_mask] + self.index = self.index[trial_mask & subtask_mask] + + self.session = pathlib.Path(data.session).name + self.train_mask = data.cursor.train_mask[trial_mask & subtask_mask] + self.test_mask = data.cursor.test_mask[trial_mask & subtask_mask] + self.valid_mask = data.cursor.valid_mask[trial_mask & subtask_mask] + + self.trial_id = self.trial_id[trial_mask & subtask_mask] + self.subtask_index = self.subtask_index[trial_mask & subtask_mask] + + def __len__(self): + return len(self.neural) + + @property + def input_dimension(self): + return self.neural.size(1) + + def __getitem__(self, index): + """Return [ No.Samples x Neurons x 10 ]""" + index = self.expand_index(index) + return self.neural[index].transpose(2, 1) + + def load_dataset(self, path: str, split: str = "train") -> Dataset: + """Load dataset from processed torch_brain format. + + Args: + path: Path to the h5 file or parent directory + split: Which split to use (used for sampling intervals) + + Returns: + Dataset object containing the recording + """ + # Extract the recording_id from the path + # torch_brain expects: root/brainset/session.h5 + # Format: recording_id = "brainset/session" + + path_obj = pathlib.Path(path) + if path_obj.suffix == '.h5': + # If path is a file, extract parent (brainset) and stem (session) + root = str(path_obj.parent.parent) + recording_id = f"{path_obj.parent.name}/{path_obj.stem}" + else: + # If path is a directory, use it as root + root = str(path_obj) + recording_id = None # Will need to be specified differently + + return Dataset(root=root, + recording_id=recording_id, + split=split, + keep_files_open=True) + + def get_neural_and_vel_data(self, data): + spike_times = data.spikes.timestamps + unit_indices = data.spikes.unit_index + + n_neurons = np.max(data.spikes.unit_index) + 1 + time_bins = data.cursor.timestamps + total_time = len(time_bins) + + psth = np.zeros((n_neurons, total_time)) + for i, spike_time in enumerate(spike_times): + unit_index = unit_indices[i] + time_bin = np.digitize(spike_time, time_bins) - 1 + if 0 <= time_bin < total_time: + psth[unit_index, time_bin] += 1 + + vel = data.cursor.vel + return psth.T, vel + + def get_trial_numbers(self, data): + cursor_timestamps = data.cursor.timestamps + trial_starts = data.trials.start + trial_ends = data.trials.end + + trial_numbers = np.full(cursor_timestamps.shape, -1) + + for trial_num, (start, end) in enumerate(zip(trial_starts, trial_ends)): + in_trial = (cursor_timestamps >= start) & (cursor_timestamps <= end) + trial_numbers[in_trial] = trial_num + + return trial_numbers diff --git a/cebra/datasets/poyo_data.py b/cebra/datasets/poyo_data.py new file mode 100644 index 00000000..249b44fa --- /dev/null +++ b/cebra/datasets/poyo_data.py @@ -0,0 +1,58 @@ +import pathlib +from enum import Enum +from typing import Union + +import joblib as jl +import pandas as pd + +import cebra.data +import cebra.io +from cebra.datasets import get_datapath + +_DEFAULT_DATADIR = get_datapath() + + +class Task(Enum): + CO = 0 + RT = 1 + + +class PoyoDataset(cebra.data.SingleSessionDataset): + + def __init__(self, file: Union[pathlib.Path, str], drop_outliers: bool): + super().__init__() + + data_dict = jl.load(file) + data_df = pd.DataFrame.from_dict(data_dict) + + # e.g. filename: perich_sub-C_ses-CO-20131003_samplNone_smthNone + if "perich" in str(file): + file_list = str(file).split("-") + if file_list[2] in Task.__members__: + data_df["task"] = Task[file_list[2]].value + else: + raise NotImplementedError("Only CO and RT tasks are supported.") + else: + raise NotImplementedError("Only perich dataset is supported.") + + if drop_outliers: + data_df = data_df[data_df[("subtask_index", "subtask_idx")] != 5] + + self.neural = data_df["Spikes"].values + self.index = data_df["hand_vel"].values + self.trial_id = data_df["trial_id"].values + self.subtask_index = data_df[("subtask_index", "subtask_idx")].values + + self.task = data_df["task"].values[0] + + def __len__(self): + return len(self.neural) + + @property + def input_dimension(self): + return self.neural.size(1) + + def __getitem__(self, index): + """Return [ No.Samples x Neurons x 10 ]""" + index = self.expand_index(index) + return self.neural[index].transpose(2, 1) diff --git a/cebra/integrations/sklearn/decoder.py b/cebra/integrations/sklearn/decoder.py index 03b93238..09340f8a 100644 --- a/cebra/integrations/sklearn/decoder.py +++ b/cebra/integrations/sklearn/decoder.py @@ -30,6 +30,10 @@ import sklearn.base import sklearn.neighbors import torch +import torch.nn as nn +import torch.optim as optim +from torch.utils.data import DataLoader +from torch.utils.data import TensorDataset import cebra.helper @@ -248,3 +252,81 @@ def iter_hyperparams() -> Generator[dict, None, None]: """ for alpha in [0.001, 0.01, 0.1, 1, 10, 100]: yield dict(alpha=alpha) + + +class MLPDecoder(Decoder): + """Decoder implementing a simple MLP in PyTorch.""" + + def __init__( + self, + model_type: str = "two_layers", # "single_linear_layer" or "two_layers" + lr: float = 1e-3, + batch_size: int = 500, + num_epochs: int = 20, + device: str = "cuda", + ): + self.model_type = model_type + self.lr = lr + self.batch_size = batch_size + self.num_epochs = num_epochs + self.device = device if torch.cuda.is_available() else "cpu" + + def _build_model(self, input_dim: int, output_dim: int): + if self.model_type == "single_linear_layer": # Single-layer linear model + return nn.Linear(input_dim, output_dim) + elif self.model_type == "two_layers": # Two-layer MLP with GELU non-linearity + return nn.Sequential( + nn.Linear(input_dim, 32), + nn.GELU(), + nn.Linear(32, output_dim), + ) + else: + raise ValueError(f"Unknown hidden type: {self.hidden}") + + def fit( + self, + X: Union[npt.NDArray, torch.Tensor], + y: Union[npt.NDArray, torch.Tensor], + ) -> "MLPDecoder": + if isinstance(X, np.ndarray): + X = torch.from_numpy(X).float() + if isinstance(y, np.ndarray): + y = torch.from_numpy(y).float() + if y.ndim == 1: + y = y[:, None] + + self.input_dim = X.shape[1] + self.output_dim = y.shape[1] + + self.model_ = self._build_model(self.input_dim, + self.output_dim).to(self.device) + optimizer = optim.Adam(self.model_.parameters(), lr=self.lr) + criterion = nn.MSELoss() + + dataset = TensorDataset(X.to(self.device), y.to(self.device)) + loader = DataLoader(dataset, batch_size=self.batch_size, shuffle=True) + + self.model_.train() + for _ in range(self.num_epochs): + for xb, yb in loader: + optimizer.zero_grad() + pred = self.model_(xb) + loss = criterion(pred, yb) + loss.backward() + optimizer.step() + + return self + + def predict(self, X: Union[npt.NDArray, torch.Tensor]) -> npt.NDArray: + if isinstance(X, np.ndarray): + X = torch.from_numpy(X).float() + self.model_.eval() + with torch.no_grad(): + pred = self.model_(X.to(self.device)).cpu().numpy() + return pred + + @staticmethod + def iter_hyperparams() -> Generator[dict, None, None]: + for lr in [1e-2, 1e-3]: + for hidden in ["single", "two"]: + yield dict(lr=lr, hidden=hidden) diff --git a/cebra/solver/base.py b/cebra/solver/base.py index c04c3398..9f86f521 100644 --- a/cebra/solver/base.py +++ b/cebra/solver/base.py @@ -36,8 +36,11 @@ from typing import Callable, Dict, List, Literal, Optional, Tuple, Union import literate_dataclasses as dataclasses +import numpy as np +import packaging.version import torch import torch.nn.functional as F +import wandb from torch.utils.data import DataLoader from torch.utils.data import Dataset @@ -48,6 +51,31 @@ from cebra.solver.util import Meter from cebra.solver.util import ProgressBar +# NOTE(stes): From torch 2.6 onwards, we need to specify the following list +# when loading CEBRA models to allow weights_only = True. +CEBRA_LOAD_SAFE_GLOBALS = [ + cebra.data.Offset, torch.torch_version.TorchVersion, np.dtype, np.float64, + np.int64 +] + + +def _safe_torch_load(filename, weights_only, **kwargs): + if weights_only is None: + if packaging.version.parse( + torch.__version__) >= packaging.version.parse("2.6.0"): + weights_only = True + else: + weights_only = False + + if not weights_only: + checkpoint = torch.load(filename, weights_only=False, **kwargs) + else: + # NOTE(stes): This is only supported for torch 2.6+ + with torch.serialization.safe_globals(CEBRA_LOAD_SAFE_GLOBALS): + checkpoint = torch.load(filename, weights_only=True, **kwargs) + + return checkpoint + def _check_indices(batch_start_idx: int, batch_end_idx: int, offset: cebra.data.Offset, num_samples: int): @@ -314,6 +342,7 @@ class Solver(abc.ABC, cebra.io.HasDevice): "temperature": [] })) tqdm_on: bool = True + scheduler: torch.optim.lr_scheduler = None def __post_init__(self): cebra.io.HasDevice.__init__(self) @@ -356,16 +385,29 @@ def load_state_dict(self, state_dict: dict, strict: bool = True): """ def _contains(key): - if key in state_dict: - return True - elif strict: - raise KeyError( - f"Key {key} missing in state_dict. Contains: {list(state_dict.keys())}." - ) + if isinstance(state_dict, Solver): + if hasattr(state_dict, key): + return True + elif strict: + raise KeyError( + f"Key {key} missing in state_dict. Contains: {list(state_dict.keys())}." + ) + + elif isinstance(state_dict, dict): + if key in state_dict: + return True + elif strict: + raise KeyError( + f"Key {key} missing in state_dict. Contains: {list(state_dict.keys())}." + ) + return False def _get(key): - return state_dict.get(key) + if isinstance(state_dict, Solver): + return getattr(state_dict, key) + elif isinstance(state_dict, dict): + return state_dict.get(key) if _contains("model"): self.model.load_state_dict(_get("model")) @@ -499,7 +541,13 @@ def step(self, batch: cebra.data.Batch) -> dict: loss.backward() self.optimizer.step() + if self.scheduler is not None: + self.scheduler.step() self.history.append(loss.item()) + + if wandb.run is not None: + wandb.log({"loss": loss.item()}) + stats = dict( pos=align.item(), neg=uniform.item(), @@ -728,19 +776,31 @@ def _inference(self, batch: cebra.data.Batch) -> cebra.data.Batch: """ raise NotImplementedError - def load(self, logdir: str, filename: str = "checkpoint.pth"): + def load(self, + logdir: str, + filename: str = "checkpoint.pth", + weights_only: bool = False): """Load the experiment from its checkpoint file. Args: logdir: Logging directory. filename: Checkpoint name for loading the experiment. + weights_only: Indicates whether unpickler should be restricted to loading only tensors, primitive types, + dictionaries and any types added via :py:func:`torch.serialization.add_safe_globals`. + See :py:func:`torch.load` with ``weights_only=True`` for more details. It it recommended to leave this + at the default value of ``None``, which sets the argument to ``False`` for torch<2.6, and ``True`` for + higher versions of torch. If you experience issues with loading custom models (specified outside + of the CEBRA package), you can try to set this to ``False`` if you trust the source of the model. """ savepath = os.path.join(logdir, filename) if not os.path.exists(savepath): print("Did not find a previous experiment. Starting from scratch.") return - checkpoint = torch.load(savepath, map_location=self.device) + + checkpoint = _safe_torch_load(savepath, weights_only) + + #checkpoint = torch.load(savepath, map_location=self.device, weights_only=weights_only) self.load_state_dict(checkpoint, strict=True) n_features = self.n_features From 17e0c6c8ebd66ad1ef2b83893885b81157d90e73 Mon Sep 17 00:00:00 2001 From: atharva <62803658+vovw@users.noreply.github.com> Date: Tue, 16 Sep 2025 02:27:33 +0530 Subject: [PATCH 02/27] Fix matplotlib colormap deprecation warnings for 3.11 compatibility (#269) --- cebra/integrations/matplotlib.py | 2 +- cebra/integrations/plotly.py | 2 +- setup.cfg | 4 +--- tests/test_plotly.py | 2 +- 4 files changed, 4 insertions(+), 6 deletions(-) diff --git a/cebra/integrations/matplotlib.py b/cebra/integrations/matplotlib.py index c2696d4a..844844fd 100644 --- a/cebra/integrations/matplotlib.py +++ b/cebra/integrations/matplotlib.py @@ -1235,7 +1235,7 @@ def compare_models( # check the color of the traces if color is None: - cebra_map = plt.get_cmap(cmap) + cebra_map = matplotlib.colormaps.get_cmap(cmap) colors = matplotlib.colors.ListedColormap( cebra_map.resampled(n_models)(np.arange(n_models))).colors else: diff --git a/cebra/integrations/plotly.py b/cebra/integrations/plotly.py index 2cfc5ec9..af8719fd 100644 --- a/cebra/integrations/plotly.py +++ b/cebra/integrations/plotly.py @@ -87,7 +87,7 @@ def _define_colorscale(self, cmap: str): Returns: colorscale: List of scaled colors to plot the embeddings """ - colorscale = _convert_cmap2colorscale(matplotlib.cm.get_cmap(cmap)) + colorscale = _convert_cmap2colorscale(matplotlib.colormaps.get_cmap(cmap)) return colorscale diff --git a/setup.cfg b/setup.cfg index 7faff998..0bfa5f84 100644 --- a/setup.cfg +++ b/setup.cfg @@ -39,9 +39,7 @@ install_requires = scipy torch>=2.4.0 tqdm - # NOTE(stes): Remove pin once https://github.com/AdaptiveMotorControlLab/CEBRA/issues/240 - # is resolved. - matplotlib<3.11 + matplotlib requests [options.extras_require] diff --git a/tests/test_plotly.py b/tests/test_plotly.py index 187d234c..b1a86b67 100644 --- a/tests/test_plotly.py +++ b/tests/test_plotly.py @@ -31,7 +31,7 @@ @pytest.mark.parametrize("cmap", ["viridis", "plasma", "inferno", "magma"]) def test_colorscale(cmap): - cmap = matplotlib.cm.get_cmap(cmap) + cmap = matplotlib.colormaps.get_cmap(cmap) colorscale = cebra_plotly._convert_cmap2colorscale(cmap) assert isinstance(colorscale, list) From aa00659a49634e1dcf9ac1d4ef33aca754c8cfce Mon Sep 17 00:00:00 2001 From: atharva <62803658+vovw@users.noreply.github.com> Date: Wed, 24 Sep 2025 22:10:29 +0530 Subject: [PATCH 03/27] Remove pkg resources (#272) 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 #271 --- cebra/helper.py | 12 ++++++------ cebra/integrations/sklearn/cebra.py | 4 ++-- tests/test_plot.py | 6 +++--- tests/test_sklearn.py | 6 +++--- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/cebra/helper.py b/cebra/helper.py index 93bae2b1..b956d7f0 100644 --- a/cebra/helper.py +++ b/cebra/helper.py @@ -32,7 +32,7 @@ import numpy as np import numpy.typing as npt -import pkg_resources +import packaging.version import requests import torch @@ -75,8 +75,8 @@ def download_file_from_zip_url(url, *, file): def _is_mps_availabe(torch): available = False - if pkg_resources.parse_version( - torch.__version__) >= pkg_resources.parse_version("1.12"): + if packaging.version.parse( + torch.__version__) >= packaging.version.parse("1.12"): if torch.backends.mps.is_available(): if torch.backends.mps.is_built(): available = True @@ -159,17 +159,17 @@ def requires_package_version(module, version: str): the required ``version``. """ - required_version = pkg_resources.parse_version(version) + required_version = packaging.version.parse(version) def _requires_package_version(function): @wraps(function) def wrapper(*args, patched_version=None, **kwargs): if patched_version is not None: - installed_version = pkg_resources.parse_version( + installed_version = packaging.version.parse( patched_version) # Use the patched version if provided else: - installed_version = pkg_resources.parse_version( + installed_version = packaging.version.parse( module.__version__) if installed_version < required_version: diff --git a/cebra/integrations/sklearn/cebra.py b/cebra/integrations/sklearn/cebra.py index 98e56747..0f056b45 100644 --- a/cebra/integrations/sklearn/cebra.py +++ b/cebra/integrations/sklearn/cebra.py @@ -28,7 +28,7 @@ import numpy as np import numpy.typing as npt import packaging.version -import pkg_resources +import importlib.metadata import sklearn import sklearn.utils.validation as sklearn_utils_validation import torch @@ -1397,7 +1397,7 @@ def save(self, 'numpy_version': np.__version__, 'sklearn_version': - pkg_resources.get_distribution("scikit-learn" + importlib.metadata.distribution("scikit-learn" ).version } }, filename) diff --git a/tests/test_plot.py b/tests/test_plot.py index 1d94d310..2bafa42b 100644 --- a/tests/test_plot.py +++ b/tests/test_plot.py @@ -25,7 +25,7 @@ import matplotlib import matplotlib.pyplot as plt import numpy as np -import pkg_resources +import packaging.version import pytest import torch from sklearn.exceptions import NotFittedError @@ -190,8 +190,8 @@ def test_compare_models_with_different_versions(matplotlib_version): # minimum version of matplotlib minimum_version = "3.6" - if pkg_resources.parse_version( - matplotlib_version) < pkg_resources.parse_version(minimum_version): + if packaging.version.parse( + matplotlib_version) < packaging.version.parse(minimum_version): with pytest.raises(ImportError): cebra_plot.compare_models(models=fitted_models, patched_version=matplotlib_version) diff --git a/tests/test_sklearn.py b/tests/test_sklearn.py index c3d2095c..63bbbab9 100644 --- a/tests/test_sklearn.py +++ b/tests/test_sklearn.py @@ -26,7 +26,7 @@ import _util import _utils_deprecated import numpy as np -import pkg_resources +import packaging.version import pytest import sklearn.utils.estimator_checks import torch @@ -1320,8 +1320,8 @@ def test_check_device(): with pytest.raises(ValueError): cebra_sklearn_utils.check_device(device) - if pkg_resources.parse_version( - torch.__version__) >= pkg_resources.parse_version("1.12"): + if packaging.version.parse( + torch.__version__) >= packaging.version.parse("1.12"): device = "mps" torch.backends.mps.is_available = lambda: True From 994cbbe52250423dcdbcce073cd3315882ac4e8c Mon Sep 17 00:00:00 2001 From: Mackenzie Mathis Date: Wed, 24 Sep 2025 18:40:54 +0200 Subject: [PATCH 04/27] Update README.md (#261) - adding xCEBRA to readme --- README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 5fed1f00..af7f9c08 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,12 @@ To receive updates on code releases, please 👀 watch or ⭐️ star this repos It can jointly use behavioral and neural data in a hypothesis- or discovery-driven manner to produce consistent, high-performance latent spaces. While it is not specific to neural and behavioral data, this is the first domain we used the tool in. This application case is to obtain a consistent representation of latent variables driving activity and behavior, improving decoding accuracy of behavioral variables over standard supervised learning, and obtaining embeddings which are robust to domain shifts. -# Reference +# References + +- 📄 **Publication April 2025**: + [Time-series attribution maps with regularized contrastive learning.](https://arxiv.org/abs/2502.12977) +Steffen Schneider, Rodrigo González Laiz, Anastasiia Filipova, Markus Frey, Mackenzie Weygandt Mathis. AISTATS 2025. + - 📄 **Publication May 2023**: [Learnable latent embeddings for joint behavioural and neural analysis.](https://doi.org/10.1038/s41586-023-06031-6) From 68b3ce7b3b21eb9d8ecead7dcf7bffc9ab9085f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Thu, 1 Oct 2026 16:08:54 +0200 Subject: [PATCH 05/27] Enhance Jacobian computation and multi-objective training support - 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. --- cebra/attribution/_jacobian.py | 86 ++++--- cebra/attribution/attribution_models.py | 157 ++++++++++++- cebra/data/datasets.py | 144 ++++++++++++ cebra/data/multi_session.py | 6 +- cebra/data/multiobjective.py | 110 +++++++++ cebra/distributions/__init__.py | 1 + cebra/distributions/multisession.py | 72 ++++-- cebra/models/jacobian_regularizer.py | 17 +- cebra/solver/base.py | 14 +- cebra/solver/multiobjective.py | 300 ++++++++++++++++++++++++ 10 files changed, 834 insertions(+), 73 deletions(-) diff --git a/cebra/attribution/_jacobian.py b/cebra/attribution/_jacobian.py index 00102aeb..311e61c5 100644 --- a/cebra/attribution/_jacobian.py +++ b/cebra/attribution/_jacobian.py @@ -83,6 +83,7 @@ def compute_jacobian( double_precision: bool = False, convert_to_numpy: bool = True, hybrid_solver: bool = False, + output_batch_size: int | None = None, ) -> Union[torch.Tensor, np.ndarray]: """Compute the Jacobian matrix for a given model and input. @@ -97,42 +98,73 @@ def compute_jacobian( double_precision: If True, use double precision convert_to_numpy: If True, convert output to numpy array hybrid_solver: If True, concatenate multiple outputs along dimension 1 + output_batch_size: Optional number of output/latent dimensions to process + per autograd chunk. If ``None``, process all outputs in one retained + graph as before. Smaller values reduce peak GPU memory without + changing the Jacobian math. Returns: Jacobian matrix as either PyTorch tensor or numpy array """ - if double_precision: - model = model.to("cpu").double() - input_vars = tensors_to_cpu_and_double(input_vars) - if hybrid_solver: - output = model(*input_vars) - output_vars = torch.cat(output, dim=1).to("cpu").double() + if output_batch_size is not None and int(output_batch_size) <= 0: + raise ValueError( + f"output_batch_size must be positive when provided, got {output_batch_size}." + ) + + def _prepare_model_and_inputs(): + if double_precision: + prepared_model = model.to("cpu").double() + prepared_inputs = tensors_to_cpu_and_double(input_vars) else: - output_vars = model(*input_vars).to("cpu").double() - else: - model = model.to(cuda_device).float() - input_vars = tensors_to_cuda(input_vars, cuda_device=cuda_device) + prepared_model = model.to(cuda_device).float() + prepared_inputs = tensors_to_cuda(input_vars, cuda_device=cuda_device) + return prepared_model, prepared_inputs + def _forward_outputs(prepared_model, prepared_inputs): if hybrid_solver: - output = model(*input_vars) - output_vars = torch.cat(output, dim=1) - else: - output_vars = model(*input_vars) + output = prepared_model(*prepared_inputs) + if double_precision: + return torch.cat(output, dim=1).to("cpu").double() + return torch.cat(output, dim=1) + if double_precision: + return prepared_model(*prepared_inputs).to("cpu").double() + return prepared_model(*prepared_inputs) if mode == "autograd": - jacob = [] - for i in range(output_vars.shape[1]): - grads = torch.autograd.grad( - output_vars[:, i:i + 1], - input_vars, - retain_graph=True, - create_graph=False, - grad_outputs=torch.ones(output_vars[:, i:i + 1].shape).to( - output_vars.device), - ) - jacob.append(torch.cat(grads, dim=1)) - - jacobian = torch.stack(jacob, dim=1) + prepared_model, prepared_inputs = _prepare_model_and_inputs() + output_vars = _forward_outputs(prepared_model, prepared_inputs) + n_outputs = int(output_vars.shape[1]) + effective_output_batch_size = ( + n_outputs if output_batch_size is None else min(int(output_batch_size), n_outputs) + ) + + jacob_chunks = [] + for output_start in range(0, n_outputs, effective_output_batch_size): + output_end = min(output_start + effective_output_batch_size, n_outputs) + if output_start > 0: + output_vars = _forward_outputs(prepared_model, prepared_inputs) + + chunk_rows = [] + for local_idx, output_idx in enumerate(range(output_start, output_end)): + is_last_in_chunk = local_idx == (output_end - output_start - 1) + grads = torch.autograd.grad( + output_vars[:, output_idx : output_idx + 1], + prepared_inputs, + retain_graph=not is_last_in_chunk, + create_graph=False, + grad_outputs=torch.ones( + output_vars[:, output_idx : output_idx + 1].shape, + device=output_vars.device, + ), + ) + chunk_rows.append(torch.cat(grads, dim=1).detach().cpu()) + del grads + + jacob_chunks.append(torch.stack(chunk_rows, dim=1)) + del chunk_rows + del output_vars + + jacobian = torch.cat(jacob_chunks, dim=1) jacobian = jacobian.detach().cpu() diff --git a/cebra/attribution/attribution_models.py b/cebra/attribution/attribution_models.py index ddbc7a37..8d06d001 100644 --- a/cebra/attribution/attribution_models.py +++ b/cebra/attribution/attribution_models.py @@ -39,6 +39,33 @@ from cebra.attribution import register +_VALID_ATTRIBUTION_RESULT_KEYS = { + "jf", + "jf-convabs", + "jf-inv-lsq", + "jf-inv-svd", + "jf-convabs-inv-lsq", + "jf-convabs-inv-svd", +} + + +def _normalize_selected_result_keys(selected_keys): + if selected_keys is None: + return None + normalized = [] + for key in selected_keys: + key_str = str(key).strip().replace("_", "-") + if not key_str: + continue + if key_str not in _VALID_ATTRIBUTION_RESULT_KEYS: + raise ValueError( + f"Unknown attribution result key {key!r}. " + f"Valid keys: {sorted(_VALID_ATTRIBUTION_RESULT_KEYS)}" + ) + normalized.append(key_str) + return set(normalized) + + @dataclasses.dataclass class AttributionMap: """Base class for computing attribution maps for CEBRA models. @@ -324,7 +351,7 @@ def _reduce(full_jacobian): class JFMethodBased(AttributionMap): """Compute the attribution map using the Jacobian of the model encoder.""" - def _compute_jacobian(self, input_data): + def _compute_jacobian(self, input_data, output_batch_size=None): return cebra.attribution._jacobian.compute_jacobian( self.model, input_vars=[input_data], @@ -333,9 +360,11 @@ def _compute_jacobian(self, input_data): double_precision=False, convert_to_numpy=True, hybrid_solver=False, + output_batch_size=output_batch_size, ) - def compute_attribution_map(self): + def compute_attribution_map(self, selected_keys=None): + selected_keys = _normalize_selected_result_keys(selected_keys) full_jacobian = self._compute_jacobian(self.input_data) @@ -343,12 +372,16 @@ def compute_attribution_map(self): for key, value in self._reduce_attribution_map({ 'jf': full_jacobian }).items(): - result[key] = value + if selected_keys is None or key in selected_keys: + result[key] = value for method in ['lsq', 'svd']: + inv_key = f"{key}-inv-{method}" + if selected_keys is not None and inv_key not in selected_keys: + continue print(f"Computing inverse for {key} with method {method}") - result[f"{key}-inv-{method}"], result[ - f'time_inversion_{method}'] = self._inverse(value, - method=method) + result[inv_key], result[f'time_inversion_{method}'] = self._inverse( + value, method=method + ) # result[f"{key}-inv-{method}-conditions"] = self.check_moores_penrose_conditions(value, result[f"{key}-inv-{method}"]) return result @@ -363,7 +396,8 @@ class JFMethodBasedBatched(JFMethodBased): :py:class:`JFMethodBased` """ - def compute_attribution_map(self, batch_size=1024): + def compute_attribution_map(self, batch_size=1024, selected_keys=None): + selected_keys = _normalize_selected_result_keys(selected_keys) if batch_size > self.input_data.shape[0]: raise ValueError( f"Batch size ({batch_size}) is bigger than data ({self.input_data.shape[0]})" @@ -380,12 +414,113 @@ def compute_attribution_map(self, batch_size=1024): for key, value in self._reduce_attribution_map({ 'jf': full_jacobian }).items(): - result[key] = value + if selected_keys is None or key in selected_keys: + result[key] = value for method in ['lsq', 'svd']: + inv_key = f"{key}-inv-{method}" + if selected_keys is not None and inv_key not in selected_keys: + continue + result[inv_key], result[f'time_inversion_{method}'] = self._inverse( + value, method=method + ) - result[f"{key}-inv-{method}"], result[ - f'time_inversion_{method}'] = self._inverse(value, - method=method) + return result + + +@dataclasses.dataclass +@register("jacobian-based-batched-optimized") +class JFMethodBasedBatchedOptimized(JFMethodBased): + """Optimized Jacobian-based attribution using streaming mini-batches. + + This class keeps the original ``jacobian-based-batched`` behavior untouched. + + Args: + batch_size: Number of samples per Jacobian mini-batch. + return_full: If True, returns per-sample maps (same shape contract as the + original class). If False, returns sample-averaged maps to reduce memory. + """ + + def compute_attribution_map( + self, + batch_size=1024, + return_full=True, + selected_keys=None, + latent_batch_size=None, + ): + selected_keys = _normalize_selected_result_keys(selected_keys) + if batch_size > self.input_data.shape[0]: + raise ValueError( + f"Batch size ({batch_size}) is bigger than data ({self.input_data.shape[0]})" + ) + + input_data_batches = torch.split(self.input_data, batch_size) + keys = sorted(_VALID_ATTRIBUTION_RESULT_KEYS if selected_keys is None else selected_keys) + + if return_full: + per_key_chunks = {key: [] for key in keys} + running_sums = None + total_samples = None + else: + per_key_chunks = None + running_sums = {key: None for key in keys} + total_samples = 0 + + time_inversion = {'lsq': 0.0, 'svd': 0.0} + + for input_data_batch in input_data_batches: + jacobian_batch = self._compute_jacobian( + input_data_batch, output_batch_size=latent_batch_size + ) + reduced_batch = self._reduce_attribution_map({'jf': jacobian_batch}) + batch_samples = next(iter(reduced_batch.values())).shape[0] + + for key, value in reduced_batch.items(): + if selected_keys is None or key in selected_keys: + if return_full: + per_key_chunks[key].append(value) + else: + if running_sums[key] is None: + running_sums[key] = value.sum(axis=0) + else: + running_sums[key] += value.sum(axis=0) + + for method in ['lsq', 'svd']: + inv_key = f"{key}-inv-{method}" + if selected_keys is not None and inv_key not in selected_keys: + continue + inv_value, dt = self._inverse(value, method=method) + if return_full: + per_key_chunks[inv_key].append(inv_value) + else: + if running_sums[inv_key] is None: + running_sums[inv_key] = inv_value.sum(axis=0) + else: + running_sums[inv_key] += inv_value.sum(axis=0) + + time_inversion[method] += dt + + if not return_full: + total_samples += batch_samples + + del jacobian_batch + del reduced_batch + + if return_full: + result = { + key: np.concatenate(chunks, axis=0) + for key, chunks in per_key_chunks.items() + } + else: + if total_samples == 0: + raise ValueError("No samples available for attribution aggregation.") + result = { + key: value / float(total_samples) + for key, value in running_sums.items() + } + result['num_samples'] = int(total_samples) + + result['time_inversion_lsq'] = time_inversion['lsq'] + result['time_inversion_svd'] = time_inversion['svd'] return result diff --git a/cebra/data/datasets.py b/cebra/data/datasets.py index 689452cf..e999d397 100644 --- a/cebra/data/datasets.py +++ b/cebra/data/datasets.py @@ -141,6 +141,21 @@ def discrete_index(self): def __len__(self): return len(self.neural) + def to(self, device: str) -> "TensorDataset": + """Move dataset to the specified device. + + Args: + device: Target device + + Returns: + Self for chaining + """ + super().to(device) + self.neural = self.neural.to(device) + self.continuous = self.continuous.to(device) if self.continuous is not None else None + self.discrete = self.discrete.to(device) if self.discrete is not None else None + return self + def __getitem__(self, index): index = self.expand_index(index) return self.neural[index].transpose(2, 1) @@ -341,6 +356,13 @@ def _apply(self, func): def _iter_property(self, attr): return (getattr(data, attr) for data in self.iter_sessions()) + def to(self, device: str) -> "DatasetCollection": + """Move the collection and all contained sessions to the given device.""" + super().to(device) + for session in self.iter_sessions(): + session.to(device) + return self + # TODO(stes): This should be a single session dataset? class DatasetxCEBRA(cebra_io.HasDevice, cebra_data_masking.MaskedMixin): @@ -566,3 +588,125 @@ def __getitem__(self, args) -> List[Batch]: session_id, index = args return self.get_session(session_id).__getitem__(index) + + +class UnifiedxCEBRADataset(UnifiedDataset): + """Multi-session unified dataset with per-objective labels for multiobjective learning. + + Extends UnifiedDataset to support flexible, per-objective label selection and + concatenation across sessions. Designed to work with UnifiedContrastiveMultiObjectiveLoader. + + Example: + >>> import cebra.data + >>> import torch + >>> session1 = torch.randn((100, 30)) + >>> session2 = torch.randn((100, 50)) + >>> index1 = torch.randn((100, 4)) + >>> index2 = torch.randn((100, 4)) + >>> label1_obj1 = torch.randn((100,)) + >>> label1_obj2 = torch.randn((100,)) + >>> label2_obj1 = torch.randn((100,)) + >>> label2_obj2 = torch.randn((100,)) + >>> + >>> dataset1 = cebra.data.TensorDataset(session1, continuous=index1) + >>> dataset2 = cebra.data.TensorDataset(session2, continuous=index2) + >>> + >>> # Create unified dataset with per-session labels + >>> unified_dataset = cebra.data.UnifiedxCEBRADataset(dataset1, dataset2) + >>> # Add per-objective labels (stored per session) + >>> unified_dataset.add_labels("objective_1", [label1_obj1, label2_obj1]) + >>> unified_dataset.add_labels("objective_2", [label1_obj2, label2_obj2]) + """ + + def __init__(self, *datasets: cebra_data.SingleSessionDataset): + super().__init__(*datasets) + self.labels = {} + + def add_labels(self, label_name: str, label_list: List[torch.Tensor]): + """Add a set of per-objective labels, one per session. + + Args: + label_name: Name of the label/objective (e.g., "position", "velocity") + label_list: List of label tensors, one per session, each of shape (session_length,) + or (session_length, num_dims) + """ + if len(label_list) != self.num_sessions: + raise ValueError( + f"Expected {self.num_sessions} label tensors (one per session), " + f"got {len(label_list)}" + ) + + # Concatenate per-session labels into a single unified tensor + concatenated_labels = torch.cat([ + self._to_tensor(label) for label in label_list + ], dim=0) + + self.labels[label_name] = concatenated_labels + + @staticmethod + def _to_tensor(data: Union[torch.Tensor, np.ndarray]) -> torch.Tensor: + """Convert array to tensor if necessary.""" + if isinstance(data, np.ndarray): + return torch.from_numpy(data) + return data + + def load_batch_contrastive(self, index: BatchIndex) -> Batch: + """Load a batch for contrastive learning with per-objective positives. + + Returns a single Batch with shared ref/neg and a list of positives (one per objective). + + Args: + index: BatchIndex with: + - reference: (num_sessions, num_samples) tensor (shared across objectives) + - negative: (num_sessions, num_samples) tensor (shared across objectives) + - positive: list of (num_sessions, num_samples) tensors, one per objective + + Returns: + Batch with: + - reference: concatenated across sessions + - negative: concatenated across sessions + - positive: list of tensors, each concatenated across sessions per objective + """ + # Get reference and negative once (shared across objectives) + temp_index = BatchIndex( + reference=index.reference, + negative=index.negative, + positive=index.positive[0], # Use first objective for structure + ) + batches = self._get_batches(temp_index) + + if hasattr(self, "apply_mask"): + reference = self.apply_mask( + torch.cat([batch.reference for batch in batches], dim=1) + ) + negative = self.apply_mask( + torch.cat([batch.negative for batch in batches], dim=1) + ) + else: + reference = torch.cat([batch.reference for batch in batches], dim=1) + negative = torch.cat([batch.negative for batch in batches], dim=1) + + # Get positives per objective + positive_per_obj = [] + for obj_idx_tensor in index.positive: + temp_index = BatchIndex( + reference=index.reference, + negative=index.negative, + positive=obj_idx_tensor, + ) + batches = self._get_batches(temp_index) + + if hasattr(self, "apply_mask"): + pos = self.apply_mask( + torch.cat([batch.positive for batch in batches], dim=1) + ) + else: + pos = torch.cat([batch.positive for batch in batches], dim=1) + + positive_per_obj.append(pos) + + return cebra_data.Batch( + reference=reference, + negative=negative, + positive=positive_per_obj, + ) diff --git a/cebra/data/multi_session.py b/cebra/data/multi_session.py index bf5cc2a1..88a66fad 100644 --- a/cebra/data/multi_session.py +++ b/cebra/data/multi_session.py @@ -163,9 +163,9 @@ def get_indices(self, neg_idx = self.sampler.sample_prior(self.batch_size) pos_idx, idx, idx_rev = self.sampler.sample_conditional(ref_idx) - ref_idx = torch.from_numpy(ref_idx) - neg_idx = torch.from_numpy(neg_idx) - pos_idx = torch.from_numpy(pos_idx) + ref_idx = torch.from_numpy(ref_idx).to(self.device) + neg_idx = torch.from_numpy(neg_idx).to(self.device) + pos_idx = torch.from_numpy(pos_idx).to(self.device) return BatchIndex( reference=ref_idx, diff --git a/cebra/data/multiobjective.py b/cebra/data/multiobjective.py index dbbb9b86..e2c6c54f 100644 --- a/cebra/data/multiobjective.py +++ b/cebra/data/multiobjective.py @@ -21,6 +21,8 @@ # import literate_dataclasses as dataclasses +import numpy as np +import torch import cebra.data as cebra_data import cebra.distributions @@ -135,6 +137,12 @@ def add_config(self, config): kwargs_distribution['label_name']], delta=kwargs_distribution['delta'], device=self.device) + elif config["distribution"] == "unified_time_delta": + distribution = cebra.distributions.UnifiedSampler( + self.dataset, + kwargs_distribution['time_delta'], + device=self.device, + ) else: raise NotImplementedError( f"Distribution {config['distribution']} is not implemented yet." @@ -171,3 +179,105 @@ def __iter__(self): for _ in range(len(self)): index = self.get_indices(num_samples=self.batch_size) yield self.dataset.load_batch_contrastive(index) + + +@dataclasses.dataclass +class UnifiedContrastiveMultiObjectiveLoader(cebra_data.Loader): + """Unified Contrastive Multiobjective data Loader for multi-session training. + + Uses a single shared model across sessions with per-objective time_delta distributions. + Reference and negative samples are shared across all objectives and sampled uniformly + across sessions via UnifiedSampler. Positive samples are drawn per-objective using + time_delta sampling with random shifts. + + Yields batches of the specified size from the given UnifiedDataset. + """ + + sampling_mode_contrastive: str = dataclasses.field( + default="refneg_shared", + doc="""Type of sampling performed, re whether reference and negative samples + are shared. Only 'refneg_shared' is supported for unified multiobjective.""" + ) + + def __post_init__(self): + super().__post_init__() + self.distributions = [] + + def add_config(self, config): + """Add a per-objective configuration with time_delta distribution. + + Only time_delta distributions are supported for unified continuous multiobjective. + Uses the primary continuous index from the unified dataset. + + Args: + config: A dict with keys 'distribution' and 'kwargs'. + - 'distribution': must be "time_delta" + - 'kwargs': dict with 'time_delta' (int, the time window). + 'label_name' is ignored; primary continuous index is used. + """ + kwargs_distribution = config['kwargs'] + + if config['distribution'] != "unified_time_delta": + raise NotImplementedError( + f"Only 'unified_time_delta' distribution is supported for unified multiobjective, " + f"got '{config['distribution']}'." + ) + + if not hasattr(self.dataset, 'continuous_index'): + raise ValueError( + "UnifiedDataset must have 'continuous_index' attribute." + ) + + #TODO: adapt to more labels! + distribution = cebra.distributions.UnifiedSampler( + self.dataset, + self.time_offset, + device=self.device, + ) + self.distributions.append(distribution) + + def get_indices(self, num_samples: int): + """Sample and return the specified number of indices for unified multiobjective. + + Reference and negative indices are shared across all objectives and sampled + uniformly across sessions. Positive indices are drawn per-objective using + time_delta distributions with random shifts. + + Args: + num_samples: Batch size (number of samples per objective). + + Returns: + A BatchIndex with: + - reference: shape (num_sessions, num_samples) tensor shared across objectives + - positive: list of per-objective positive indices, each (num_sessions, num_samples) tensor + - negative: shape (num_sessions, num_samples) tensor shared across objectives + """ + if self.sampling_mode_contrastive != "refneg_shared": + raise ValueError( + f"Sampling mode {self.sampling_mode_contrastive} is not implemented yet." + ) + + # Sample shared reference and negative using the first distribution + # These come back as numpy arrays from UnifiedSampler + ref_idx_np = self.distributions[0].sample_prior(self.batch_size) + neg_idx_np = self.distributions[0].sample_prior(self.batch_size) + ref_idx = torch.from_numpy(ref_idx_np).to(self.device) + neg_idx = torch.from_numpy(neg_idx_np).to(self.device) + + # Sample per-objective positives + positives_idx = [] + for distribution in self.distributions: + pos_idx_np = distribution.sample_conditional(ref_idx_np) + pos_idx = torch.from_numpy(pos_idx_np).to(self.device) + positives_idx.append(pos_idx) + + return BatchIndex( + reference=ref_idx, + positive=positives_idx, + negative=neg_idx, + ) + + def __iter__(self): + for _ in range(len(self)): + index = self.get_indices(num_samples=self.batch_size) + yield self.dataset.load_batch_contrastive(index) diff --git a/cebra/distributions/__init__.py b/cebra/distributions/__init__.py index 6985adbc..e92161fe 100644 --- a/cebra/distributions/__init__.py +++ b/cebra/distributions/__init__.py @@ -64,4 +64,5 @@ "DeltaNormalDistribution", "MultivariateDiscrete", "MultisessionSampler", + "UnifiedSampler" ] diff --git a/cebra/distributions/multisession.py b/cebra/distributions/multisession.py index 9fe303a6..47b25ba0 100644 --- a/cebra/distributions/multisession.py +++ b/cebra/distributions/multisession.py @@ -31,7 +31,28 @@ import cebra.distributions as cebra_distr import cebra.io -_device = cebra.io.device() + +def _resolve_device(dataset, device: Optional[str] = None) -> str: + def _normalize_cuda_device(device_name: str) -> str: + if device_name != "cuda": + return device_name + + # Prefer the concrete device index from dataset tensors if available. + if hasattr(dataset, "continuous_index"): + idx_device = dataset.continuous_index.device + if idx_device.type == "cuda" and idx_device.index is not None: + return f"cuda:{idx_device.index}" + + # Fall back to currently selected CUDA device instead of implicit cuda:0. + if torch.cuda.is_available(): + return f"cuda:{torch.cuda.current_device()}" + return device_name + + if device is not None: + return _normalize_cuda_device(str(device)) + if hasattr(dataset, "device"): + return _normalize_cuda_device(str(dataset.device)) + return _normalize_cuda_device(cebra.io.device()) def _search(data, query): @@ -145,8 +166,9 @@ class MultisessionSampler(cebra_distr.PriorDistribution, * Add better CUDA support and refactor ``numpy`` implementation. """ - def __init__(self, dataset, time_offset): + def __init__(self, dataset, time_offset, device: Optional[str] = None): self.dataset = dataset + self.device = _resolve_device(dataset, device) # TODO(stes): implement in pytorch self.all_data = self.dataset.continuous_index.cpu().numpy() @@ -158,18 +180,21 @@ def __init__(self, dataset, time_offset): # TODO(stes): unify naming time_delta = time_offset - self.time_difference = (torch.cat( - [ - dataset.continuous_index[time_delta:] - - dataset.continuous_index[:-time_delta] - for dataset in self.dataset.iter_sessions() - ], - dim=0, - ).cpu().numpy()) + + # NOTE(celia): Keep this on CPU: a previous CUDA torch.cat here could OOM due to + # large temporary allocations when concatenating across many sessions. + time_differences = [] + for dataset in self.dataset.iter_sessions(): + continuous_index = dataset.continuous_index + if continuous_index.device.type != "cpu": + continuous_index = continuous_index.cpu() + time_differences.append((continuous_index[time_delta:] - + continuous_index[:-time_delta]).numpy()) + self.time_difference = np.concatenate(time_differences, axis=0) self.index = [ cebra_distr.ContinuousIndex( - dataset.continuous_index.float().to(_device)) + dataset.continuous_index.float().to(self.device)) for dataset in self.dataset.iter_sessions() ] @@ -247,9 +272,9 @@ def sample_conditional(self, idx: torch.Tensor) -> torch.Tensor: # TODO this part fails in Pytorch query = query[idx.reshape(s)] - query = torch.from_numpy(query).to(_device) + query = torch.from_numpy(query).to(self.device) - pos_idx = torch.zeros(shape, device=_device).long() + pos_idx = torch.zeros(shape, device=self.device).long() for i in range(self.num_sessions): pos_idx[i] = self.index[i].search(query[i]) pos_idx = pos_idx.cpu().numpy() @@ -281,8 +306,9 @@ class DiscreteMultisessionSampler(cebra_distr.PriorDistribution, * Add better CUDA support and refactor ``numpy`` implementation. """ - def __init__(self, dataset): + def __init__(self, dataset, device: Optional[str] = None): self.dataset = dataset + self.device = _resolve_device(dataset, device) # TODO(stes): implement in pytorch self.all_data = self.dataset.discrete_index.cpu().numpy() @@ -294,7 +320,7 @@ def __init__(self, dataset): self.index = [ cebra_distr.DiscreteUniform( - dataset.discrete_index.int().to(_device)) + dataset.discrete_index.int().to(self.device)) for dataset in self.dataset.iter_sessions() ] @@ -370,10 +396,10 @@ def sample_conditional(self, idx: torch.Tensor) -> torch.Tensor: # TODO this part fails in Pytorch # apply shuffle query = query[idx.reshape(s)] - query = torch.from_numpy(query).to(_device) + query = torch.from_numpy(query).to(self.device) # sample conditional for each assigned session - pos_idx = torch.zeros(shape, device=_device).long() + pos_idx = torch.zeros(shape, device=self.device).long() for i in range(self.num_sessions): pos_idx[i] = self.index[i].sample_conditional(query[i]) pos_idx = pos_idx.cpu().numpy() @@ -496,6 +522,10 @@ def _get_query(self, aligned: If True, no time difference is added to the query. Otherwise, a random time difference is added to the query. """ + + # self.all_data is numpy-backed, so ensure indices are on host before indexing. + if torch.is_tensor(reference_idx): + reference_idx = reference_idx.detach().cpu().numpy() cum_idx = reference_idx + self.lengths[session_id] if aligned: query = self.all_data[cum_idx] @@ -503,7 +533,7 @@ def _get_query(self, diff_idx = torch.randint(len(self.time_difference), (len(reference_idx),)) query = self.all_data[cum_idx] + self.time_difference[diff_idx] - return torch.from_numpy(query).to(_device) + return torch.from_numpy(query).to(self.device) def sample_all_sessions(self, ref_idx: torch.Tensor, session_id: int) -> torch.Tensor: @@ -535,7 +565,7 @@ def sample_all_sessions(self, ref_idx: torch.Tensor, # cum_ref_idx: (num_samples, ), values of ref_idx, switched to correspond to the indexes in # of session_id, in the flatten array self.all_data. all_idx = torch.zeros(self.num_sessions, len(ref_idx), - device=_device).long() + device=self.device).long() query = self._get_query( reference_idx=ref_idx, session_id=session_id, aligned=True) # same query for all + no time diff added @@ -578,8 +608,8 @@ def sample_conditional(self, reference_idx: npt.NDArray) -> torch.Tensor: """ cond_idx = torch.zeros((reference_idx.shape[0], reference_idx.shape[1]), - dtype=torch.int, - device=_device).long() + dtype=torch.int, + device=self.device).long() for session_id in range(self.num_sessions): query = self._get_query(reference_idx=reference_idx[session_id], diff --git a/cebra/models/jacobian_regularizer.py b/cebra/models/jacobian_regularizer.py index a909a31b..c541993f 100644 --- a/cebra/models/jacobian_regularizer.py +++ b/cebra/models/jacobian_regularizer.py @@ -86,19 +86,17 @@ def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: for ii in range(num_proj): if self.n == -1: # orthonormal vector, sequentially spanned - v = torch.zeros(B, C) + v = torch.zeros(B, C, device=x.device) v[:, ii] = 1 else: # random properly-normalized vector for each sample - v = self._random_vector(C=C, B=B) - if x.is_cuda: - v = v.cuda() + v = self._random_vector(C=C, B=B, device=x.device) Jv = self._jacobian_vector_product(y, x, v, create_graph=True) J2 += C * torch.norm(Jv)**2 / (num_proj * B) R = (1 / 2) * J2 return R - def _random_vector(self, C: int, B: int) -> torch.Tensor: + def _random_vector(self, C: int, B: int, device: torch.device = None) -> torch.Tensor: """Creates a random vector of dimension C with a norm of C^(1/2). This is needed for the projection formula to work. @@ -106,16 +104,17 @@ def _random_vector(self, C: int, B: int) -> torch.Tensor: Args: C: Output dimension B: Batch size + device: Device to create the tensor on Returns: A random normalized vector """ if C == 1: - return torch.ones(B) - v = torch.randn(B, C) - arxilirary_zero = torch.zeros(B, C) + return torch.ones(B, device=device) + v = torch.randn(B, C, device=device) + arxilirary_zero = torch.zeros(B, C, device=device) vnorm = torch.norm(v, 2, 1, True) - v = torch.addcdiv(arxilirary_zero, 1.0, v, vnorm) + v = torch.addcdiv(arxilirary_zero, v, vnorm, value=1.0) return v def _jacobian_vector_product(self, diff --git a/cebra/solver/base.py b/cebra/solver/base.py index 7a125c2a..0e6d2c2b 100644 --- a/cebra/solver/base.py +++ b/cebra/solver/base.py @@ -779,7 +779,8 @@ def _inference(self, batch: cebra.data.Batch) -> cebra.data.Batch: def load(self, logdir: str, filename: str = "checkpoint.pth", - weights_only: bool = False): + weights_only: bool = False, + map_location=None): """Load the experiment from its checkpoint file. Args: @@ -791,6 +792,8 @@ def load(self, at the default value of ``None``, which sets the argument to ``False`` for torch<2.6, and ``True`` for higher versions of torch. If you experience issues with loading custom models (specified outside of the CEBRA package), you can try to set this to ``False`` if you trust the source of the model. + map_location: Optional location passed to :py:func:`torch.load`. + If not provided, checkpoints are remapped to the current model device. """ savepath = os.path.join(logdir, filename) @@ -798,7 +801,14 @@ def load(self, print("Did not find a previous experiment. Starting from scratch.") return - checkpoint = _safe_torch_load(savepath, weights_only) + if map_location is None: + map_location = next(self.model.parameters()).device + + checkpoint = _safe_torch_load( + savepath, + weights_only, + map_location=map_location, + ) #checkpoint = torch.load(savepath, map_location=self.device, weights_only=weights_only) self.load_state_dict(checkpoint, strict=True) diff --git a/cebra/solver/multiobjective.py b/cebra/solver/multiobjective.py index 98587bd7..ca521b26 100644 --- a/cebra/solver/multiobjective.py +++ b/cebra/solver/multiobjective.py @@ -43,6 +43,7 @@ import logging import time import warnings +from contextlib import nullcontext from typing import Callable, Dict, List, Optional, Tuple import literate_dataclasses as dataclasses @@ -506,3 +507,302 @@ def _inference(self, batch: cebra.data.Batch) -> cebra.data.Batch: cebra.data.Batch(pred_refs[i], pred_pos[i], pred_negs[i])) return prediction_batches + + +@register("unified-multiobjective-solver") +@dataclasses.dataclass +class UnifiedMultiobjectiveSolverxCEBRA(MultiobjectiveSolverBase): + """Unified multi-objective solver for CEBRA. + + This solver is used for training CEBRA models with multiple objectives across + multiple sessions using a single shared model. Designed to work with + :py:class:`cebra.data.multiobjective.UnifiedContrastiveMultiObjectiveLoader`. + + Unlike the standard multiobjective solver which handles per-session models, + this solver applies a single model to unified batches where reference, positive, + and negative samples are already aligned across sessions. + + See Also: + :py:class:`cebra.data.multiobjective.UnifiedContrastiveMultiObjectiveLoader` + :py:class:`cebra.solver.multiobjective.MultiObjectiveConfig` + :py:class:`cebra.models.multicriterions.MultiCriterions` + """ + + _variant_name = "unified-multiobjective-solver" + + def _set_fitted_params(self, loader: cebra.data.Loader): + """Set parameters once the solver is fitted for unified multiobjective training. + + For unified training, num_sessions is the number of sessions in the unified dataset, + and n_features is the total concatenated feature dimension across all sessions. + + Args: + loader: Loader used to fit the solver. + """ + self.num_sessions = loader.dataset.num_sessions + self.n_features = loader.dataset.input_dimension + + def _check_is_inputs_valid( + self, + inputs: Optional[List[torch.Tensor]], + session_id: Optional[int] = None + ): + """Check that the inputs can be inferred using the unified model. + + For unified training, inputs should be a list of per-session tensors, + and the concatenated feature dimension must match the model's input dimension. + + Args: + inputs: List of input tensors, one per session. Each has shape + (n_samples, num_features_session, ...). + session_id: The target session ID (required for unified models). + """ + if inputs is None: + return + + if isinstance(inputs, list): + inputs_shape = 0 + for i in range(len(inputs)): + inputs_shape += inputs[i].shape[1] + elif isinstance(inputs, torch.Tensor): + raise NotImplementedError( + "Unified models require a list of per-session tensors, not a single tensor." + ) + else: + raise NotImplementedError( + f"Invalid input type: {type(inputs)}. Expected list of tensors." + ) + + if self.n_features != inputs_shape: + raise ValueError( + f"Invalid input shape: model requires an input of shape " + f"(n_samples, {self.n_features}), but got total feature dimension " + f"(n_samples, {inputs_shape}) from concatenated sessions." + ) + + def _check_is_session_id_valid( + self, + session_id: Optional[int] = None, + ): + """Check that the session ID provided is valid for the unified solver. + + The session ID must be non-null and between 0 and the number of sessions. + + Args: + session_id: The session ID to check. + """ + if session_id is None: + raise RuntimeError( + "No session_id provided: unified multiobjective model requires a session_id " + "as the target session to use to align the sessions." + ) + if session_id >= self.num_sessions or session_id < 0: + raise RuntimeError( + f"Invalid session_id {session_id}: session_id for the current unified model " + f"must be between 0 and {self.num_sessions-1}." + ) + + def _get_model(self, session_id: Optional[int] = None): + """Get the unified model (independent of session_id). + + For unified models, there is only one shared model regardless of session. + The session_id is still validated but not used for model selection. + + Args: + session_id: The session ID, required for validation. + + Returns: + The shared unified model. + """ + self._check_is_session_id_valid(session_id=session_id) + self._check_is_fitted() + return self.model + + def _inference(self, batch: cebra.data.Batch) -> cebra.data.Batch: + """Compute predictions for unified multiobjective batch. + + For unified batches, reference, positive, and negative samples are already + aligned across sessions (concatenated along the neuron dimension). We apply + the single model to each and return per-objective prediction batches. + + Args: + batch: A Batch with reference, positive (list), and negative tensors + already unified across sessions. + + Returns: + A list of Batch objects, one per objective, with model predictions. + """ + pred_refs = self.model(batch.reference) + pred_negs = self.model(batch.negative) + + prediction_batches = [] + for i, positive in enumerate(batch.positive): + pred_pos = self.model(positive) + prediction_batches.append( + cebra.data.Batch( + reference=pred_refs[i].unsqueeze(0).view(-1, pred_refs[i].shape[-1]), + positive=pred_pos[i].unsqueeze(0).view(-1, pred_pos[i].shape[-1]), + negative=pred_negs[i].unsqueeze(0).view(-1, pred_negs[i].shape[-1]) + )) + + return prediction_batches + + + @torch.no_grad() + def transform(self, + inputs: List[torch.Tensor], + labels: List[torch.Tensor], + pad_before_transform: bool = True, + session_id: Optional[int] = None, + batch_size: Optional[int] = 512, + split_outputs: bool = False) -> torch.Tensor: + """Compute the embedding for the `session_id`th session of the dataset. + + For unified multiobjective training, the embedding is computed using the shared + unified model, similar to UnifiedSolver. All sessions must be provided as they + are used for sampling context across sessions. + + Args: + inputs: The input signal for all sessions (list of tensors). + labels: The auxiliary variables to use for sampling (list of tensors). + pad_before_transform: Whether to pad the input before computing embeddings. + session_id: The session ID for which to compute embeddings. Required for + multi-session models. + batch_size: Batch size for computing embeddings (default 512). + split_outputs: Whether to return per-objective outputs (True) or concatenated + output (False, default). If True, returns a tuple of embeddings + one per objective. + + Returns: + If split_outputs=False: The output embedding for the session corresponding to + the provided ID `session_id`, with shape (num_samples(session_id), output_dimension). + If split_outputs=True: A tuple of embeddings, one per objective, with shapes + (num_samples(session_id), output_dimension_objective_i). + """ + if not isinstance(inputs, list): + raise ValueError( + f"Inputs to transform() should be a list, not {type(inputs)}.") + + self._check_is_fitted() + + if session_id is None: + raise ValueError("Session ID is required for unified multiobjective models.") + + # Use the concrete model device (e.g. cuda:2), not a generic "cuda". + transform_device_torch = next(self.model.parameters()).device + transform_device = str(transform_device_torch) + device_ctx = ( + torch.cuda.device(transform_device_torch) + if transform_device_torch.type == "cuda" + else nullcontext() + ) + + with device_ctx: + # Build a unified dataset for sampling context + dataset = cebra.data.UnifiedDataset( + cebra.data.TensorDataset( + inputs[i], continuous=labels[i], offset=cebra.data.Offset(0, 1)) + for i in range(len(inputs))).to(transform_device) + + # Use UnifiedLoader for sampling + loader = cebra.data.UnifiedLoader(dataset, num_steps=1).to(transform_device) + + # Set split_outputs to specified value + self.model.set_split_outputs(split_outputs) + + # Compute embeddings in batches + refs_data_batch_embeddings = [] + batch_range = range(0, len(dataset.get_session(session_id)), batch_size) + if len(batch_range) < 2: + raise ValueError( + "Not enough data to perform the batched transform. Please provide a larger dataset or reduce the batch size." + ) + for batch_start in batch_range: + batch_end = min(batch_start + batch_size, + len(dataset.get_session(session_id))) + + if batch_start == batch_range[-2]: # one before last batch + last_start = batch_start + continue + if batch_start == batch_range[-1]: # last batch, likely incomplete + batch_start = last_start + batch_end = len(dataset.get_session(session_id)) + + # Sample indices from all sessions aligned to the target session + refs_idx_batch = loader.sampler.sample_all_sessions( + ref_idx=torch.arange(batch_start, batch_end), + session_id=session_id).to(transform_device) + + # Concatenate data across sessions + refs_data_batch = torch.cat([ + session[refs_idx_batch[s_id].cpu()] + for s_id, session in enumerate(dataset.iter_sessions()) + ], dim=1).squeeze() + + if len(self.model.get_offset()) < 2 and pad_before_transform: + pad_before_transform = False + + self.model.eval() + # Get embedding with the specified split_outputs setting + embedding = self._transform(model=self.model, + inputs=refs_data_batch, + pad_before_transform=pad_before_transform, + offset=self.model.get_offset(), + batch_size=batch_size) + refs_data_batch_embeddings.append(embedding) + + + # Reset split_outputs to True for subsequent training + self.model.set_split_outputs(True) + + if split_outputs: + # If split_outputs was True, we have tuples of embeddings + # Stack them across batches per objective + num_objectives = len(refs_data_batch_embeddings[0]) + return tuple(torch.cat([batch[i] for batch in refs_data_batch_embeddings], dim=0) + for i in range(num_objectives)) + else: + # If split_outputs was False, we have concatenated tensors + return torch.cat(refs_data_batch_embeddings, dim=0) + + + def get_aligned_data(self, + inputs, + labels, + start: int, + end: int, + session_id: Optional[int] = None) -> torch.Tensor: + """Get data aligned across sessions for the specified session ID and index range. + + Args: + inputs: List of input tensors, one per session. + labels: List of label tensors, one per session. + start: Start index for the target session. + end: End index for the target session. + session_id: The target session ID to align to. + + Returns: + A tensor of data aligned across sessions for the specified session ID and index range. + """ + + # Build a unified dataset for sampling context + dataset = cebra.data.UnifiedDataset( + cebra.data.TensorDataset( + inputs[i], continuous=labels[i], offset=cebra.data.Offset(0, 1)) + for i in range(len(inputs))).to(self.device) + + # Use UnifiedLoader for sampling + loader = cebra.data.UnifiedLoader(dataset, num_steps=1) + + # Sample indices from all sessions aligned to the target session + refs_idx_batch = loader.sampler.sample_all_sessions( + ref_idx=torch.arange(start, end), + session_id=session_id).to(self.device) + + # Concatenate data across sessions + refs_data_batch = torch.cat([ + session[refs_idx_batch[s_id].cpu()] + for s_id, session in enumerate(dataset.iter_sessions()) + ], dim=1).squeeze() + + return refs_data_batch \ No newline at end of file From d869d700cb13dc99ec2be2d625fe7b26a63c4781 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Fri, 2 Oct 2026 14:59:45 +0200 Subject: [PATCH 06/27] Add random tie-breaking option to UnifiedSampler and related classes --- cebra/distributions/multisession.py | 38 ++++++++++++++++++++++-- cebra/solver/multiobjective.py | 11 +++++-- cebra/solver/unified_session.py | 6 +++- tests/test_distributions.py | 45 +++++++++++++++++++++++++++++ 4 files changed, 94 insertions(+), 6 deletions(-) diff --git a/cebra/distributions/multisession.py b/cebra/distributions/multisession.py index 47b25ba0..051689e9 100644 --- a/cebra/distributions/multisession.py +++ b/cebra/distributions/multisession.py @@ -464,6 +464,39 @@ class UnifiedSampler(MultisessionSampler): """ + def __init__(self, + dataset, + time_offset, + device: Optional[str] = None, + random_ties: bool = False, + tie_rtol: float = 1e-6): + """ + Args: + random_ties: If ``True``, every nearest-label search (the matched samples of the + non-reference sessions in :py:meth:`sample_all_sessions`, and the positives of + every session in :py:meth:`sample_conditional`) picks uniformly at random among + all timepoints whose label is equally close to the query, instead of the first + one. Needed whenever labels repeat exactly within a session -- e.g. the same + stimulus frame shown on several trials -- where ``argmin`` always returns the + earliest trial. Can also be set after construction (``sampler.random_ties``). + Default ``False`` keeps the original behaviour. + tie_rtol: Relative tolerance for two distances to count as tied (absorbs float + rounding in the distance computation). + """ + super().__init__(dataset, time_offset, device=device) + self.random_ties = random_ties + self.tie_rtol = tie_rtol + + def _search(self, session_id: int, query: torch.Tensor) -> torch.Tensor: + """Nearest-label search in one session, ties broken as set by ``random_ties``.""" + if not self.random_ties: + return self.index[session_id].search(query) + distance = self.index[session_id].dist_matrix(query) # (session length, num queries) + dmin = distance.min(dim=0, keepdim=True).values + tied = distance <= dmin + self.tie_rtol * dmin.abs().clamp_min(1.0) + scores = torch.rand(distance.shape, device=distance.device) + return scores.masked_fill(~tied, -1.0).argmax(dim=0) + def sample_all_uniform_prior(self, num_samples: int) -> npt.NDArray: """Returns uniformly sampled index for all sessions of the dataset. @@ -580,8 +613,7 @@ def sample_all_sessions(self, ref_idx: torch.Tensor, # aligned=False) # get the idx of the datapoint that is the closest to the query - all_idx[i] = self.index[i].search( - query) # search in the whole dataset + all_idx[i] = self._search(i, query) # search in the whole dataset # all_idx[i] = self.index[i].search_or_mask( # query, threshold=self.distance_threshold[i]) @@ -615,6 +647,6 @@ def sample_conditional(self, reference_idx: npt.NDArray) -> torch.Tensor: query = self._get_query(reference_idx=reference_idx[session_id], session_id=session_id) - cond_idx[session_id] = self.index[session_id].search(query) + cond_idx[session_id] = self._search(session_id, query) return cond_idx.cpu().numpy() diff --git a/cebra/solver/multiobjective.py b/cebra/solver/multiobjective.py index ca521b26..8959069a 100644 --- a/cebra/solver/multiobjective.py +++ b/cebra/solver/multiobjective.py @@ -655,7 +655,8 @@ def transform(self, pad_before_transform: bool = True, session_id: Optional[int] = None, batch_size: Optional[int] = 512, - split_outputs: bool = False) -> torch.Tensor: + split_outputs: bool = False, + random_ties: bool = False) -> torch.Tensor: """Compute the embedding for the `session_id`th session of the dataset. For unified multiobjective training, the embedding is computed using the shared @@ -672,6 +673,9 @@ def transform(self, split_outputs: Whether to return per-objective outputs (True) or concatenated output (False, default). If True, returns a tuple of embeddings one per objective. + random_ties: Break nearest-label ties uniformly at random when aligning the other + sessions to ``session_id`` (``UnifiedSampler.random_ties``). Default + ``False`` keeps the first tie. Set it to match how the model was trained. Returns: If split_outputs=False: The output embedding for the session corresponding to @@ -706,6 +710,7 @@ def transform(self, # Use UnifiedLoader for sampling loader = cebra.data.UnifiedLoader(dataset, num_steps=1).to(transform_device) + loader.sampler.random_ties = bool(random_ties) # Set split_outputs to specified value self.model.set_split_outputs(split_outputs) @@ -771,7 +776,8 @@ def get_aligned_data(self, labels, start: int, end: int, - session_id: Optional[int] = None) -> torch.Tensor: + session_id: Optional[int] = None, + random_ties: bool = False) -> torch.Tensor: """Get data aligned across sessions for the specified session ID and index range. Args: @@ -793,6 +799,7 @@ def get_aligned_data(self, # Use UnifiedLoader for sampling loader = cebra.data.UnifiedLoader(dataset, num_steps=1) + loader.sampler.random_ties = bool(random_ties) # Sample indices from all sessions aligned to the target session refs_idx_batch = loader.sampler.sample_all_sessions( diff --git a/cebra/solver/unified_session.py b/cebra/solver/unified_session.py index 3524700f..4e7a5156 100644 --- a/cebra/solver/unified_session.py +++ b/cebra/solver/unified_session.py @@ -195,7 +195,8 @@ def transform(self, labels: List[torch.Tensor], pad_before_transform: bool = True, session_id: Optional[int] = None, - batch_size: Optional[int] = 512) -> torch.Tensor: + batch_size: Optional[int] = 512, + random_ties: bool = False) -> torch.Tensor: """Compute the embedding for the `session_id`th session of the dataset. Note: @@ -208,6 +209,8 @@ def transform(self, session_id: The session ID, an :py:class:`int` between 0 and the number of sessions -1. batch_size: If not None, batched inference will be applied. + random_ties: Break nearest-label ties uniformly at random when aligning the other + sessions (``UnifiedSampler.random_ties``). Default ``False`` keeps the first tie. Note: The ``session_id`` is needed in order to sample the corresponding number of samples and @@ -238,6 +241,7 @@ def transform(self, # Only used to sample the reference samples loader = cebra.data.UnifiedLoader(dataset, num_steps=1) + loader.sampler.random_ties = bool(random_ties) # Sampling in batch refs_data_batch_embeddings = [] diff --git a/tests/test_distributions.py b/tests/test_distributions.py index 656559bb..fa83a013 100644 --- a/tests/test_distributions.py +++ b/tests/test_distributions.py @@ -26,6 +26,7 @@ import pytest import torch +import cebra.data import cebra.datasets as cebra_datasets import cebra.distributions as cebra_distr import cebra.distributions.base as cebra_distr_base @@ -424,3 +425,47 @@ def test_unified_distribution(time_offset): positive = sampler.sample_conditional(sample) assert positive.shape == (dataset.num_sessions, num_samples) + + +def _tiled_unified_dataset(n_frames=50, n_repeats=6, n_sessions=3, seed=0): + """Sessions whose labels repeat exactly on every trial (same stimulus frame each repeat).""" + gen = torch.Generator().manual_seed(seed) + labels = torch.randn(n_frames, 4, generator=gen).repeat(n_repeats, 1) + sessions = [ + cebra.data.TensorDataset(neural=torch.randn(n_frames * n_repeats, 3 + i, generator=gen), + continuous=labels.clone()) for i in range(n_sessions) + ] + return cebra.data.UnifiedDataset(*sessions), labels + + +def test_unified_sampler_default_returns_first_tie(): + dataset, _ = _tiled_unified_dataset() + sampler = cebra_distr.UnifiedSampler(dataset, time_offset=1) + ref = sampler.sample_prior(200, session_id=0) + # every non-reference session is matched on the first trial: argmin returns the earliest tie + assert (ref[1:] < 50).all() + assert (sampler.sample_conditional(ref) < 50).all() + + +@pytest.mark.parametrize("set_after_init", [False, True]) +def test_unified_sampler_random_ties_uses_every_repeat(set_after_init): + n_frames, n_repeats = 50, 6 + dataset, labels = _tiled_unified_dataset(n_frames, n_repeats) + if set_after_init: + sampler = cebra_distr.UnifiedSampler(dataset, time_offset=1) + sampler.random_ties = True + else: + sampler = cebra_distr.UnifiedSampler(dataset, time_offset=1, random_ties=True) + np.random.seed(0) + torch.manual_seed(0) + ref = sampler.sample_prior(3000, session_id=0) + pos = sampler.sample_conditional(ref) + for idx in (ref[1:], pos): + repeats = np.bincount((np.asarray(idx) // n_frames).ravel(), minlength=n_repeats) + # spread over all repeats, roughly uniformly + assert (repeats > 0).all() + assert repeats.min() / repeats.max() > 0.7 + # matched samples are still exact label matches of the reference frame + ref_frame = ref[0] % n_frames + for s in range(1, ref.shape[0]): + assert torch.equal(labels[ref[s]], labels[ref_frame]) From da1822f2750624dbc120f8c2bba54a3d61ab12ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Fri, 23 Oct 2026 10:32:45 +0200 Subject: [PATCH 07/27] Update UnifiedSampler and related classes to enable random tie-breaking by default --- cebra/data/multiobjective.py | 5 ++++- cebra/distributions/multisession.py | 4 ++-- cebra/solver/multiobjective.py | 8 +++++--- cebra/solver/unified_session.py | 5 +++-- tests/test_distributions.py | 9 +++++++-- 5 files changed, 21 insertions(+), 10 deletions(-) diff --git a/cebra/data/multiobjective.py b/cebra/data/multiobjective.py index e2c6c54f..51e36da3 100644 --- a/cebra/data/multiobjective.py +++ b/cebra/data/multiobjective.py @@ -228,7 +228,10 @@ def add_config(self, config): "UnifiedDataset must have 'continuous_index' attribute." ) - #TODO: adapt to more labels! + # Not handled: the sampler always uses the loader's ``time_offset`` + # (default 10), not ``kwargs['time_delta']``, and always samples on the dataset's primary + # ``continuous_index``; per-objective labels (``label_name`` / ``add_labels``) are ignored. + # Every current launcher passes time_delta=10, so the two agree. distribution = cebra.distributions.UnifiedSampler( self.dataset, self.time_offset, diff --git a/cebra/distributions/multisession.py b/cebra/distributions/multisession.py index 051689e9..570f2f9b 100644 --- a/cebra/distributions/multisession.py +++ b/cebra/distributions/multisession.py @@ -468,7 +468,7 @@ def __init__(self, dataset, time_offset, device: Optional[str] = None, - random_ties: bool = False, + random_ties: bool = True, tie_rtol: float = 1e-6): """ Args: @@ -479,7 +479,7 @@ def __init__(self, one. Needed whenever labels repeat exactly within a session -- e.g. the same stimulus frame shown on several trials -- where ``argmin`` always returns the earliest trial. Can also be set after construction (``sampler.random_ties``). - Default ``False`` keeps the original behaviour. + Default ``True``; ``False`` restores the legacy first-tie behaviour. tie_rtol: Relative tolerance for two distances to count as tied (absorbs float rounding in the distance computation). """ diff --git a/cebra/solver/multiobjective.py b/cebra/solver/multiobjective.py index 8959069a..35db92cf 100644 --- a/cebra/solver/multiobjective.py +++ b/cebra/solver/multiobjective.py @@ -656,7 +656,7 @@ def transform(self, session_id: Optional[int] = None, batch_size: Optional[int] = 512, split_outputs: bool = False, - random_ties: bool = False) -> torch.Tensor: + random_ties: bool = True) -> torch.Tensor: """Compute the embedding for the `session_id`th session of the dataset. For unified multiobjective training, the embedding is computed using the shared @@ -675,7 +675,7 @@ def transform(self, one per objective. random_ties: Break nearest-label ties uniformly at random when aligning the other sessions to ``session_id`` (``UnifiedSampler.random_ties``). Default - ``False`` keeps the first tie. Set it to match how the model was trained. + ``True``; ``False`` restores the legacy first-tie behaviour. Returns: If split_outputs=False: The output embedding for the session corresponding to @@ -777,7 +777,7 @@ def get_aligned_data(self, start: int, end: int, session_id: Optional[int] = None, - random_ties: bool = False) -> torch.Tensor: + random_ties: bool = True) -> torch.Tensor: """Get data aligned across sessions for the specified session ID and index range. Args: @@ -786,6 +786,8 @@ def get_aligned_data(self, start: Start index for the target session. end: End index for the target session. session_id: The target session ID to align to. + random_ties: Break nearest-label ties uniformly at random (``UnifiedSampler.random_ties``). + Default ``True``; ``False`` restores the legacy first-tie behaviour. Returns: A tensor of data aligned across sessions for the specified session ID and index range. diff --git a/cebra/solver/unified_session.py b/cebra/solver/unified_session.py index 4e7a5156..29bee7e6 100644 --- a/cebra/solver/unified_session.py +++ b/cebra/solver/unified_session.py @@ -196,7 +196,7 @@ def transform(self, pad_before_transform: bool = True, session_id: Optional[int] = None, batch_size: Optional[int] = 512, - random_ties: bool = False) -> torch.Tensor: + random_ties: bool = True) -> torch.Tensor: """Compute the embedding for the `session_id`th session of the dataset. Note: @@ -210,7 +210,8 @@ def transform(self, the number of sessions -1. batch_size: If not None, batched inference will be applied. random_ties: Break nearest-label ties uniformly at random when aligning the other - sessions (``UnifiedSampler.random_ties``). Default ``False`` keeps the first tie. + sessions (``UnifiedSampler.random_ties``). Default ``True``; + ``False`` restores the legacy first-tie behaviour. Note: The ``session_id`` is needed in order to sample the corresponding number of samples and diff --git a/tests/test_distributions.py b/tests/test_distributions.py index fa83a013..20e1fee3 100644 --- a/tests/test_distributions.py +++ b/tests/test_distributions.py @@ -438,9 +438,14 @@ def _tiled_unified_dataset(n_frames=50, n_repeats=6, n_sessions=3, seed=0): return cebra.data.UnifiedDataset(*sessions), labels -def test_unified_sampler_default_returns_first_tie(): +def test_unified_sampler_random_ties_default_is_true(): dataset, _ = _tiled_unified_dataset() - sampler = cebra_distr.UnifiedSampler(dataset, time_offset=1) + assert cebra_distr.UnifiedSampler(dataset, time_offset=1).random_ties is True + + +def test_unified_sampler_first_tie_when_random_ties_false(): + dataset, _ = _tiled_unified_dataset() + sampler = cebra_distr.UnifiedSampler(dataset, time_offset=1, random_ties=False) ref = sampler.sample_prior(200, session_id=0) # every non-reference session is matched on the first trial: argmin returns the earliest tie assert (ref[1:] < 50).all() From 1e8c6d8e68f8e73b11ce63ce7aa3ee06a2ce6e48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Thu, 12 Nov 2026 12:49:10 +0100 Subject: [PATCH 08/27] Refactor code by removing prints, cleaning dataset class methods, updating documentation --- cebra/data/base.py | 25 --------------- cebra/data/datasets.py | 49 ++++++++++------------------- cebra/datasets/make_nlb_data.py | 1 - cebra/datasets/perich.py | 27 ++++++++++++++-- cebra/models/multiobjective.py | 2 -- docs/source/api/pytorch/data.rst | 16 ++++++++++ docs/source/api/pytorch/solvers.rst | 13 ++++++++ 7 files changed, 71 insertions(+), 62 deletions(-) diff --git a/cebra/data/base.py b/cebra/data/base.py index aed263ff..fce0c2c4 100644 --- a/cebra/data/base.py +++ b/cebra/data/base.py @@ -181,7 +181,6 @@ def expand_index_in_trial(self, index: torch.Tensor, trial_ids: List[int], ], device=index.device) - print(index) return index[:, None] + offset[None, :] def expand_index_in_trial_padding(self, index: torch.Tensor, @@ -202,30 +201,6 @@ def expand_index_in_trial_padding(self, index: torch.Tensor, return torch.minimum(torch.maximum(base, trial_start[:, None]), trial_end[:, None]) - def expand_index_forward(self, index: torch.Tensor) -> torch.Tensor: - """Expand the index to include the offset in the forward direction only. - - Args: - index: A one-dimensional tensor of type long containing indices - to select from the dataset. - - Returns: - An expanded index of shape ``(len(index), len(self.offset))``. - - - Note: - Requires the :py:attr:`offset` to be set. - - """ - offset = torch.arange(self.offset.left + self.offset.right + 1, - device=index.device) - - index = torch.clamp( - index, 0, - len(self) - (self.offset.right + self.offset.left + 1)) - - return index[:, None] + offset[None, :] - @abc.abstractmethod def __getitem__(self, index: torch.Tensor) -> torch.Tensor: """Return samples at the given time indices. diff --git a/cebra/data/datasets.py b/cebra/data/datasets.py index e999d397..668376f0 100644 --- a/cebra/data/datasets.py +++ b/cebra/data/datasets.py @@ -152,8 +152,10 @@ def to(self, device: str) -> "TensorDataset": """ super().to(device) self.neural = self.neural.to(device) - self.continuous = self.continuous.to(device) if self.continuous is not None else None - self.discrete = self.discrete.to(device) if self.discrete is not None else None + self.continuous = self.continuous.to( + device) if self.continuous is not None else None + self.discrete = self.discrete.to( + device) if self.discrete is not None else None return self def __getitem__(self, index): @@ -180,18 +182,6 @@ def _assert_datasets_same_device( return devices.pop() -class ForwardTensorDataset(TensorDataset): - """A dataset that returns items on the range [idx, idx + offset). - - Note: - This is useful for training models on predictive neural activity (e.g., grid cells, place cells). - """ - - def __getitem__(self, index: torch.Tensor) -> torch.Tensor: - index = self.expand_index_forward(index) - return self.neural[index].transpose(2, 1) - - class TrialTensorDataset(TensorDataset): """A dataset that returns items on the range [idx, idx + offset). @@ -633,14 +623,12 @@ def add_labels(self, label_name: str, label_list: List[torch.Tensor]): if len(label_list) != self.num_sessions: raise ValueError( f"Expected {self.num_sessions} label tensors (one per session), " - f"got {len(label_list)}" - ) - + f"got {len(label_list)}") + # Concatenate per-session labels into a single unified tensor - concatenated_labels = torch.cat([ - self._to_tensor(label) for label in label_list - ], dim=0) - + concatenated_labels = torch.cat( + [self._to_tensor(label) for label in label_list], dim=0) + self.labels[label_name] = concatenated_labels @staticmethod @@ -674,18 +662,16 @@ def load_batch_contrastive(self, index: BatchIndex) -> Batch: positive=index.positive[0], # Use first objective for structure ) batches = self._get_batches(temp_index) - + if hasattr(self, "apply_mask"): reference = self.apply_mask( - torch.cat([batch.reference for batch in batches], dim=1) - ) + torch.cat([batch.reference for batch in batches], dim=1)) negative = self.apply_mask( - torch.cat([batch.negative for batch in batches], dim=1) - ) + torch.cat([batch.negative for batch in batches], dim=1)) else: reference = torch.cat([batch.reference for batch in batches], dim=1) negative = torch.cat([batch.negative for batch in batches], dim=1) - + # Get positives per objective positive_per_obj = [] for obj_idx_tensor in index.positive: @@ -695,16 +681,15 @@ def load_batch_contrastive(self, index: BatchIndex) -> Batch: positive=obj_idx_tensor, ) batches = self._get_batches(temp_index) - + if hasattr(self, "apply_mask"): pos = self.apply_mask( - torch.cat([batch.positive for batch in batches], dim=1) - ) + torch.cat([batch.positive for batch in batches], dim=1)) else: pos = torch.cat([batch.positive for batch in batches], dim=1) - + positive_per_obj.append(pos) - + return cebra_data.Batch( reference=reference, negative=negative, diff --git a/cebra/datasets/make_nlb_data.py b/cebra/datasets/make_nlb_data.py index 66a632d8..61e8e25e 100644 --- a/cebra/datasets/make_nlb_data.py +++ b/cebra/datasets/make_nlb_data.py @@ -78,7 +78,6 @@ def filt(x): if kern_sd != 0: convolved = np.apply_along_axis(filt, 1, spikes) - print(np.any(np.isnan(convolved))) return convolved else: return spikes diff --git a/cebra/datasets/perich.py b/cebra/datasets/perich.py index 7ab2f5e3..b43dad5c 100644 --- a/cebra/datasets/perich.py +++ b/cebra/datasets/perich.py @@ -1,3 +1,24 @@ +# +# CEBRA: Consistent EmBeddings of high-dimensional Recordings using Auxiliary variables +# © Mackenzie W. Mathis & Steffen Schneider (v0.4.0+) +# Source code: +# https://github.com/AdaptiveMotorControlLab/CEBRA +# +# Please see LICENSE.md for the full license document: +# https://github.com/AdaptiveMotorControlLab/CEBRA/blob/main/LICENSE.md +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# import pathlib from enum import Enum from typing import Union @@ -5,7 +26,6 @@ import joblib as jl import numpy as np import pandas as pd -from torch_brain.data import Dataset # Migrated from poyo to torch_brain import cebra.data import cebra.io @@ -72,7 +92,7 @@ def __getitem__(self, index): index = self.expand_index(index) return self.neural[index].transpose(2, 1) - def load_dataset(self, path: str, split: str = "train") -> Dataset: + def load_dataset(self, path: str, split: str = "train"): """Load dataset from processed torch_brain format. Args: @@ -82,6 +102,9 @@ def load_dataset(self, path: str, split: str = "train") -> Dataset: Returns: Dataset object containing the recording """ + # torch_brain is an optional dependency, imported lazily. + from torch_brain.data import Dataset + # Extract the recording_id from the path # torch_brain expects: root/brainset/session.h5 # Format: recording_id = "brainset/session" diff --git a/cebra/models/multiobjective.py b/cebra/models/multiobjective.py index 5dc4d247..7441ded0 100644 --- a/cebra/models/multiobjective.py +++ b/cebra/models/multiobjective.py @@ -298,10 +298,8 @@ def __init__(self, check_slices_for_gaps(self.feature_ranges) if check_overlapping_feature_ranges(self.feature_ranges): - print("Computing renormalized ranges...") self.renormalize_ranges = compute_renormalize_ranges( self.feature_ranges, sort=True) - print("New ranges:", self.renormalize_ranges) def set_split_outputs(self, val): assert isinstance(val, bool) diff --git a/docs/source/api/pytorch/data.rst b/docs/source/api/pytorch/data.rst index 4f35932a..09e6c0bd 100644 --- a/docs/source/api/pytorch/data.rst +++ b/docs/source/api/pytorch/data.rst @@ -34,6 +34,22 @@ Pre-defined Datasets :show-inheritance: +Unified Datasets and Dataloaders +-------------------------------- + +:py:class:`cebra.data.datasets.UnifiedDataset` and :py:class:`cebra.data.datasets.DatasetxCEBRA` +are documented under *Pre-defined Datasets* above, and :py:class:`cebra.data.multi_session.UnifiedLoader` +under *Multi Session Dataloaders*. + + +Masking +-------------------------------- + +.. automodule:: cebra.data.masking + :members: + :show-inheritance: + + Single Session Dataloaders -------------------------------- diff --git a/docs/source/api/pytorch/solvers.rst b/docs/source/api/pytorch/solvers.rst index 1a4445bc..f2a5dd6d 100644 --- a/docs/source/api/pytorch/solvers.rst +++ b/docs/source/api/pytorch/solvers.rst @@ -25,6 +25,19 @@ Multi session training :members: :show-inheritance: +Unified session training +------------------------ + +.. automodule:: cebra.solver.unified_session + :members: + :show-inheritance: + +Multi-objective training +------------------------ + +The multi-objective solvers (:py:mod:`cebra.solver.multiobjective`) are documented under +:doc:`Multi-objective models `. + Training utilities ------------------ From f0dd150275af1d4abb4bdce315bd59f21a96b46e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Thu, 12 Nov 2026 13:41:12 +0100 Subject: [PATCH 09/27] Modify checkpoint loading to support numpy scalars --- cebra/solver/base.py | 108 +++++++++++++++---------------------------- tests/test_solver.py | 36 +++++++++++++++ 2 files changed, 73 insertions(+), 71 deletions(-) diff --git a/cebra/solver/base.py b/cebra/solver/base.py index 0e6d2c2b..04ed9f88 100644 --- a/cebra/solver/base.py +++ b/cebra/solver/base.py @@ -37,10 +37,8 @@ import literate_dataclasses as dataclasses import numpy as np -import packaging.version import torch import torch.nn.functional as F -import wandb from torch.utils.data import DataLoader from torch.utils.data import Dataset @@ -51,30 +49,34 @@ from cebra.solver.util import Meter from cebra.solver.util import ProgressBar -# NOTE(stes): From torch 2.6 onwards, we need to specify the following list -# when loading CEBRA models to allow weights_only = True. -CEBRA_LOAD_SAFE_GLOBALS = [ - cebra.data.Offset, torch.torch_version.TorchVersion, np.dtype, np.float64, - np.int64 +try: + from numpy._core.multiarray import scalar as _numpy_scalar # numpy>=2 +except ImportError: + from numpy.core.multiarray import scalar as _numpy_scalar # numpy<2 + +# From torch 2.6, ``torch.load`` only unpickles tensors and Python primitives by default +# (``weights_only=True``). A numpy scalar stored in a checkpoint, e.g. a value computed with numpy +# and saved in ``n_features`` or in the training ``log``, then fails to load. These globals let +# ``Solver.load`` rebuild numpy scalars, and nothing else. The module of the scalar function is +# ``numpy._core`` for files written with numpy>=2 and ``numpy.core`` with numpy<2, so both names +# are listed. +_CHECKPOINT_SAFE_GLOBALS = [ + (_numpy_scalar, "numpy._core.multiarray.scalar"), + (_numpy_scalar, "numpy.core.multiarray.scalar"), + np.dtype, +] + [ + getattr(np.dtypes, name) + for name in ("Int32DType", "Int64DType", "Float32DType", "Float64DType") + if hasattr(np, "dtypes") ] -def _safe_torch_load(filename, weights_only, **kwargs): - if weights_only is None: - if packaging.version.parse( - torch.__version__) >= packaging.version.parse("2.6.0"): - weights_only = True - else: - weights_only = False - - if not weights_only: - checkpoint = torch.load(filename, weights_only=False, **kwargs) - else: - # NOTE(stes): This is only supported for torch 2.6+ - with torch.serialization.safe_globals(CEBRA_LOAD_SAFE_GLOBALS): - checkpoint = torch.load(filename, weights_only=True, **kwargs) - - return checkpoint +def _load_checkpoint(path: str, map_location) -> dict: + """:py:func:`torch.load` that also accepts numpy scalars (see ``_CHECKPOINT_SAFE_GLOBALS``).""" + if not hasattr(torch.serialization, "safe_globals"): # torch<2.5 + return torch.load(path, map_location=map_location) + with torch.serialization.safe_globals(_CHECKPOINT_SAFE_GLOBALS): + return torch.load(path, map_location=map_location) def _check_indices(batch_start_idx: int, batch_end_idx: int, @@ -328,6 +330,8 @@ class Solver(abc.ABC, cebra.io.HasDevice): as the logs for positive (``pos``) and negative (``neg``) pairs. For the standard criterions in CEBRA, also contains the value of the ``temperature``. tqdm_on: Use ``tqdm`` for showing a progress bar during training. + scheduler: An optional PyTorch learning rate scheduler. If set, it is stepped + after every optimizer step (i.e., once per training iteration). """ model: torch.nn.Module @@ -385,29 +389,16 @@ def load_state_dict(self, state_dict: dict, strict: bool = True): """ def _contains(key): - if isinstance(state_dict, Solver): - if hasattr(state_dict, key): - return True - elif strict: - raise KeyError( - f"Key {key} missing in state_dict. Contains: {list(state_dict.keys())}." - ) - - elif isinstance(state_dict, dict): - if key in state_dict: - return True - elif strict: - raise KeyError( - f"Key {key} missing in state_dict. Contains: {list(state_dict.keys())}." - ) - + if key in state_dict: + return True + elif strict: + raise KeyError( + f"Key {key} missing in state_dict. Contains: {list(state_dict.keys())}." + ) return False def _get(key): - if isinstance(state_dict, Solver): - return getattr(state_dict, key) - elif isinstance(state_dict, dict): - return state_dict.get(key) + return state_dict.get(key) if _contains("model"): self.model.load_state_dict(_get("model")) @@ -543,11 +534,8 @@ def step(self, batch: cebra.data.Batch) -> dict: self.optimizer.step() if self.scheduler is not None: self.scheduler.step() - self.history.append(loss.item()) - - if wandb.run is not None: - wandb.log({"loss": loss.item()}) + self.history.append(loss.item()) stats = dict( pos=align.item(), neg=uniform.item(), @@ -776,41 +764,19 @@ def _inference(self, batch: cebra.data.Batch) -> cebra.data.Batch: """ raise NotImplementedError - def load(self, - logdir: str, - filename: str = "checkpoint.pth", - weights_only: bool = False, - map_location=None): + def load(self, logdir: str, filename: str = "checkpoint.pth"): """Load the experiment from its checkpoint file. Args: logdir: Logging directory. filename: Checkpoint name for loading the experiment. - weights_only: Indicates whether unpickler should be restricted to loading only tensors, primitive types, - dictionaries and any types added via :py:func:`torch.serialization.add_safe_globals`. - See :py:func:`torch.load` with ``weights_only=True`` for more details. It it recommended to leave this - at the default value of ``None``, which sets the argument to ``False`` for torch<2.6, and ``True`` for - higher versions of torch. If you experience issues with loading custom models (specified outside - of the CEBRA package), you can try to set this to ``False`` if you trust the source of the model. - map_location: Optional location passed to :py:func:`torch.load`. - If not provided, checkpoints are remapped to the current model device. """ savepath = os.path.join(logdir, filename) if not os.path.exists(savepath): print("Did not find a previous experiment. Starting from scratch.") return - - if map_location is None: - map_location = next(self.model.parameters()).device - - checkpoint = _safe_torch_load( - savepath, - weights_only, - map_location=map_location, - ) - - #checkpoint = torch.load(savepath, map_location=self.device, weights_only=weights_only) + checkpoint = _load_checkpoint(savepath, map_location=self.device) self.load_state_dict(checkpoint, strict=True) n_features = self.n_features diff --git a/tests/test_solver.py b/tests/test_solver.py index cf2c62ad..6e41e09f 100644 --- a/tests/test_solver.py +++ b/tests/test_solver.py @@ -401,3 +401,39 @@ def test_unified_session(data_name, model_architecture, loader_initfunc, emb = solver.transform(data, labels, session_id=i, batch_size=300) assert emb.shape == (loader.dataset.num_timepoints, 3) + + +def test_load_checkpoint_with_numpy_scalars(tmp_path): + # Checkpoints of unified solvers saved before n_features was a Python int store it as a + # numpy int64; torch>=2.6 loads with weights_only=True by default. + model = cebra.models.init("offset1-model", num_neurons=4, num_units=8, num_output=3) + solver = cebra.solver.SingleSessionSolver( + model=model, + criterion=cebra.models.InfoNCE(), + optimizer=torch.optim.Adam(model.parameters())) + solver.n_features = np.int64(4) + solver.log[("loss_val", 0)] = [np.float64(0.5)] + solver.save(str(tmp_path), "model.pt") + + other = cebra.solver.SingleSessionSolver( + model=cebra.models.init("offset1-model", num_neurons=4, num_units=8, num_output=3), + criterion=cebra.models.InfoNCE(), + optimizer=torch.optim.Adam(model.parameters())) + other.load(str(tmp_path), "model.pt") + assert other.n_features == 4 + assert other.log[("loss_val", 0)] == [0.5] + for key, value in solver.model.state_dict().items(): + assert torch.equal(value, other.model.state_dict()[key]) + + +@pytest.mark.skipif(not hasattr(torch.serialization, "safe_globals"), + reason="torch<2.5 has no weights_only allowlist") +def test_load_checkpoint_rejects_other_objects(tmp_path): + # Only numpy scalars are added to the allowlist: a checkpoint holding any other + # object (here a numpy array) is still refused when torch loads with weights_only=True. + path = tmp_path / "model.pt" + torch.save({"n_features": np.arange(3)}, path) + with pytest.raises(Exception): + with torch.serialization.safe_globals( + cebra.solver.base._CHECKPOINT_SAFE_GLOBALS): + torch.load(path, weights_only=True) From e1281eecdf1dc49915445c842dd73edec98fdc0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Thu, 12 Nov 2026 14:17:05 +0100 Subject: [PATCH 10/27] Optimize Jacobian regularization and add masking functionalities --- cebra/attribution/attribution_models.py | 23 +++-- cebra/data/base.py | 60 ++++--------- cebra/data/datasets.py | 34 ++------ cebra/data/masking.py | 85 +++++-------------- cebra/data/multiobjective.py | 15 ++-- cebra/models/jacobian_regularizer.py | 2 + tests/test_attribution.py | 108 ++++++++++++++++++++++++ tests/test_data_masking.py | 15 ++++ tests/test_models.py | 23 +++++ 9 files changed, 211 insertions(+), 154 deletions(-) diff --git a/cebra/attribution/attribution_models.py b/cebra/attribution/attribution_models.py index 8d06d001..b5794052 100644 --- a/cebra/attribution/attribution_models.py +++ b/cebra/attribution/attribution_models.py @@ -50,6 +50,7 @@ def _normalize_selected_result_keys(selected_keys): + """Map names as a set (``_`` read as ``-``), or ``None``; raise on unknown names.""" if selected_keys is None: return None normalized = [] @@ -430,14 +431,9 @@ def compute_attribution_map(self, batch_size=1024, selected_keys=None): @dataclasses.dataclass @register("jacobian-based-batched-optimized") class JFMethodBasedBatchedOptimized(JFMethodBased): - """Optimized Jacobian-based attribution using streaming mini-batches. + """Jacobian-based attribution computed in mini-batches, with an optional running mean. - This class keeps the original ``jacobian-based-batched`` behavior untouched. - - Args: - batch_size: Number of samples per Jacobian mini-batch. - return_full: If True, returns per-sample maps (same shape contract as the - original class). If False, returns sample-averaged maps to reduce memory. + Same results as ``jacobian-based-batched``, with less memory. """ def compute_attribution_map( @@ -447,6 +443,17 @@ def compute_attribution_map( selected_keys=None, latent_batch_size=None, ): + """Compute the attribution maps. + + Args: + batch_size: Samples per Jacobian batch. + return_full: Return one map per sample. If ``False``, return the mean over samples. + selected_keys: Maps to compute, e.g. ``["jf"]``. ``None``: all of them. + latent_batch_size: Embedding dimensions per autograd pass. ``None``: all at once. + + Returns: + Dict from map name to array, ``(T, D, N)`` per sample or ``(D, N)`` averaged. + """ selected_keys = _normalize_selected_result_keys(selected_keys) if batch_size > self.input_data.shape[0]: raise ValueError( @@ -511,8 +518,6 @@ def compute_attribution_map( for key, chunks in per_key_chunks.items() } else: - if total_samples == 0: - raise ValueError("No samples available for attribution aggregation.") result = { key: value / float(total_samples) for key, value in running_sums.items() diff --git a/cebra/data/base.py b/cebra/data/base.py index fce0c2c4..e8c36276 100644 --- a/cebra/data/base.py +++ b/cebra/data/base.py @@ -22,7 +22,6 @@ """Base classes for datasets and loaders.""" import abc -from typing import List import literate_dataclasses as dataclasses import torch @@ -149,21 +148,14 @@ def expand_index(self, index: torch.Tensor) -> torch.Tensor: return index[:, None] + offset[None, :] - def expand_index_in_trial(self, index: torch.Tensor, trial_ids: List[int], - trial_borders: List[int]) -> torch.Tensor: - """ - - Note: - When the neural/behavior is in discrete trial, e.g) Monkey Reaching Dataset - the slice should be defined within the trial. - - Args: - index: A one-dimensional tensor of type long containing indices - to select from the dataset. - trial_ids: Indicate the trial id to which the index belong to, - size of ``len(self.index)``. - trial_borders: Indicate the border of each trial, size of ``len(self.index)``. + def expand_index_in_trial(self, index, trial_ids, trial_borders): + """When the neural/behavior is in discrete trial, e.g) Monkey Reaching Dataset + the slice should be defined within the trial. + trial_ids is in size of a length of self.index and indicate the trial id of the index belong to. + trial_borders is in size of a length of self.idnex and indicate the border of each trial. + Todo: + - rewrite """ # TODO(stes) potential room for speed improvements by pre-allocating these tensors/ @@ -171,36 +163,18 @@ def expand_index_in_trial(self, index: torch.Tensor, trial_ids: List[int], offset = torch.arange(-self.offset.left, self.offset.right, device=index.device) - - index = torch.tensor([ - torch.clamp( - i, - trial_borders[trial_ids[i]] + self.offset.left, - trial_borders[trial_ids[i] + 1] - self.offset.right, - ) for i in index - ], - device=index.device) - + index = torch.tensor( + [ + torch.clamp( + i, + trial_borders[trial_ids[i]] + self.offset.left, + trial_borders[trial_ids[i] + 1] - self.offset.right, + ) for i in index + ], + device=self.device, + ) return index[:, None] + offset[None, :] - def expand_index_in_trial_padding(self, index: torch.Tensor, - trial_ids: List[int], - trial_borders: List[int]) -> torch.Tensor: - offset = torch.arange(-self.offset.left, - self.offset.right, - device=index.device) - - base = index[:, None] + offset[None, :] - - trial_borders = torch.tensor(trial_borders, device=index.device) - trial_ids = torch.tensor(trial_ids, device=index.device) - - trial_start = trial_borders[trial_ids[index]] - trial_end = trial_borders[trial_ids[index] + 1] - 1 - - return torch.minimum(torch.maximum(base, trial_start[:, None]), - trial_end[:, None]) - @abc.abstractmethod def __getitem__(self, index: torch.Tensor) -> torch.Tensor: """Return samples at the given time indices. diff --git a/cebra/data/datasets.py b/cebra/data/datasets.py index 668376f0..1285eef9 100644 --- a/cebra/data/datasets.py +++ b/cebra/data/datasets.py @@ -182,31 +182,6 @@ def _assert_datasets_same_device( return devices.pop() -class TrialTensorDataset(TensorDataset): - """A dataset that returns items on the range [idx, idx + offset). - - Note: - This is useful for training models on predictive neural activity (e.g., grid cells, place cells). - """ - - def __init__(self, - neural: Union[torch.Tensor, npt.NDArray], - continuous: Union[torch.Tensor, npt.NDArray] = None, - discrete: Union[torch.Tensor, npt.NDArray] = None, - offset: Offset = Offset(0, 1), - device: str = "cpu", - trial_ids: Union[torch.Tensor, npt.NDArray] = None, - trial_borders: Union[torch.Tensor, npt.NDArray] = None): - super().__init__(neural, continuous, discrete, offset, device) - self.trial_ids = trial_ids - self.trial_borders = trial_borders - - def __getitem__(self, index: torch.Tensor) -> torch.Tensor: - index = self.expand_index_in_trial_padding(index, self.trial_ids, - self.trial_borders) - return self.neural[index].transpose(2, 1) - - class DatasetCollection(cebra_data.MultiSessionDataset): """Multi session dataset made up of a list of datasets. @@ -507,10 +482,11 @@ def __init__(self, *datasets: cebra_data.SingleSessionDataset): @property def input_dimension(self) -> int: """Returns the sum of the input dimension for each session.""" - return np.sum([ - self.get_input_dimension(session_id) - for session_id in range(self.num_sessions) - ]) + # A Python int, not a numpy scalar: it is saved as ``n_features`` in the solver + # checkpoint, and ``torch.load(weights_only=True)`` rejects numpy scalars. + return sum( + int(self.get_input_dimension(session_id)) + for session_id in range(self.num_sessions)) def _get_batches(self, index): """Return the data at the specified index location.""" diff --git a/cebra/data/masking.py b/cebra/data/masking.py index ca8d1901..e4830aea 100644 --- a/cebra/data/masking.py +++ b/cebra/data/masking.py @@ -43,8 +43,6 @@ def set_masks( Dict[str, Any], List[Union[Tuple[str, Any], Dict[str, Any]]], ]] = None, - apply_multiple_masks: bool = False, - fill_with_noise: bool = False, ) -> None: """Set the mask types and parameters for the dataset. @@ -56,13 +54,6 @@ def set_masks( Args: masking: Mask configuration. See formats above. - apply_multiple_masks: When True, `apply_mask` will randomly pick a - number of configured masks and apply them all in a single call - (combined). When False, a single mask is sampled per call - (default/legacy behavior). - fill_with_noise: When True, masked positions are filled with Gaussian - noise sampled from per-neuron mean and std (computed from unmasked - values). When False, masked positions are zeroed (default/legacy behavior). Note: - By default, no masks are applied. @@ -70,10 +61,6 @@ def set_masks( class are replaced. When using the list format, entries are appended, allowing duplicates with different parameters. """ - # Store strategy - self._apply_multiple_masks = bool(apply_multiple_masks) - self._fill_with_noise = bool(fill_with_noise) - if masking is None: return @@ -183,53 +170,17 @@ def apply_mask(self, if not self._masks: return data - # Compute the mask to apply (single or combined) - if getattr(self, "_apply_multiple_masks", False): - # Randomly choose how many masks to apply (at least one, at most all) - num_to_apply = random.randint(1, len(self._masks)) - selected_masks = random.sample(self._masks, num_to_apply) + sampled_mask = random.choice(self._masks) + mask = sampled_mask.apply_mask(data) - # Start with all-ones mask and combine multiplicatively (logical AND) - mask = torch.ones_like(data, dtype=torch.int) - for m in selected_masks: - mask = mask.mul(m.apply_mask(data)) - else: - sampled_mask = random.choice(self._masks) - mask = sampled_mask.apply_mask(data) - - # Apply masking strategy: zeros or Gaussian noise - if getattr(self, "_fill_with_noise", False): - # Fill masked positions with per-neuron Gaussian noise - # mask: (batch_size, n_neurons, offset) with 1=keep, 0=mask - inverse_mask = (mask == 0) # True where we need to fill - - # Compute per-neuron mean and std from unmasked values - # Shape: (batch_size, n_neurons) - masked_data = data * mask # Zero out masked positions - sum_unmasked = masked_data.sum(dim=2) # Sum over time - count_unmasked = mask.sum(dim=2).clamp( - min=1) # Count valid timesteps - mean_per_neuron = sum_unmasked / count_unmasked # (batch_size, n_neurons) - - # Compute std - squared_diff = ((data - mean_per_neuron.unsqueeze(2))**2) * mask - var_per_neuron = squared_diff.sum(dim=2) / count_unmasked - std_per_neuron = var_per_neuron.sqrt().clamp( - min=1e-6) # Avoid div by zero - - # Generate Gaussian noise and fill masked positions - noise = torch.randn_like(data) * std_per_neuron.unsqueeze( - 2) + mean_per_neuron.unsqueeze(2) - data = torch.where(inverse_mask, noise, data) - else: - # Legacy behavior: multiply by mask (zeros out masked positions) - num_chunks = (data.shape[0] + chunk_size - - 1) // chunk_size # Compute number of chunks + num_chunks = (data.shape[0] + chunk_size - + 1) // chunk_size # Compute number of chunks - for i in range(num_chunks): - start, end = i * chunk_size, min((i + 1) * chunk_size, - data.shape[0]) - data[start:end].mul_(mask[start:end]) # in-place for memory + for i in range(num_chunks): + start, end = i * chunk_size, min((i + 1) * chunk_size, + data.shape[0]) + data[start:end].mul_( + mask[start:end]) # apply mask in-place to save memory return data @@ -472,6 +423,13 @@ def _select_masking_params(self) -> float: class SessionBlockMask(Mask): + """Mask all the neurons of randomly chosen sessions of a unified input. + + Args: + masking_value: Number of neurons of each session, in the order of the concatenated + input. Or a tuple ``(neurons_per_session, num_sessions)`` to always mask + ``num_sessions`` sessions; otherwise 1 to ``len(neurons_per_session) - 1`` are masked. + """ def __init__(self, masking_value: Union[List[int], Tuple[List[int], int]]): super().__init__(masking_value) @@ -487,16 +445,15 @@ def __name__(self): return "SessionBlockMask" def apply_mask(self, data: torch.Tensor) -> torch.Tensor: - """ Apply masking to contiguous blocks of neurons corresponding to sessions. + """Build a mask that hides the neurons of the selected sessions. + + The same sessions are masked for the whole batch. Args: - data: batch of size (batch_size, n_neurons, offset). - self.mask_prop: Proportion of neurons to mask. The neurons are masked in a - contiguous block. + data: Batch of shape ``(batch_size, n_neurons, offset)``. Returns: - torch.Tensor: The mask, a tensor of the same size as the input data with the - masked neurons set to 1. + Mask of the same shape as ``data``: 0 for masked neurons, 1 otherwise. """ batch_size, n_neurons, offset_length = data.shape diff --git a/cebra/data/multiobjective.py b/cebra/data/multiobjective.py index 51e36da3..0c166653 100644 --- a/cebra/data/multiobjective.py +++ b/cebra/data/multiobjective.py @@ -204,16 +204,13 @@ def __post_init__(self): self.distributions = [] def add_config(self, config): - """Add a per-objective configuration with time_delta distribution. - - Only time_delta distributions are supported for unified continuous multiobjective. - Uses the primary continuous index from the unified dataset. - + """Add the positive-sample distribution of one objective. + Args: - config: A dict with keys 'distribution' and 'kwargs'. - - 'distribution': must be "time_delta" - - 'kwargs': dict with 'time_delta' (int, the time window). - 'label_name' is ignored; primary continuous index is used. + config: Dict with ``"distribution"``, which must be ``"unified_time_delta"``, and + ``"kwargs"``. Note: ``kwargs["time_delta"]`` and ``kwargs["label_name"]`` are + ignored; the sampler uses the loader's ``time_offset`` and the dataset's + ``continuous_index``. """ kwargs_distribution = config['kwargs'] diff --git a/cebra/models/jacobian_regularizer.py b/cebra/models/jacobian_regularizer.py index c541993f..053b3424 100644 --- a/cebra/models/jacobian_regularizer.py +++ b/cebra/models/jacobian_regularizer.py @@ -114,6 +114,8 @@ def _random_vector(self, C: int, B: int, device: torch.device = None) -> torch.T v = torch.randn(B, C, device=device) arxilirary_zero = torch.zeros(B, C, device=device) vnorm = torch.norm(v, 2, 1, True) + #NOTE:``value`` as a keyword: the positional form ``addcdiv(input, value, t1, t2)`` is + # no longer supported and will be deprecated. v = torch.addcdiv(arxilirary_zero, v, vnorm, value=1.0) return v diff --git a/tests/test_attribution.py b/tests/test_attribution.py index cfb8ad7a..52d7eff9 100644 --- a/tests/test_attribution.py +++ b/tests/test_attribution.py @@ -2,8 +2,10 @@ import pytest import torch +import cebra.attribution import cebra.attribution._jacobian import cebra.attribution.jacobian_attribution as jacobian_attribution +import cebra.models from cebra.attribution import attribution_models from cebra.models import Model @@ -212,3 +214,109 @@ def test_attribution_map_transforms(): model=model, input_data=input_data, aggregate=aggregate) assert isinstance(jf, np.ndarray) assert isinstance(jhatg, np.ndarray) + + +def _optimized_and_reference(model, input_data, batch_size, **kwargs): + """Maps of ``jacobian-based-batched-optimized`` and of ``jacobian-based-batched``.""" + optimized = cebra.attribution.init("jacobian-based-batched-optimized", + model=model, + input_data=input_data, + output_dimension=3) + reference = cebra.attribution.init("jacobian-based-batched", + model=model, + input_data=input_data, + output_dimension=3) + return (optimized.compute_attribution_map(batch_size=batch_size, + **kwargs), + reference.compute_attribution_map(batch_size=batch_size)) + + +_JACOBIAN_KEYS = ("jf", "jf-convabs", "jf-inv-lsq", "jf-inv-svd", + "jf-convabs-inv-lsq", "jf-convabs-inv-svd") + + +@pytest.mark.parametrize("conv", [False, True]) +def test_jacobian_batched_optimized_matches_batched(conv): + torch.manual_seed(0) + if conv: + model = cebra.models.init("offset10-model", + num_neurons=6, + num_units=8, + num_output=3) + else: + model = torch.nn.Sequential(torch.nn.Linear(6, 8), torch.nn.Tanh(), + torch.nn.Linear(8, 3)) + input_data = torch.randn(70, 6, requires_grad=True) + # batch_size does not divide the number of samples: the last batch is smaller. + full, reference = _optimized_and_reference(model, input_data, batch_size=32) + for key in _JACOBIAN_KEYS: + np.testing.assert_allclose(full[key], reference[key], rtol=1e-5, atol=1e-6) + + mean, _ = _optimized_and_reference(model, + input_data, + batch_size=32, + return_full=False) + assert mean["num_samples"] == len(reference["jf"]) + for key in _JACOBIAN_KEYS: + np.testing.assert_allclose(mean[key], + reference[key].mean(axis=0), + rtol=1e-5, + atol=1e-6) + + +def test_jacobian_batched_optimized_selected_keys_and_latent_batching(): + torch.manual_seed(0) + model = torch.nn.Sequential(torch.nn.Linear(6, 8), torch.nn.Tanh(), + torch.nn.Linear(8, 3)) + input_data = torch.randn(40, 6, requires_grad=True) + full, reference = _optimized_and_reference(model, + input_data, + batch_size=16, + selected_keys=["jf", "jf_inv_svd"], + latent_batch_size=1) + # "_" is read as "-"; only the selected maps and the timings are returned. + assert set(full) == {"jf", "jf-inv-svd", "time_inversion_lsq", "time_inversion_svd"} + assert full["time_inversion_lsq"] == 0.0 + np.testing.assert_allclose(full["jf"], reference["jf"], rtol=1e-5, atol=1e-6) + np.testing.assert_allclose(full["jf-inv-svd"], + reference["jf-inv-svd"], + rtol=1e-5, + atol=1e-6) + + +def test_jacobian_batched_optimized_errors(): + model = torch.nn.Linear(6, 3) + method = cebra.attribution.init("jacobian-based-batched-optimized", + model=model, + input_data=torch.randn(10, 6), + output_dimension=3) + with pytest.raises(ValueError, match="bigger than data"): + method.compute_attribution_map(batch_size=11) + with pytest.raises(ValueError, match="Unknown attribution result key"): + method.compute_attribution_map(batch_size=5, selected_keys=["jf-abs"]) + + +@pytest.mark.parametrize("output_batch_size", [1, 2, 3, 100]) +def test_compute_jacobian_output_batching(output_batch_size): + torch.manual_seed(0) + model = torch.nn.Sequential(torch.nn.Linear(6, 8), torch.nn.Tanh(), + torch.nn.Linear(8, 5)) + x = torch.randn(7, 6) + kwargs = dict(double_precision=True) + full = cebra.attribution._jacobian.compute_jacobian( + model, [x.clone().requires_grad_(True)], **kwargs) + batched = cebra.attribution._jacobian.compute_jacobian( + model, [x.clone().requires_grad_(True)], + output_batch_size=output_batch_size, + **kwargs) + assert full.shape == (7, 5, 6) + np.testing.assert_allclose(batched, full, atol=1e-10) + + +def test_compute_jacobian_invalid_output_batch_size(): + model = torch.nn.Linear(3, 2) + with pytest.raises(ValueError): + cebra.attribution._jacobian.compute_jacobian( + model, [torch.randn(4, 3, requires_grad=True)], + double_precision=True, + output_batch_size=0) diff --git a/tests/test_data_masking.py b/tests/test_data_masking.py index 78448300..24ed7e34 100644 --- a/tests/test_data_masking.py +++ b/tests/test_data_masking.py @@ -213,3 +213,18 @@ def test_apply_mask_with_chunk_size(): assert masked_data.shape == data.shape, "Masked data shape should match input data shape" assert not torch.equal( data, masked_data), "Data should be modified when a mask is applied" + + +def test_session_block_mask(): + data = torch.ones((8, 10, 4)) + mask = cebra.data.masking.SessionBlockMask(([3, 3, 4], 1)) + out = mask.apply_mask(data) + assert out.shape == data.shape + # Exactly one whole session is masked, identically for all samples. + assert (out == out[:1]).all() + masked = int((out[0, :, 0] == 0).sum()) + assert masked in (3, 4) + + with pytest.raises(ValueError): + cebra.data.masking.SessionBlockMask( + ([3, 3, 4], 1)).apply_mask(torch.ones((2, 11, 4))) diff --git a/tests/test_models.py b/tests/test_models.py index 78779107..0c954267 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -26,6 +26,7 @@ from torch import nn import cebra.models +import cebra.models.jacobian_regularizer as jacobian_regularizer import cebra.models.model import cebra.registry @@ -366,3 +367,25 @@ def test_parametrized_offset_models_layer_structure(offset_n): f"Offset left for offset{offset_n} should be {expected_left}, got {offset.left}" assert offset.right == expected_right, \ f"Offset right for offset{offset_n} should be {expected_right}, got {offset.right}" + + +@pytest.mark.parametrize("n", [1, -1]) +def test_jacobian_reg_positive_and_gradient_flows(n): + torch.manual_seed(0) + model = nn.Linear(5, 3) + x = torch.randn(8, 5, requires_grad=True) + reg = jacobian_regularizer.JacobianReg(n=n)(x, model(x)) + assert reg.item() > 0 + reg.backward() + assert model.weight.grad is not None + assert model.weight.grad.abs().sum() > 0 + + +def test_jacobian_reg_exact_value_linear(): + # For y = W x, (1/2) tr(J J^T) = (1/2) ||W||_F^2 with n=-1. + torch.manual_seed(0) + model = nn.Linear(5, 3, bias=False) + x = torch.randn(8, 5, requires_grad=True) + value = jacobian_regularizer.JacobianReg(n=-1)(x, model(x)) + assert value.item() == pytest.approx(0.5 * model.weight.pow(2).sum().item(), + rel=1e-4) From 8a9a52e25cabffb4f300ff4afacd24c933ff12f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Fri, 13 Nov 2026 10:24:15 +0100 Subject: [PATCH 11/27] Add feature map attribution and update documentation - 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. --- cebra/attribution/__init__.py | 1 + cebra/attribution/feature_map.py | 537 ++++++++++++++++++++++ cebra/distributions/multisession.py | 202 +++++++-- cebra/solver/multiobjective.py | 317 +------------ cebra/solver/unified_session.py | 538 ++++++++++++++++++---- docs/source/api/pytorch/attribution.rst | 7 + docs/source/api/pytorch/solvers.rst | 4 + tests/test_distributions.py | 136 ++++++ tests/test_feature_map.py | 571 ++++++++++++++++++++++++ tests/test_integration_xcebra.py | 7 +- tests/test_solver.py | 208 +++++++++ 11 files changed, 2088 insertions(+), 440 deletions(-) create mode 100644 cebra/attribution/feature_map.py create mode 100644 tests/test_feature_map.py diff --git a/cebra/attribution/__init__.py b/cebra/attribution/__init__.py index e1d8306a..8dcef3fa 100644 --- a/cebra/attribution/__init__.py +++ b/cebra/attribution/__init__.py @@ -36,3 +36,4 @@ from cebra.attribution.attribution_models import * from cebra.attribution.jacobian_attribution import * +from cebra.attribution.feature_map import * diff --git a/cebra/attribution/feature_map.py b/cebra/attribution/feature_map.py new file mode 100644 index 00000000..e592aadb --- /dev/null +++ b/cebra/attribution/feature_map.py @@ -0,0 +1,537 @@ +# +# CEBRA: Consistent EmBeddings of high-dimensional Recordings using Auxiliary variables +# © Mackenzie W. Mathis & Steffen Schneider (v0.4.0+) +# Source code: +# https://github.com/AdaptiveMotorControlLab/CEBRA +# +# Please see LICENSE.md for the full license document: +# https://github.com/AdaptiveMotorControlLab/CEBRA/blob/main/LICENSE.md +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +"""Feature attribution maps: how each input channel drives each feature, through the embedding. + +For one trained model: + +1. ``W = fit_feature_readout(embedding, features, train_fraction=0.9)``: linear readout ``(D, F)`` from the + embedding to the features. +2. ``M = feature_attribution_map(solver, inputs, W)``: the signed map ``M = J^T W`` of shape + ``(N, F)``, with ``J = dz/dx`` the forward Jacobian of the encoder, averaged over time. The + solver must have been trained with the Jacobian regularizer. +3. ``average_feature_maps([M_1, M_2, ...])``: mean over models. + +Fit ``W`` for each model separately, on that model's own embedding: the embeddings of different +models are not aligned, so a ``W`` is only valid for the model it was fitted on. + +``N`` is the number of input channels (summed over sessions for a unified model), ``D`` the +embedding dimension and ``F`` the number of features. The map is signed: no absolute value and no +pseudo-inverse. + +Valid rows: a model with offset ``(left, right)`` gives one output per window of ``left + right`` +input samples, so row ``r`` of the embedding and of the per-row maps is input sample ``left + r``: +features ``features[left:T - right + 1]`` match the rows of a session of ``T`` samples. +""" + +import warnings + +import numpy as np +import torch + +import cebra.attribution +import cebra.models +from cebra.solver.unified_session import UnifiedSolverxCEBRA + +__all__ = [ + "fit_feature_readout", + "feature_attribution_map", + "average_feature_maps", +] + + +def _train_rows(n_rows: int, train_fraction, train_index) -> np.ndarray: + """Integer row indices of the readout's training subset (see :func:`fit_feature_readout`).""" + if train_fraction is not None and train_index is not None: + raise ValueError("Give train_fraction or train_index, not both.") + if train_fraction is None and train_index is None: + train_fraction = 0.8 + print( + "fit_feature_readout: fitting on the first 80% of rows (train_fraction=0.8); " + "pass train_fraction or train_index to choose.") + if train_fraction is not None: + if not 0 < float(train_fraction) <= 1: + raise ValueError( + f"train_fraction must be in (0, 1], got {train_fraction}.") + rows = np.arange(int(round(n_rows * float(train_fraction)))) + else: + index = np.asarray(train_index) + if index.dtype == bool: + if index.shape != (n_rows,): + raise ValueError( + f"A boolean train_index must have shape ({n_rows},), got {index.shape}." + ) + rows = np.flatnonzero(index) + else: + if index.ndim != 1 or (index.size and + not np.issubdtype(index.dtype, np.integer)): + raise ValueError( + "train_index must be a 1-d array of integer rows or a boolean mask." + ) + if index.size and (index.min() < -n_rows or index.max() >= n_rows): + raise ValueError( + f"train_index is out of range for {n_rows} rows.") + rows = np.arange(n_rows)[index.astype(int)] + if rows.size == 0: + raise ValueError("The readout training subset is empty.") + if np.unique(rows).size == n_rows: + warnings.warn( + "The readout is fitted on every row passed, so no row is held out. Pass only " + "training data, or hold rows out with train_fraction < 1 or a train_index that " + "leaves rows out.", + UserWarning, + stacklevel=3) + return rows + + +def fit_feature_readout( + embedding, + features, + alpha: float = 1.0, + train_fraction=None, + train_index=None, +) -> np.ndarray: + """Fit a ridge readout from the embedding to the features. + + The rows of ``embedding`` and ``features`` must be aligned 1:1 (see the module notes for the + valid rows). The readout is fitted on the first 80% of the rows by default, or on the rows + chosen by ``train_fraction`` (the first rows, a contiguous block) or ``train_index`` (any + rows), so the other rows stay free for a held-out check. Selecting every row is only right + if the rows passed are all training data; it gives a warning. + + Discrete (categorical) features must be one-hot encoded, one column per category: integer + labels would be fitted as one continuous target. + + Args: + embedding: Array of shape ``(T, D)``. + features: Array of shape ``(T, F)``, or ``(T,)`` for one feature. Used as given; z-score + them first to put features on a comparable scale. + alpha: Ridge penalty. + train_fraction: Fit on the first ``round(T * train_fraction)`` rows, in ``(0, 1]``. + Default (neither argument given): 0.8, with a message printed. + train_index: Fit on these rows, as integer indices or a boolean mask of length ``T``. + Not together with ``train_fraction``. + + Returns: + The readout ``W`` of shape ``(D, F)``, such that ``embedding @ W`` approximates + ``features`` (the intercept is dropped). + + Raises: + ValueError: If both ``train_fraction`` and ``train_index`` are given, if the training + rows are empty, or if the shapes do not match. + + Warns: + UserWarning: If the selected rows are all the rows passed (no row held out). + + Example: + >>> import numpy as np + >>> from cebra.attribution import fit_feature_readout + >>> rng = np.random.default_rng(0) + >>> embedding = rng.normal(size=(100, 4)) + >>> features = embedding @ rng.normal(size=(4, 2)) + >>> W = fit_feature_readout(embedding, features, train_fraction=0.9) + >>> W.shape + (4, 2) + >>> W = fit_feature_readout(embedding, features) # first 80% of the rows + fit_feature_readout: fitting on the first 80% of rows (train_fraction=0.8); pass train_fraction or train_index to choose. + >>> held_out = np.corrcoef((embedding[90:] @ W)[:, 0], features[90:, 0])[0, 1] + >>> bool(held_out > 0.99) + True + """ + from sklearn.linear_model import Ridge + + embedding = np.asarray(embedding, dtype=float) + features = np.asarray(features, dtype=float) + if features.ndim == 1: + features = features[:, None] + if embedding.ndim != 2 or features.ndim != 2: + raise ValueError( + f"embedding and features must be 2-d, got {embedding.shape} and {features.shape}." + ) + if embedding.shape[0] != features.shape[0]: + raise ValueError( + f"embedding and features must have the same rows, got {embedding.shape[0]} and " + f"{features.shape[0]}.") + rows = _train_rows(embedding.shape[0], train_fraction, train_index) + + readout = Ridge(alpha=float(alpha)).fit(embedding[rows], features[rows]) + coef = np.asarray(readout.coef_).reshape(features.shape[1], + embedding.shape[1]) + return coef.T # (D, F), also for a single feature + + +def _window(model) -> tuple: + """(left, right) of the model window, as CEBRA applies it to the Jacobian input. + + CEBRA's Jacobian only windows the input for a ``ConvolutionalModelMixin``. Every other model is + evaluated sample by sample, i.e. ``(left, right) = (0, 1)``. + """ + if isinstance(model, cebra.models.ConvolutionalModelMixin): + offset = model.get_offset() + return int(offset.left), int(offset.right) + return 0, 1 + + +def _num_valid_rows(model, n_samples: int) -> int: + """Number of valid rows (see the module notes) of the model on ``n_samples`` inputs.""" + left, right = _window(model) + n_valid = int(n_samples) - (left + right) + 1 + if n_valid < 1: + raise ValueError( + f"{n_samples} input samples are too few for the model window ({left + right}).") + return n_valid + + +def _is_cuda_oom(exc: Exception) -> bool: + """Whether ``exc`` is a CUDA out-of-memory error.""" + message = str(exc).lower() + return "out of memory" in message and "cuda" in message + + +def _check_readout(W, n_outputs: int) -> np.ndarray: + """Readout as a float array of shape ``(n_outputs, F)``, or a clear error.""" + W = np.asarray(W, dtype=float) + if W.ndim != 2: + raise ValueError( + f"The readout W must be 2-d (outputs, features), got shape {W.shape}." + ) + if W.shape[0] != n_outputs: + raise ValueError( + f"The readout W has {W.shape[0]} rows, but the attributed model outputs are {n_outputs} " + f"(the model output dimension, or len(output_slice)). Fit W on the same embedding columns." + ) + return W + + +#: Attribution methods that return CEBRA's Jacobian ``jf``, usable as ``method``. +JACOBIAN_METHODS = ( + "jacobian-based-batched-optimized", + "jacobian-based-batched", + "jacobian-based", +) + + +def _check_method(method: str): + """Raise if ``method`` is not one of :data:`JACOBIAN_METHODS`.""" + if method not in JACOBIAN_METHODS: + raise ValueError( + f"method must be one of {JACOBIAN_METHODS}, got {method!r}.") + + +def _compute_jf(method, model, inputs, batch_size, latent_batch_size, + return_full): + """CEBRA's Jacobian ``jf`` with attribution ``method``: ``(T, D, N)``, or its ``(D, N)`` mean. + + ``inputs`` must require gradients. ``latent_batch_size`` is only used by + ``jacobian-based-batched-optimized``, which also averages without storing every sample. + """ + _check_method(method) + attribution = cebra.attribution.init( + method, + model=model, + input_data=inputs, + output_dimension=int(model.num_output), + ) + if method == "jacobian-based-batched-optimized": + result = attribution.compute_attribution_map( + batch_size=batch_size, + return_full=return_full, + selected_keys=["jf"], + latent_batch_size=latent_batch_size, + ) + return np.asarray(result["jf"], dtype=np.float64) + if method == "jacobian-based-batched": + result = attribution.compute_attribution_map(batch_size=batch_size, + selected_keys=["jf"]) + else: + result = attribution.compute_attribution_map(selected_keys=["jf"]) + jf = np.asarray(result["jf"], dtype=np.float64) + return jf if return_full else jf.mean(axis=0) + + +def _row_feature_maps(model, inputs, start, stop, W, output_slice, + latent_batch_size, method): + """Per-row maps ``J_t[output_slice]^T W`` for valid rows ``start`` to ``stop - 1``. + + The input samples ``start`` to ``stop + left + right - 2`` form the windows of these rows, so + CEBRA's Jacobian (``jf``: the window Jacobian averaged over the offset, one entry per row) is + computed on that slice only. Returns ``(stop - start, N, F)`` float64. + """ + left, right = _window(model) + device = next(model.parameters()).device + window = (inputs[start:stop + left + right - 1].to(device=device, + copy=True).detach()) + window.requires_grad_(True) + jac = _compute_jf(method, + model, + window, + batch_size=stop - start, + latent_batch_size=latent_batch_size, + return_full=True) # (rows, D, N) + if output_slice is not None: + jac = jac[:, output_slice, :] + return np.matmul(jac.transpose(0, 2, 1), W) # (rows, N, F) + + +def _feature_maps(model, inputs, W, output_slice, batch_size, latent_batch_size, + average, method): + """Shared implementation of the per-row and time-mean maps. + + Rows are processed in blocks of ``batch_size``; each block is multiplied by ``W`` at once, so + the full Jacobian over time is never stored. On CUDA out-of-memory errors the block size is + halved (down to 1, then the error is raised). + """ + inputs = torch.as_tensor(inputs) + n_valid = _num_valid_rows(model, inputs.shape[0]) + device = next(model.parameters()).device + step = min(max(1, int(batch_size)), n_valid) + + blocks, total, start = [], None, 0 + # A model trained with several losses returns one output per loss (split_outputs); + # the Jacobian needs the single concatenated output. + previous = getattr(model, "split_outputs", None) + if previous is not None: + model.split_outputs = False + # The Jacobian is taken in eval mode (no dropout, fixed normalization statistics). + modes = [(module, module.training) for module in model.modules()] + model.eval() + try: + while start < n_valid: + stop = min(start + step, n_valid) + try: + block = _row_feature_maps(model, inputs, start, stop, W, + output_slice, latent_batch_size, + method) + except RuntimeError as exc: + if not _is_cuda_oom(exc) or step <= 1: + raise + step = max(1, step // 2) + if device.type == "cuda": + torch.cuda.empty_cache() + continue + if average: + total = (block.sum(axis=0) if total is None else total + + block.sum(axis=0)) + else: + blocks.append(block) + start = stop + finally: + for module, training in modes: + module.training = training + if previous is not None: + model.split_outputs = previous + + if average: + return total / n_valid + return np.concatenate(blocks, axis=0) + + +def average_feature_maps(maps) -> np.ndarray: + """Mean of feature attribution maps, e.g. over models trained with different seeds. + + Average the signed maps: the mean of ``|M|`` is not ``|mean M|``. Each map must come from + its own model with a ``W`` fitted on that model's own embedding (the embeddings of different + models are not aligned): never share a ``W`` across models. + + Args: + maps: Sequence of arrays of the same shape, e.g. ``(N, F)`` per model. + + Returns: + Array with the shape of one map. + + Example: + >>> import numpy as np + >>> from cebra.attribution import average_feature_maps + >>> maps = [np.ones((5, 2)), 3 * np.ones((5, 2))] + >>> average_feature_maps(maps).shape + (5, 2) + >>> float(average_feature_maps(maps)[0, 0]) + 2.0 + """ + maps = [np.asarray(m) for m in maps] + if not maps: + raise ValueError("average_feature_maps needs at least one map.") + return np.mean(np.stack(maps), axis=0) + + +def _check_regularized(solver): + """Raise unless ``solver`` was set up with the Jacobian regularizer.""" + if isinstance(solver, cebra.CEBRA): + raise TypeError( + "A cebra.CEBRA object is not accepted: the sklearn API does not train regularized " + "models. Train with a regularized solver, e.g. 'unified-xcebra' or the xCEBRA " + "solvers.") + if (getattr(solver, "regularizer", None) is None and + getattr(solver, "jac_regularizer", None) is None): + raise TypeError( + f"feature_attribution_map needs a solver trained with the Jacobian regularizer " + f"(e.g. 'unified-xcebra', an xCEBRA solver or RegularizedSolver), got " + f"{type(solver).__name__}.") + + +def feature_attribution_map( + solver, + inputs, + W, + *, + labels=None, + session_id=None, + indices=None, + output_slice=None, + average: bool = True, + random_ties: bool = False, + seed=0, + batch_size: int = 64, + latent_batch_size: int = 32, + method: str = "jacobian-based-batched-optimized", +) -> np.ndarray: + """Signed feature attribution map ``M = J^T W`` of one model trained with the Jacobian regularizer. + + ``M[n, f] = sum_d dz_d/dx_n * W[d, f]``, with ``J`` the forward Jacobian of the embedding and + ``W`` the readout from :func:`fit_feature_readout`. A positive value means that raising + channel ``n`` raises the readout of feature ``f``. ``J(t)`` is the Jacobian of ``z(t)`` with + respect to the whole input window of the model, averaged over the window (CEBRA's ``jf``); + the mean map is the mean of the per-timepoint maps. + + Fit ``W`` for each model separately, on that model's own embedding (embeddings of different + models are not aligned, so a ``W`` is only valid for its model); never share a ``W`` across + models. For a unified solver, ``inputs`` and ``labels`` are per-session lists, as in + ``solver.transform``, and the map has one row per channel of all sessions concatenated. Use + the same ``random_ties`` and ``seed`` as the ``transform`` that gave the embedding ``W`` was + fitted on. + + Args: + solver: Solver trained with the Jacobian regularizer: a unified solver (e.g. + ``"unified-xcebra"``) or a single-session one (an xCEBRA solver or + :py:class:`~cebra.solver.regularized.RegularizedSolver`). Plain modules, unregularized + solvers and :py:class:`cebra.CEBRA` objects raise a ``TypeError``. + inputs: ``(T, N)`` array or tensor, or for a unified solver a list of ``(T_s, N_s)``. + W: Readout of shape ``(D, F)``, with ``D`` the output dimension (or + ``len(output_slice)``). + labels: Unified only, required. Auxiliary variables of each session, ``(T_s, d)``. + session_id: Unified only, required. Reference session. + indices: Rows of the (reference) session's inputs at which the map is computed. For a + unified solver the other sessions are aligned to these rows. Default: all. + output_slice: Single session only. Embedding columns of one head, e.g. one subspace of a + :py:class:`~cebra.models.SubspaceMultiobjectiveModel`. + average: ``True`` for the time mean ``(N, F)``, ``False`` for one map per valid row + ``(T_valid, N, F)`` (see the module notes). + random_ties: Unified only. Break nearest-label ties at random instead of taking the + first. + seed: Unified only. Seed of the tie draws (default 0). Use the same seed as the + ``transform`` that gave the embedding ``W`` was fitted on. + batch_size: Rows per Jacobian batch, halved on CUDA out-of-memory. + latent_batch_size: Embedding dimensions per autograd pass. Only used by the default + ``method``. + method: Attribution method that computes the Jacobian, one of + :data:`JACOBIAN_METHODS`. + + Returns: + Array, float64: ``(N, F)`` for ``average=True``, ``(T_valid, N, F)`` for ``average=False``. + + Raises: + TypeError: If ``solver`` was not trained with the Jacobian regularizer. + ValueError: If ``W`` does not match the output dimension, if the input is shorter than + the model window, if ``labels`` or ``session_id`` is missing for a unified solver, + if unified-only arguments are given for a single-session solver, or if ``method`` is + not a Jacobian method. + + Example: + Readout, map, then the average over models, on small random data: + + >>> import numpy as np + >>> import torch + >>> import cebra + >>> from cebra.attribution import (average_feature_maps, + ... feature_attribution_map, + ... fit_feature_readout) + >>> rng = np.random.default_rng(0) + >>> x = torch.tensor(rng.normal(size=(100, 10)), dtype=torch.float32) + >>> features = rng.normal(size=(100, 2)) + >>> maps = [] + >>> for seed in range(3): # one model per seed; here untrained encoders + ... _ = torch.manual_seed(seed) + ... model = cebra.models.init("offset1-model", num_neurons=10, num_units=16, + ... num_output=4) + ... solver = cebra.solver.RegularizedSolver( + ... model=model, criterion=cebra.models.InfoNCE(), + ... optimizer=torch.optim.Adam(model.parameters())) + ... embedding = model(x).detach().numpy() + ... W = fit_feature_readout(embedding, features, train_fraction=0.9) + ... maps.append(feature_attribution_map(solver, x, W)) + >>> maps[0].shape + (10, 2) + >>> average_feature_maps(maps).shape + (10, 2) + + For a unified model, pass the per-session data and labels, with the same ``random_ties`` + and ``seed`` as in the ``transform`` that produced the embedding:: + + z = solver.transform(inputs, labels, session_id=0, random_ties=True, seed=0) + W = fit_feature_readout(z, features, train_fraction=0.9) + M = feature_attribution_map(solver, inputs, W, labels=labels, session_id=0, + random_ties=True, seed=0) + """ + _check_regularized(solver) + _check_method(method) + model = solver.model + + if isinstance(solver, UnifiedSolverxCEBRA): + if labels is None: + raise ValueError( + "labels are required for a unified solver (a list of per-session " + "auxiliary variables, as in solver.transform).") + if session_id is None: + raise ValueError( + "session_id is required for a unified solver (the reference session)." + ) + if output_slice is not None: + raise ValueError( + "output_slice is not supported for a unified solver.") + W = _check_readout(W, int(model.num_output)) + aligned = solver.aligned_inputs(inputs, + labels, + session_id, + indices=indices, + random_ties=random_ties, + seed=seed) + return _feature_maps(model, aligned, W, None, batch_size, + latent_batch_size, average, method) + + if labels is not None or session_id is not None or random_ties: + raise ValueError( + "labels, session_id and random_ties are only for unified solvers." + ) + if isinstance(inputs, (list, tuple)): + raise ValueError( + "A single-session model needs inputs of shape (T, N), not a list.") + neural = torch.as_tensor(inputs, dtype=torch.float32) + if neural.ndim != 2: + raise ValueError( + f"inputs must have shape (T, N), got {tuple(neural.shape)}.") + if indices is not None: + neural = neural[torch.as_tensor(indices, dtype=torch.long)] + n_outputs = int(model.num_output) + if output_slice is not None: + n_outputs = len(range(n_outputs)[output_slice]) + W = _check_readout(W, n_outputs) + return _feature_maps(model, neural, W, output_slice, batch_size, + latent_batch_size, average, method) diff --git a/cebra/distributions/multisession.py b/cebra/distributions/multisession.py index 570f2f9b..823005e3 100644 --- a/cebra/distributions/multisession.py +++ b/cebra/distributions/multisession.py @@ -33,6 +33,8 @@ def _resolve_device(dataset, device: Optional[str] = None) -> str: + """Device of the sampler: ``device``, else the dataset's, with ``"cuda"`` made explicit.""" + def _normalize_cuda_device(device_name: str) -> str: if device_name != "cuda": return device_name @@ -193,9 +195,8 @@ def __init__(self, dataset, time_offset, device: Optional[str] = None): self.time_difference = np.concatenate(time_differences, axis=0) self.index = [ - cebra_distr.ContinuousIndex( - dataset.continuous_index.float().to(self.device)) - for dataset in self.dataset.iter_sessions() + cebra_distr.ContinuousIndex(dataset.continuous_index.float().to( + self.device)) for dataset in self.dataset.iter_sessions() ] @property @@ -319,9 +320,8 @@ def __init__(self, dataset, device: Optional[str] = None): self.lengths[0] = 0 self.index = [ - cebra_distr.DiscreteUniform( - dataset.discrete_index.int().to(self.device)) - for dataset in self.dataset.iter_sessions() + cebra_distr.DiscreteUniform(dataset.discrete_index.int().to( + self.device)) for dataset in self.dataset.iter_sessions() ] @property @@ -418,13 +418,20 @@ def __getitem__(self, pos_idx): class UnifiedSampler(MultisessionSampler): """Multi-session sampling, considering them as a single session. - Align embeddings across multiple sessions, using a set of - auxiliary variables, so that the samples in the different sessions - are sampled together based on how the corresponding auxiliary - variables are close from each other. + For each sample of a reference session, every other session contributes the sample with + the nearest auxiliary variable. The matched samples are concatenated on the neuron axis, so + a single model is trained on all sessions. + + Nearest-label search: - Then, the reference, positive and negative can be concatenated on their - neurons axis to train a single model for all sessions. + - Ties: when several samples are equally near (e.g. the same stimulus shown on several + trials), ``random_ties=True`` (default) draws one uniformly at random; ``False`` always + takes the first, so only the first occurrence (e.g. the first trial) is ever used. + - Repeated labels are handled automatically: if a session has at most half as many + distinct labels as samples, distances are computed to the distinct labels only, which is + faster. Otherwise (e.g. measured position or velocity) all samples are searched, as if + the step did not exist; only a one-time check per session is added. Nothing needs to be + set. Example: >>> import cebra.distributions.multisession as cebra_distributions_multisession @@ -456,6 +463,12 @@ class UnifiedSampler(MultisessionSampler): >>> pos = torch.LongTensor(pos) >>> loss = (ref - pos)**2 + >>> # Reproducible tie draws: pass a seed + >>> seeded = cebra_distributions_multisession.UnifiedSampler(dataset, time_offset=10, seed=0) + >>> matched = seeded.sample_all_sessions(torch.arange(20), session_id=0) + >>> matched.shape + torch.Size([2, 20]) + Note: This function does currently not support explicitly selected discrete indices. They should be added as dimensions to the @@ -464,38 +477,135 @@ class UnifiedSampler(MultisessionSampler): """ + #: Upper bound on the number of elements of the ``(session length, chunk)`` distance matrix + #: held in memory at once during the nearest-label search. + max_search_elements: int = 2**24 + def __init__(self, dataset, time_offset, device: Optional[str] = None, random_ties: bool = True, - tie_rtol: float = 1e-6): + tie_rtol: float = 1e-6, + seed: Optional[int] = None): """ Args: - random_ties: If ``True``, every nearest-label search (the matched samples of the - non-reference sessions in :py:meth:`sample_all_sessions`, and the positives of - every session in :py:meth:`sample_conditional`) picks uniformly at random among - all timepoints whose label is equally close to the query, instead of the first - one. Needed whenever labels repeat exactly within a session -- e.g. the same - stimulus frame shown on several trials -- where ``argmin`` always returns the - earliest trial. Can also be set after construction (``sampler.random_ties``). - Default ``True``; ``False`` restores the legacy first-tie behaviour. - tie_rtol: Relative tolerance for two distances to count as tied (absorbs float - rounding in the distance computation). + dataset: The :py:class:`~cebra.data.UnifiedDataset` to sample from. + time_offset: Step ``Δ`` of the label differences ``label[t + Δ] - label[t]`` used to + shift the positive samples. + device: Device of the sampled indices. Default: the device of the dataset. + random_ties: Draw one of several equally near samples at random instead of taking + the first. Keep ``True`` when labels repeat within a session. + tie_rtol: Relative tolerance for two distances to count as tied. + seed: Seed of the tie draws (made on CPU, so identical on any device). ``None`` + uses the global torch RNG. """ super().__init__(dataset, time_offset, device=device) self.random_ties = random_ties self.tie_rtol = tie_rtol + self.generator = (None if seed is None else + torch.Generator().manual_seed(int(seed))) + + def _unique_labels(self, session_id: int): + """Distinct labels of a session for :py:meth:`_search`, computed once and cached. + + With repeated labels (e.g. the same stimulus shown on several trials), distances are + computed to the distinct labels only, which is faster the more often each label repeats. + If more than half of + the rows are distinct (e.g. measured position), every row is its own label, so the step + is skipped where it would not help. + + Returns: + ``(dist_matrix, row_label, first_row)``: distance matrix over the labels, label id + of each row, and first row of each label (labels numbered in order of appearance). + """ + cache = self.__dict__.setdefault("_label_cache", {}) + if session_id not in cache: + labels = self.index[session_id].dist_matrix.index + uniq, inverse = torch.unique(labels, dim=0, return_inverse=True) + inverse = inverse.reshape(-1) + num = len(uniq) + rows = torch.arange(len(labels), device=labels.device) + if num > len(labels) // 2: + # Few repeated labels: searching the distinct labels saves little and costs + # more on GPU, so every row is its own label. + cache[session_id] = (self.index[session_id].dist_matrix, rows, + rows) + return cache[session_id] + first = torch.full((num,), len(labels), device=labels.device) + first = first.scatter_reduce(0, inverse, rows, reduce="amin") + order = first.argsort() # new label id -> old label id + rank = torch.empty_like(order) + rank[order] = torch.arange(num, device=order.device) + cache[session_id] = (cebra_distr.index.DistanceMatrix(uniq[order]), + rank[inverse], first[order]) + return cache[session_id] + + def _search(self, + session_id: int, + query: torch.Tensor, + generator: Optional[torch.Generator] = None) -> torch.Tensor: + """Row of session ``session_id`` nearest to each query, ties broken as set by ``random_ties``. + + Without ``random_ties``: the first nearest row (as ``argmin``). With ``random_ties``: one + uniform number per query, drawn on CPU from ``generator`` (else the sampler's, else the + global RNG), picks one of the ``k`` tied rows, each with probability ``1/k``. Memory is + bounded by :py:attr:`max_search_elements`. + """ + if query.ndim == 1: + query = query[None] + num_queries = len(query) + if num_queries == 0: + return torch.zeros(0, dtype=torch.long, device=self.device) + dist_matrix, row_label, first_row = self._unique_labels(session_id) + num_labels = len(first_row) + num_rows = len(row_label) + generator = self.generator if generator is None else generator + query = query.to(dist_matrix.device) + max_el = int(self.max_search_elements) - def _search(self, session_id: int, query: torch.Tensor) -> torch.Tensor: - """Nearest-label search in one session, ties broken as set by ``random_ties``.""" if not self.random_ties: - return self.index[session_id].search(query) - distance = self.index[session_id].dist_matrix(query) # (session length, num queries) - dmin = distance.min(dim=0, keepdim=True).values - tied = distance <= dmin + self.tie_rtol * dmin.abs().clamp_min(1.0) - scores = torch.rand(distance.shape, device=distance.device) - return scores.masked_fill(~tied, -1.0).argmax(dim=0) + uq, inv = torch.unique(query, dim=0, return_inverse=True) + inv = inv.reshape(-1) + chunk = max(1, max_el // max(num_labels, 1)) + best = torch.cat([ + dist_matrix(uq[s:s + chunk]).argmin(dim=0) + for s in range(0, len(uq), chunk) + ]) + return first_row[best][inv] + + # One uniform number per original query, drawn up front in query order. + u = torch.rand(num_queries, generator=generator).to(dist_matrix.device) + uq, inv = torch.unique(query, dim=0, return_inverse=True) + inv = inv.reshape(-1) + out = torch.empty(num_queries, + dtype=torch.long, + device=dist_matrix.device) + # distinct queries per block: the (labels, block) distances and the (block, rows) + # tied-row table both stay below max_search_elements + block = max(1, max_el // max(num_labels, num_rows, 1)) + stride = num_rows + 1 + for start in range(0, len(uq), block): + distance = dist_matrix(uq[start:start + block]) # (labels, block) + dmin = distance.min(dim=0, keepdim=True).values + tied_label = distance <= dmin + self.tie_rtol * dmin.abs( + ).clamp_min(1.0) + # (block, rows): the label of each row is tied; running count along the rows + tied = tied_label.T[:, row_label] + running = tied.cumsum(dim=1) + num_tied = running[:, -1] + cols = torch.arange(len(running), device=running.device) + # every row of ``running`` is non-decreasing, so with an offset per row the + # flattened table is sorted and one searchsorted answers all queries of the block + flat = (running + cols[:, None] * stride).reshape(-1) + sel = ((inv >= start) & (inv < start + block)).nonzero().flatten() + col = inv[sel] - start + k = num_tied[col] + rank = (u[sel] * k).floor().long().clamp_max(k - 1) + # (rank + 1)-th tied row: number of rows whose running count is <= rank + pos = torch.searchsorted(flat, col * stride + rank, right=True) + out[sel] = pos - col * num_rows + return out def sample_all_uniform_prior(self, num_samples: int) -> npt.NDArray: """Returns uniformly sampled index for all sessions of the dataset. @@ -568,22 +678,22 @@ def _get_query(self, query = self.all_data[cum_idx] + self.time_difference[diff_idx] return torch.from_numpy(query).to(self.device) - def sample_all_sessions(self, ref_idx: torch.Tensor, - session_id: int) -> torch.Tensor: - """Sample sessions based on a reference session. - - Reference samples for the ``session_id`` th session were first sampled uniformly, as in - the py:class:`~.MultisessionSampler`. Then, reference samples for the other sessions - are sampled so that they are as close as the corresponding auxiliary variables in - the reference session. + def sample_all_sessions( + self, + ref_idx: torch.Tensor, + session_id: int, + generator: Optional[torch.Generator] = None) -> torch.Tensor: + """Match the reference samples of one session in every other session. - Note: similar to ``sample_condiditonal`` but at the level of the sessions, sampling ref idx in each - session so that they are close to the ref idx in the reference session (``session_id`` th session). + In each other session, the sample with the nearest auxiliary variable is chosen (see + the class docstring for ties). Args: ref_idx: Uniformly sampled ``idx`` for the reference session, ``(num_samples, )``, values can be in ``[0, len(session)]``. session_id: Session ID of the reference session, whose ``idx`` are present in ``ref_idx``. + generator: CPU generator for the tie draws (only used with ``random_ties``). ``None`` + uses the sampler generator (see ``seed``), or the global torch RNG if there is none. Returns: The prior for all sessions, creating a "pseudo-animal", where ``idx`` sampled in different @@ -597,7 +707,8 @@ def sample_all_sessions(self, ref_idx: torch.Tensor, # element of a session in self.all_data. # cum_ref_idx: (num_samples, ), values of ref_idx, switched to correspond to the indexes in # of session_id, in the flatten array self.all_data. - all_idx = torch.zeros(self.num_sessions, len(ref_idx), + all_idx = torch.zeros(self.num_sessions, + len(ref_idx), device=self.device).long() query = self._get_query( reference_idx=ref_idx, session_id=session_id, @@ -613,7 +724,8 @@ def sample_all_sessions(self, ref_idx: torch.Tensor, # aligned=False) # get the idx of the datapoint that is the closest to the query - all_idx[i] = self._search(i, query) # search in the whole dataset + all_idx[i] = self._search(i, query, + generator) # search in the whole dataset # all_idx[i] = self.index[i].search_or_mask( # query, threshold=self.distance_threshold[i]) @@ -640,8 +752,8 @@ def sample_conditional(self, reference_idx: npt.NDArray) -> torch.Tensor: """ cond_idx = torch.zeros((reference_idx.shape[0], reference_idx.shape[1]), - dtype=torch.int, - device=self.device).long() + dtype=torch.int, + device=self.device).long() for session_id in range(self.num_sessions): query = self._get_query(reference_idx=reference_idx[session_id], diff --git a/cebra/solver/multiobjective.py b/cebra/solver/multiobjective.py index 35db92cf..72c88b99 100644 --- a/cebra/solver/multiobjective.py +++ b/cebra/solver/multiobjective.py @@ -34,6 +34,10 @@ - :py:class:`cebra.solver.multiobjective.ContrastiveMultiobjectiveSolverxCEBRA` - :py:class:`cebra.solver.multiobjective.SupervisedMultiobjectiveSolverxCEBRA` +Unified CEBRA with the Jacobian regularization of xCEBRA uses the base class of these solvers +and lives in :py:mod:`cebra.solver.unified_session` +(:py:class:`~cebra.solver.unified_session.UnifiedSolverxCEBRA`). + See Also: :py:class:`cebra.solver.multiobjective.SupervisedMultiobjectiveSolverxCEBRA` :py:class:`cebra.solver.multiobjective.MultiObjectiveConfig` @@ -43,7 +47,6 @@ import logging import time import warnings -from contextlib import nullcontext from typing import Callable, Dict, List, Optional, Tuple import literate_dataclasses as dataclasses @@ -436,6 +439,10 @@ def validation( stats_val.update(metrics) for key, value in stats_val.items(): + # Log Python numbers, not numpy scalars, so that the checkpoint loads with + # ``torch.load(weights_only=True)``. + if isinstance(value, np.generic): + value = value.item() self.log.setdefault(key, []).append(value) if logger is not None: @@ -507,311 +514,3 @@ def _inference(self, batch: cebra.data.Batch) -> cebra.data.Batch: cebra.data.Batch(pred_refs[i], pred_pos[i], pred_negs[i])) return prediction_batches - - -@register("unified-multiobjective-solver") -@dataclasses.dataclass -class UnifiedMultiobjectiveSolverxCEBRA(MultiobjectiveSolverBase): - """Unified multi-objective solver for CEBRA. - - This solver is used for training CEBRA models with multiple objectives across - multiple sessions using a single shared model. Designed to work with - :py:class:`cebra.data.multiobjective.UnifiedContrastiveMultiObjectiveLoader`. - - Unlike the standard multiobjective solver which handles per-session models, - this solver applies a single model to unified batches where reference, positive, - and negative samples are already aligned across sessions. - - See Also: - :py:class:`cebra.data.multiobjective.UnifiedContrastiveMultiObjectiveLoader` - :py:class:`cebra.solver.multiobjective.MultiObjectiveConfig` - :py:class:`cebra.models.multicriterions.MultiCriterions` - """ - - _variant_name = "unified-multiobjective-solver" - - def _set_fitted_params(self, loader: cebra.data.Loader): - """Set parameters once the solver is fitted for unified multiobjective training. - - For unified training, num_sessions is the number of sessions in the unified dataset, - and n_features is the total concatenated feature dimension across all sessions. - - Args: - loader: Loader used to fit the solver. - """ - self.num_sessions = loader.dataset.num_sessions - self.n_features = loader.dataset.input_dimension - - def _check_is_inputs_valid( - self, - inputs: Optional[List[torch.Tensor]], - session_id: Optional[int] = None - ): - """Check that the inputs can be inferred using the unified model. - - For unified training, inputs should be a list of per-session tensors, - and the concatenated feature dimension must match the model's input dimension. - - Args: - inputs: List of input tensors, one per session. Each has shape - (n_samples, num_features_session, ...). - session_id: The target session ID (required for unified models). - """ - if inputs is None: - return - - if isinstance(inputs, list): - inputs_shape = 0 - for i in range(len(inputs)): - inputs_shape += inputs[i].shape[1] - elif isinstance(inputs, torch.Tensor): - raise NotImplementedError( - "Unified models require a list of per-session tensors, not a single tensor." - ) - else: - raise NotImplementedError( - f"Invalid input type: {type(inputs)}. Expected list of tensors." - ) - - if self.n_features != inputs_shape: - raise ValueError( - f"Invalid input shape: model requires an input of shape " - f"(n_samples, {self.n_features}), but got total feature dimension " - f"(n_samples, {inputs_shape}) from concatenated sessions." - ) - - def _check_is_session_id_valid( - self, - session_id: Optional[int] = None, - ): - """Check that the session ID provided is valid for the unified solver. - - The session ID must be non-null and between 0 and the number of sessions. - - Args: - session_id: The session ID to check. - """ - if session_id is None: - raise RuntimeError( - "No session_id provided: unified multiobjective model requires a session_id " - "as the target session to use to align the sessions." - ) - if session_id >= self.num_sessions or session_id < 0: - raise RuntimeError( - f"Invalid session_id {session_id}: session_id for the current unified model " - f"must be between 0 and {self.num_sessions-1}." - ) - - def _get_model(self, session_id: Optional[int] = None): - """Get the unified model (independent of session_id). - - For unified models, there is only one shared model regardless of session. - The session_id is still validated but not used for model selection. - - Args: - session_id: The session ID, required for validation. - - Returns: - The shared unified model. - """ - self._check_is_session_id_valid(session_id=session_id) - self._check_is_fitted() - return self.model - - def _inference(self, batch: cebra.data.Batch) -> cebra.data.Batch: - """Compute predictions for unified multiobjective batch. - - For unified batches, reference, positive, and negative samples are already - aligned across sessions (concatenated along the neuron dimension). We apply - the single model to each and return per-objective prediction batches. - - Args: - batch: A Batch with reference, positive (list), and negative tensors - already unified across sessions. - - Returns: - A list of Batch objects, one per objective, with model predictions. - """ - pred_refs = self.model(batch.reference) - pred_negs = self.model(batch.negative) - - prediction_batches = [] - for i, positive in enumerate(batch.positive): - pred_pos = self.model(positive) - prediction_batches.append( - cebra.data.Batch( - reference=pred_refs[i].unsqueeze(0).view(-1, pred_refs[i].shape[-1]), - positive=pred_pos[i].unsqueeze(0).view(-1, pred_pos[i].shape[-1]), - negative=pred_negs[i].unsqueeze(0).view(-1, pred_negs[i].shape[-1]) - )) - - return prediction_batches - - - @torch.no_grad() - def transform(self, - inputs: List[torch.Tensor], - labels: List[torch.Tensor], - pad_before_transform: bool = True, - session_id: Optional[int] = None, - batch_size: Optional[int] = 512, - split_outputs: bool = False, - random_ties: bool = True) -> torch.Tensor: - """Compute the embedding for the `session_id`th session of the dataset. - - For unified multiobjective training, the embedding is computed using the shared - unified model, similar to UnifiedSolver. All sessions must be provided as they - are used for sampling context across sessions. - - Args: - inputs: The input signal for all sessions (list of tensors). - labels: The auxiliary variables to use for sampling (list of tensors). - pad_before_transform: Whether to pad the input before computing embeddings. - session_id: The session ID for which to compute embeddings. Required for - multi-session models. - batch_size: Batch size for computing embeddings (default 512). - split_outputs: Whether to return per-objective outputs (True) or concatenated - output (False, default). If True, returns a tuple of embeddings - one per objective. - random_ties: Break nearest-label ties uniformly at random when aligning the other - sessions to ``session_id`` (``UnifiedSampler.random_ties``). Default - ``True``; ``False`` restores the legacy first-tie behaviour. - - Returns: - If split_outputs=False: The output embedding for the session corresponding to - the provided ID `session_id`, with shape (num_samples(session_id), output_dimension). - If split_outputs=True: A tuple of embeddings, one per objective, with shapes - (num_samples(session_id), output_dimension_objective_i). - """ - if not isinstance(inputs, list): - raise ValueError( - f"Inputs to transform() should be a list, not {type(inputs)}.") - - self._check_is_fitted() - - if session_id is None: - raise ValueError("Session ID is required for unified multiobjective models.") - - # Use the concrete model device (e.g. cuda:2), not a generic "cuda". - transform_device_torch = next(self.model.parameters()).device - transform_device = str(transform_device_torch) - device_ctx = ( - torch.cuda.device(transform_device_torch) - if transform_device_torch.type == "cuda" - else nullcontext() - ) - - with device_ctx: - # Build a unified dataset for sampling context - dataset = cebra.data.UnifiedDataset( - cebra.data.TensorDataset( - inputs[i], continuous=labels[i], offset=cebra.data.Offset(0, 1)) - for i in range(len(inputs))).to(transform_device) - - # Use UnifiedLoader for sampling - loader = cebra.data.UnifiedLoader(dataset, num_steps=1).to(transform_device) - loader.sampler.random_ties = bool(random_ties) - - # Set split_outputs to specified value - self.model.set_split_outputs(split_outputs) - - # Compute embeddings in batches - refs_data_batch_embeddings = [] - batch_range = range(0, len(dataset.get_session(session_id)), batch_size) - if len(batch_range) < 2: - raise ValueError( - "Not enough data to perform the batched transform. Please provide a larger dataset or reduce the batch size." - ) - for batch_start in batch_range: - batch_end = min(batch_start + batch_size, - len(dataset.get_session(session_id))) - - if batch_start == batch_range[-2]: # one before last batch - last_start = batch_start - continue - if batch_start == batch_range[-1]: # last batch, likely incomplete - batch_start = last_start - batch_end = len(dataset.get_session(session_id)) - - # Sample indices from all sessions aligned to the target session - refs_idx_batch = loader.sampler.sample_all_sessions( - ref_idx=torch.arange(batch_start, batch_end), - session_id=session_id).to(transform_device) - - # Concatenate data across sessions - refs_data_batch = torch.cat([ - session[refs_idx_batch[s_id].cpu()] - for s_id, session in enumerate(dataset.iter_sessions()) - ], dim=1).squeeze() - - if len(self.model.get_offset()) < 2 and pad_before_transform: - pad_before_transform = False - - self.model.eval() - # Get embedding with the specified split_outputs setting - embedding = self._transform(model=self.model, - inputs=refs_data_batch, - pad_before_transform=pad_before_transform, - offset=self.model.get_offset(), - batch_size=batch_size) - refs_data_batch_embeddings.append(embedding) - - - # Reset split_outputs to True for subsequent training - self.model.set_split_outputs(True) - - if split_outputs: - # If split_outputs was True, we have tuples of embeddings - # Stack them across batches per objective - num_objectives = len(refs_data_batch_embeddings[0]) - return tuple(torch.cat([batch[i] for batch in refs_data_batch_embeddings], dim=0) - for i in range(num_objectives)) - else: - # If split_outputs was False, we have concatenated tensors - return torch.cat(refs_data_batch_embeddings, dim=0) - - - def get_aligned_data(self, - inputs, - labels, - start: int, - end: int, - session_id: Optional[int] = None, - random_ties: bool = True) -> torch.Tensor: - """Get data aligned across sessions for the specified session ID and index range. - - Args: - inputs: List of input tensors, one per session. - labels: List of label tensors, one per session. - start: Start index for the target session. - end: End index for the target session. - session_id: The target session ID to align to. - random_ties: Break nearest-label ties uniformly at random (``UnifiedSampler.random_ties``). - Default ``True``; ``False`` restores the legacy first-tie behaviour. - - Returns: - A tensor of data aligned across sessions for the specified session ID and index range. - """ - - # Build a unified dataset for sampling context - dataset = cebra.data.UnifiedDataset( - cebra.data.TensorDataset( - inputs[i], continuous=labels[i], offset=cebra.data.Offset(0, 1)) - for i in range(len(inputs))).to(self.device) - - # Use UnifiedLoader for sampling - loader = cebra.data.UnifiedLoader(dataset, num_steps=1) - loader.sampler.random_ties = bool(random_ties) - - # Sample indices from all sessions aligned to the target session - refs_idx_batch = loader.sampler.sample_all_sessions( - ref_idx=torch.arange(start, end), - session_id=session_id).to(self.device) - - # Concatenate data across sessions - refs_data_batch = torch.cat([ - session[refs_idx_batch[s_id].cpu()] - for s_id, session in enumerate(dataset.iter_sessions()) - ], dim=1).squeeze() - - return refs_data_batch \ No newline at end of file diff --git a/cebra/solver/unified_session.py b/cebra/solver/unified_session.py index 29bee7e6..a23fe6b2 100644 --- a/cebra/solver/unified_session.py +++ b/cebra/solver/unified_session.py @@ -54,11 +54,222 @@ import cebra.models import cebra.solver.base as abc_ from cebra.solver import register +from cebra.solver.multiobjective import MultiobjectiveSolverBase + + +def _check_sessions(inputs, labels, session_id): + """Check that inputs and labels have the same sessions and that ``session_id`` exists.""" + num_sessions = len(inputs) + if len(labels) != num_sessions: + raise ValueError( + f"Got {num_sessions} sessions of inputs but {len(labels)} of labels." + ) + if not 0 <= session_id < num_sessions: + raise ValueError( + f"Invalid session_id {session_id}: must be between 0 and {num_sessions - 1}." + ) + + +def _build_aligned_indices(inputs: List[torch.Tensor], + labels: List[torch.Tensor], + session_id: int, + indices=None, + random_ties: bool = False, + seed: Optional[int] = 0) -> torch.Tensor: + """Indices of the samples matched to the reference samples of one session. + + In every other session, the sample with the nearest auxiliary label is chosen. Only indices + are returned; :py:func:`_gather_aligned_inputs` builds the model input from them. + + Args: + inputs: Neural data of each session, ``(T_s, N_s)``. + labels: Auxiliary variables of each session, ``(T_s, d)``, shared label space. + session_id: Reference session. + indices: Samples of the reference session, ``(T,)`` integers. ``None``: the whole session. + random_ties: Break nearest-label ties uniformly at random, otherwise take the first one. + seed: Seed of the tie draws. The default 0 gives the same draws in every + call (``transform``, ``aligned_inputs``, ``feature_attribution_map``); keep the same + seed in all of them. ``None`` is only allowed with ``random_ties=False``. + + Returns: + Long tensor ``(num_sessions, len(indices))`` on CPU; row ``s`` holds the sample of + session ``s`` matched to each reference sample (row ``session_id`` is ``indices``). + """ + _check_sessions(inputs, labels, session_id) + num_sessions = len(inputs) + if indices is None: + indices = torch.arange(len(inputs[session_id])) + indices = torch.as_tensor(indices, dtype=torch.long).cpu().reshape(-1) + + # Always built on CPU: the draws and the distance computations are device independent. + # The neural data is not used by the search: zero-width placeholders avoid copying it. + dataset = cebra.data.UnifiedDataset(*[ + cebra.data.TensorDataset(torch.empty(len(labels[i]), 0), + continuous=torch.as_tensor(labels[i]).cpu(), + offset=cebra.data.Offset(0, 1), + device="cpu") for i in range(num_sessions) + ]) + sampler = cebra.distributions.UnifiedSampler(dataset, + time_offset=1, + device="cpu", + random_ties=bool(random_ties)) + if random_ties and seed is None: + raise ValueError( + "random_ties=True needs a seed, so that the embedding and the attribution map use " + "the same tie draws. Pass the same seed to transform and feature_attribution_map " + "(default 0).") + generator = None if seed is None else torch.Generator().manual_seed( + int(seed)) + return sampler.sample_all_sessions(ref_idx=indices, + session_id=session_id, + generator=generator).cpu().long() + + +def _gather_aligned_inputs(inputs: List[torch.Tensor], + aligned_indices: torch.Tensor, + rows=None, + device=None) -> torch.Tensor: + """Model input of the unified model for the given aligned indices. + + Args: + inputs: Neural data of each session, ``(T_s, N_s)``. + aligned_indices: Output of :py:func:`_build_aligned_indices`, ``(num_sessions, T)``. + rows: Columns of ``aligned_indices`` to gather. ``None``: all of them. + device: Device of the output. Default: device of the first input. + + Returns: + Tensor ``(len(rows), sum_s N_s)``: the channels of all sessions, concatenated. + """ + idx = aligned_indices if rows is None else aligned_indices[:, rows] + if device is None: + device = torch.as_tensor(inputs[0]).device + out = torch.empty(idx.shape[1], + sum(x.shape[1] for x in inputs), + dtype=torch.float32, + device=device) + start = 0 + for s, x in enumerate(inputs): + x = torch.as_tensor(x) + out[:, start:start + x.shape[1]] = x[idx[s].to( + x.device)].float().to(device) + start += x.shape[1] + return out + + +class _AlignedInputsMixin: + """Shared aligned-input building and whole-session transform of the unified solvers.""" + + def aligned_inputs(self, + inputs: List[torch.Tensor], + labels: List[torch.Tensor], + session_id: int, + indices=None, + random_ties: bool = False, + seed: Optional[int] = 0) -> torch.Tensor: + """Model input of the unified model for the reference samples of one session. + + In every other session, the sample with the nearest auxiliary label (squared Euclidean + distance; one-hot encode discrete labels) is chosen, and the channels of all sessions are + concatenated. + + Args: + inputs: Neural data of each session, ``(T_s, N_s)``. + labels: Auxiliary variables of each session, ``(T_s, d)``, same ``d`` for all. + session_id: Reference session. + indices: Samples of the reference session, ``(T,)`` integers. ``None``: all of them. + random_ties: Draw one of several equally near samples at random instead of taking + the first. Training uses ``True``. + seed: Seed of the tie draws. The default 0 gives the same draws in every + call (``transform``, ``aligned_inputs``, ``feature_attribution_map``); keep the same + seed in all of them. ``None`` is only allowed with ``random_ties=False``. + + Returns: + Tensor ``(T, sum_s N_s)`` on the model device. + + Example: + >>> import torch + >>> import cebra + >>> inputs = [torch.rand(50, 3), torch.rand(60, 5)] + >>> labels = [torch.rand(50, 2), torch.rand(60, 2)] + >>> model = cebra.models.init("offset1-model", num_neurons=8, num_units=16, + ... num_output=4) + >>> solver = cebra.solver.UnifiedSolver(model=model, + ... criterion=cebra.models.InfoNCE(), + ... optimizer=torch.optim.Adam(model.parameters())) + >>> x = solver.aligned_inputs(inputs, labels, session_id=0, indices=[0, 1, 2], + ... random_ties=True, seed=0) + >>> tuple(x.shape) + (3, 8) + """ + idx = _build_aligned_indices(inputs, + labels, + session_id, + indices=indices, + random_ties=random_ties, + seed=seed) + return _gather_aligned_inputs(inputs, + idx, + device=next( + self.model.parameters()).device) + + def _transform_session(self, inputs, labels, pad_before_transform, + session_id, batch_size, random_ties, seed): + """Align the sessions on ``session_id`` and embed the session batch by batch. + + The matches are computed once; each batch of ``batch_size`` output rows is then gathered + with the context of the receptive field, so the result does not depend on ``batch_size``. + Arguments are those of :py:meth:`UnifiedSolver.transform`. + + Returns: + Tensor ``(T, output_dimension)`` (``T - len(offset) + 1`` rows without padding) + on the model device. + """ + if not isinstance(inputs, list): + raise ValueError( + f"Inputs to transform() should be a list, not {type(inputs)}.") + self._check_is_fitted() + if session_id is None: + raise ValueError("Session ID is required for multi-session models.") + + aligned_idx = _build_aligned_indices(inputs, + labels, + session_id, + random_ties=random_ties, + seed=seed) + device = next(self.model.parameters()).device + offset = self.model.get_offset() + num_samples = aligned_idx.shape[1] + if pad_before_transform: + targets = torch.arange(num_samples) + else: + targets = torch.arange( + offset.left, max(offset.left, num_samples - offset.right + 1)) + if len(targets) == 0: + raise ValueError( + f"Session {session_id} has {num_samples} samples, fewer than the " + f"receptive field of the model ({len(offset)}).") + if batch_size is None: + batch_size = len(targets) + window = torch.arange(-offset.left, offset.right) + + self.model.eval() + outputs = [] + for start in range(0, len(targets), batch_size): + t = targets[start:start + batch_size] + # input rows of the batch: its first window to its last one, edges repeated + rows = torch.arange(t[0] + window[0], t[-1] + window[-1] + 1) + rows = rows.clamp(0, num_samples - 1) + batch = _gather_aligned_inputs(inputs, + aligned_idx, + rows=rows, + device=device) + outputs.append(abc_._inference_transform(self.model, batch)) + return torch.cat(outputs, dim=0) @register("unified-session") @dataclasses.dataclass -class UnifiedSolver(abc_.Solver): +class UnifiedSolver(_AlignedInputsMixin, abc_.Solver): """Multi session training, considering a single model for all sessions.""" _variant_name = "unified-session" @@ -196,94 +407,49 @@ def transform(self, pad_before_transform: bool = True, session_id: Optional[int] = None, batch_size: Optional[int] = 512, - random_ties: bool = True) -> torch.Tensor: - """Compute the embedding for the `session_id`th session of the dataset. + random_ties: bool = False, + seed: Optional[int] = 0) -> torch.Tensor: + """Compute the embedding of session ``session_id``. - Note: - Compared to the other :py:class:`cebra.solver.base.Solver`, we need all the sessions of - the dataset to transform the data, as the sampling is across all the sessions. + The other sessions are aligned on ``session_id`` (see :py:meth:`aligned_inputs`), then + the session is embedded in batches. Each batch keeps its real neighbouring samples, so + the result does not depend on ``batch_size``. Args: - inputs: The input signal for all sessions. - labels: The auxiliary variables to use for sampling. - session_id: The session ID, an :py:class:`int` between 0 and - the number of sessions -1. - batch_size: If not None, batched inference will be applied. - random_ties: Break nearest-label ties uniformly at random when aligning the other - sessions (``UnifiedSampler.random_ties``). Default ``True``; - ``False`` restores the legacy first-tie behaviour. - - Note: - The ``session_id`` is needed in order to sample the corresponding number of samples and - return an embedding of the expected shape. - - Note: - The batched inference will be required in most cases. Default is set to ``100`` for that reason. + inputs: Neural data of all sessions, ``(T_s, N_s)``. + labels: Auxiliary variables of all sessions, ``(T_s, d)``, used for the alignment. + pad_before_transform: Pad the session edges by replication, so that the output has + one row per sample. + session_id: Session to embed, between 0 and the number of sessions - 1. + batch_size: Output rows per forward pass. ``None``: the whole session at once. + random_ties: Break nearest-label ties at random instead of taking the first. + Training uses ``True``. + seed: Seed of the tie draws. The default 0 gives the same draws in every + call (``transform``, ``aligned_inputs``, ``feature_attribution_map``); keep the same + seed in all of them. ``None`` is only allowed with ``random_ties=False``. Returns: - The output embedding for the session corresponding to the provided ID `session_id`. The shape - is (num_samples(session_id), output_dimension)``. - + The embedding ``(T, output_dimension)``, with ``T - len(offset) + 1`` rows without + padding. + + Example: + >>> import torch + >>> import cebra + >>> inputs = [torch.rand(50, 3), torch.rand(60, 5)] + >>> labels = [torch.rand(50, 2), torch.rand(60, 2)] + >>> model = cebra.models.init("offset1-model", num_neurons=8, num_units=16, + ... num_output=4) + >>> solver = cebra.solver.UnifiedSolver(model=model, + ... criterion=cebra.models.InfoNCE(), + ... optimizer=torch.optim.Adam(model.parameters())) + >>> solver.n_features, solver.num_sessions = 8, 2 # set by ``fit`` normally + >>> emb = solver.transform(inputs, labels, session_id=1, random_ties=True, seed=0) + >>> tuple(emb.shape) + (60, 4) """ - if not isinstance(inputs, list): - raise ValueError( - f"Inputs to transform() should be a list, not {type(inputs)}.") - - self._check_is_fitted() - - if session_id is None: - raise ValueError("Session ID is required for multi-session models.") - - # Sampling according to session_id required - dataset = cebra.data.UnifiedDataset( - cebra.data.TensorDataset( - inputs[i], continuous=labels[i], offset=cebra.data.Offset(0, 1)) - for i in range(len(inputs))).to(self.device) - - # Only used to sample the reference samples - loader = cebra.data.UnifiedLoader(dataset, num_steps=1) - loader.sampler.random_ties = bool(random_ties) - - # Sampling in batch - refs_data_batch_embeddings = [] - batch_range = range(0, len(dataset.get_session(session_id)), batch_size) - if len(batch_range) < 2: - raise ValueError( - "Not enough data to perform the batched transform. Please provide a larger dataset or reduce the batch size." - ) - for batch_start in batch_range: - batch_end = min(batch_start + batch_size, - len(dataset.get_session(session_id))) - - if batch_start == batch_range[-2]: # one before last batch - last_start = batch_start - continue - if batch_start == batch_range[-1]: # last batch, likely incomplete - batch_start = last_start - batch_end = len(dataset.get_session(session_id)) - - refs_idx_batch = loader.sampler.sample_all_sessions( - ref_idx=torch.arange(batch_start, batch_end), - session_id=session_id).to(self.device) - - refs_data_batch = torch.cat([ - session[refs_idx_batch[session_id]] - for session_id, session in enumerate(dataset.iter_sessions()) - ], - dim=1).squeeze() - - if len(self.model.get_offset()) < 2 and pad_before_transform: - pad_before_transform = False - - self.model.eval() - refs_data_batch_embeddings.append( - self._transform(model=self.model, - inputs=refs_data_batch, - pad_before_transform=pad_before_transform, - offset=self.model.get_offset(), - batch_size=batch_size)) - - return torch.cat(refs_data_batch_embeddings, dim=0) + return self._transform_session(inputs, labels, pad_before_transform, + session_id, batch_size, random_ties, + seed) @torch.no_grad() def decoding(self, @@ -385,3 +551,209 @@ def decoding(self, return np.array(train_scores).mean() else: return np.array(train_scores).mean(), np.array(valid_scores).mean() + + +@register("unified-multiobjective-solver", + deprecated=True) # NOTE: earlier name, kept for compatibility +@register("unified-xcebra") +@dataclasses.dataclass +class UnifiedSolverxCEBRA(_AlignedInputsMixin, MultiobjectiveSolverBase): + """Unified CEBRA solver with Jacobian regularization (unified xCEBRA). + + Trains one model shared by all sessions, like :py:class:`~cebra.solver.unified_session.UnifiedSolver`, + and adds the Jacobian regularization of xCEBRA + (:py:class:`~cebra.models.jacobian_regularizer.JacobianReg`, passed as ``regularizer``, with its + weight set over training by ``scheduler_regularizer`` in :py:meth:`fit`). It builds on the + multi-objective solver only because that solver supports the regularizer. + + Unified xCEBRA uses a single objective: one slice covering the whole embedding, with a + contrastive loss on the auxiliary variables, set with + :py:class:`~cebra.solver.multiobjective.MultiObjectiveConfig` (one ``set_slice`` / + ``set_loss`` / ``set_distribution`` / ``push``). Several slices (subspaces) are accepted by + the code but have not been used or validated with the unified sampler. + + Takes batches from :py:class:`~cebra.data.multiobjective.UnifiedContrastiveMultiObjectiveLoader`, + in which the samples of all sessions are already aligned and concatenated. + + Example: + >>> # loader: a UnifiedContrastiveMultiObjectiveLoader over the unified dataset + >>> config = cebra.solver.MultiObjectiveConfig(loader) # doctest: +SKIP + >>> config.set_slice(0, 128) # one objective: the whole embedding # doctest: +SKIP + >>> config.set_loss("FixedCosineInfoNCE", temperature=1.0) # doctest: +SKIP + >>> config.set_distribution("unified_time_delta", time_delta=10) # doctest: +SKIP + >>> config.push(); config.finalize() # doctest: +SKIP + >>> solver = cebra.solver.init("unified-xcebra", model=model, + ... feature_ranges=config.feature_ranges, criterion=config.criterion, + ... regularizer=cebra.models.jacobian_regularizer.JacobianReg(), + ... renormalize=True, use_sam=False, optimizer=optimizer) # doctest: +SKIP + >>> solver.fit(loader, scheduler_regularizer=weight_scheduler) # doctest: +SKIP + + See Also: + :py:class:`cebra.data.multiobjective.UnifiedContrastiveMultiObjectiveLoader` + :py:class:`cebra.solver.multiobjective.MultiObjectiveConfig` + :py:class:`cebra.models.multicriterions.MultiCriterions` + """ + + _variant_name = "unified-xcebra" + + def _set_fitted_params(self, loader: cebra.data.Loader): + """Set parameters once the solver is fitted for unified multiobjective training. + + For unified training, num_sessions is the number of sessions in the unified dataset, + and n_features is the total concatenated feature dimension across all sessions. + + Args: + loader: Loader used to fit the solver. + """ + self.num_sessions = loader.dataset.num_sessions + self.n_features = loader.dataset.input_dimension + + def _check_is_inputs_valid(self, + inputs: Optional[List[torch.Tensor]], + session_id: Optional[int] = None): + """Check that the inputs can be inferred using the unified model. + + For unified training, inputs should be a list of per-session tensors, + and the concatenated feature dimension must match the model's input dimension. + + Args: + inputs: List of input tensors, one per session. Each has shape + (n_samples, num_features_session, ...). + session_id: The target session ID (required for unified models). + """ + if inputs is None: + return + + if isinstance(inputs, list): + inputs_shape = 0 + for i in range(len(inputs)): + inputs_shape += inputs[i].shape[1] + elif isinstance(inputs, torch.Tensor): + raise NotImplementedError( + "Unified models require a list of per-session tensors, not a single tensor." + ) + else: + raise NotImplementedError( + f"Invalid input type: {type(inputs)}. Expected list of tensors." + ) + + if self.n_features != inputs_shape: + raise ValueError( + f"Invalid input shape: model requires an input of shape " + f"(n_samples, {self.n_features}), but got total feature dimension " + f"(n_samples, {inputs_shape}) from concatenated sessions.") + + def _check_is_session_id_valid( + self, + session_id: Optional[int] = None, + ): + """Check that the session ID provided is valid for the unified solver. + + The session ID must be non-null and between 0 and the number of sessions. + + Args: + session_id: The session ID to check. + """ + if session_id is None: + raise RuntimeError( + "No session_id provided: unified multiobjective model requires a session_id " + "as the target session to use to align the sessions.") + if session_id >= self.num_sessions or session_id < 0: + raise RuntimeError( + f"Invalid session_id {session_id}: session_id for the current unified model " + f"must be between 0 and {self.num_sessions-1}.") + + def _get_model(self, session_id: Optional[int] = None): + """Get the unified model (independent of session_id). + + For unified models, there is only one shared model regardless of session. + The session_id is still validated but not used for model selection. + + Args: + session_id: The session ID, required for validation. + + Returns: + The shared unified model. + """ + self._check_is_session_id_valid(session_id=session_id) + self._check_is_fitted() + return self.model + + def _inference(self, batch: cebra.data.Batch) -> cebra.data.Batch: + """Compute predictions for unified multiobjective batch. + + For unified batches, reference, positive, and negative samples are already + aligned across sessions (concatenated along the neuron dimension). We apply + the single model to each and return per-objective prediction batches. + + Args: + batch: A Batch with reference, positive (list), and negative tensors + already unified across sessions. + + Returns: + A list of Batch objects, one per objective, with model predictions. + """ + pred_refs = self.model(batch.reference) + pred_negs = self.model(batch.negative) + + prediction_batches = [] + for i, positive in enumerate(batch.positive): + pred_pos = self.model(positive) + prediction_batches.append( + cebra.data.Batch(reference=pred_refs[i].unsqueeze(0).view( + -1, pred_refs[i].shape[-1]), + positive=pred_pos[i].unsqueeze(0).view( + -1, pred_pos[i].shape[-1]), + negative=pred_negs[i].unsqueeze(0).view( + -1, pred_negs[i].shape[-1]))) + + return prediction_batches + + @torch.no_grad() + def transform(self, + inputs: List[torch.Tensor], + labels: List[torch.Tensor], + pad_before_transform: bool = True, + session_id: Optional[int] = None, + batch_size: Optional[int] = 512, + random_ties: bool = False, + seed: Optional[int] = 0) -> torch.Tensor: + """Compute the embedding of session ``session_id``. + + Same as :py:meth:`UnifiedSolver.transform`. The model is run with ``split_outputs`` + off (its training mode returns one output per slice) and its mode is restored + afterwards, also if an error is raised. + + Args: + inputs: Neural data of all sessions, ``(T_s, N_s)``. + labels: Auxiliary variables of all sessions, ``(T_s, d)``, used for the alignment. + pad_before_transform: Pad the session edges by replication, so that the output has + one row per sample. + session_id: Session to embed. Required. + batch_size: Output rows per forward pass. ``None``: the whole session at once. + random_ties: Break nearest-label ties at random instead of taking the first. + Training uses ``True``. + seed: Seed of the tie draws. The default 0 gives the same draws in every + call (``transform``, ``aligned_inputs``, ``feature_attribution_map``); keep the same + seed in all of them. ``None`` is only allowed with ``random_ties=False``. + + Returns: + The embedding ``(T, output_dimension)``. + + Example: + >>> # ``solver`` is a fitted UnifiedSolverxCEBRA, ``inputs``/``labels`` + >>> # the lists of per-session neural data and auxiliary variables + >>> emb = solver.transform(inputs, labels, session_id=0) # doctest: +SKIP + >>> emb = solver.transform(inputs, labels, session_id=0, + ... random_ties=True, seed=0) # doctest: +SKIP + """ + previous = self.model.split_outputs + try: + # Training runs the model with one output per slice (one per loss); + # inference needs the single concatenated embedding. + self.model.set_split_outputs(False) + return self._transform_session(inputs, labels, pad_before_transform, + session_id, batch_size, random_ties, + seed) + finally: + self.model.set_split_outputs(previous) diff --git a/docs/source/api/pytorch/attribution.rst b/docs/source/api/pytorch/attribution.rst index 6efb043f..b5bb550f 100644 --- a/docs/source/api/pytorch/attribution.rst +++ b/docs/source/api/pytorch/attribution.rst @@ -19,3 +19,10 @@ Jacobian-based attribution .. automodule:: cebra.attribution.jacobian_attribution :members: :show-inheritance: + +Feature maps +------------ + +.. automodule:: cebra.attribution.feature_map + :members: + :show-inheritance: diff --git a/docs/source/api/pytorch/solvers.rst b/docs/source/api/pytorch/solvers.rst index f2a5dd6d..1b14c8e4 100644 --- a/docs/source/api/pytorch/solvers.rst +++ b/docs/source/api/pytorch/solvers.rst @@ -28,6 +28,10 @@ Multi session training Unified session training ------------------------ +:py:class:`~cebra.solver.unified_session.UnifiedSolver` trains one model shared by all sessions; +:py:class:`~cebra.solver.unified_session.UnifiedSolverxCEBRA` adds the Jacobian regularization of +xCEBRA (registered as ``"unified-xcebra"``). + .. automodule:: cebra.solver.unified_session :members: :show-inheritance: diff --git a/tests/test_distributions.py b/tests/test_distributions.py index 20e1fee3..8e012c9c 100644 --- a/tests/test_distributions.py +++ b/tests/test_distributions.py @@ -32,6 +32,9 @@ import cebra.distributions.base as cebra_distr_base +# ---- helpers ---- + + def assert_is_tensor(T, device=None): assert isinstance(T, torch.Tensor) if device is not None: @@ -51,6 +54,9 @@ def prepare(N=1000, n=128, d=5, probs=[0.3, 0.1, 0.6], device="cpu"): return discrete, continuous +# ---- indices and distance matrices ---- + + def test_init_discrete(): discrete, continuous = prepare() @@ -94,6 +100,9 @@ def test_init_index(): assert torch.eq(b, torch.arange(10)).all() +# ---- mixed distributions ---- + + class _TestMixedBase: @functools.cached_property @@ -188,6 +197,9 @@ def test_mixed(): assert not torch.eq(samples_both, reference_idx).all() +# ---- continuous and discrete indices ---- + + def test_continuous(benchmark): discrete, continuous = prepare() @@ -231,6 +243,9 @@ def test_discrete_uniform_discrete(): np.bincount(resample_emp) / N, np.array([0.2969, 0.098, 0.6051])) +# ---- single-session samplers ---- + + @pytest.mark.parametrize("time_offset", [1, 5, 10]) def test_single_session_time_contrastive(time_offset): """Single session time-contrastive learning. @@ -277,6 +292,9 @@ def test_single_session_discrete(): pass +# ---- multi-session samplers ---- + + def test_multi_session_time_delta(): pass @@ -324,6 +342,9 @@ def test_multi_session_discrete(): assert (sample_labels == positive_labels).all() +# ---- delta distributions ---- + + class OldDeltaDistribution(cebra_distr_base.JointDistribution, cebra_distr_base.HasGenerator): """ @@ -414,6 +435,9 @@ def test_new_delta_normal_with_multidimensional_index(delta, numerical_check): "given parameters. TODO: Add a warning message for these cases.") +# ---- unified sampler ---- + + @pytest.mark.parametrize("time_offset", [1, 5, 10]) def test_unified_distribution(time_offset): dataset = cebra_datasets.init("demo-continuous-unified") @@ -474,3 +498,115 @@ def test_unified_sampler_random_ties_uses_every_repeat(set_after_init): ref_frame = ref[0] % n_frames for s in range(1, ref.shape[0]): assert torch.equal(labels[ref[s]], labels[ref_frame]) + + +# ---- unified sampler: nearest-label search (distinct labels, random ties) ---- + + +def _tied_sessions( + lengths=(60, 90, 75), n_channels=(3, 4, 5), n_frames=15, seed=0): + """Sessions whose labels repeat exactly (ties), as in repeated stimulus presentations.""" + gen = torch.Generator().manual_seed(seed) + base = torch.randn(n_frames, 2, generator=gen) + inputs, labels = [], [] + for length, n in zip(lengths, n_channels): + reps = -(-length // n_frames) + labels.append(base.repeat(reps, 1)[:length].clone()) + inputs.append(torch.randn(length, n, generator=gen)) + return inputs, labels + + +def _unified_sampler(labels, **kwargs): + inputs = [torch.zeros(len(x), 1) for x in labels] + dataset = cebra.data.UnifiedDataset(*[ + cebra.data.TensorDataset(i, continuous=l) + for i, l in zip(inputs, labels) + ]) + return cebra_distr.UnifiedSampler(dataset, time_offset=1, **kwargs) + + +def _brute(sampler, session_id, query): + """Full row-by-row distance matrix and tie mask (reference implementation).""" + dm = sampler.index[session_id].dist_matrix + distance = dm(query) + dmin = distance.min(dim=0, keepdim=True).values + tied = distance <= dmin + sampler.tie_rtol * dmin.abs().clamp_min(1.0) + return distance, tied + + +def _dup_labels(seed=0, n=120, n_unique=12, near=3): + gen = torch.Generator().manual_seed(seed) + base = torch.randn(n_unique, 4, generator=gen) + labels = base[torch.randint(n_unique, (n, ), generator=gen)].clone() + # near-duplicates: tiny perturbations, within tie_rtol of their source label + idx = torch.randperm(n, generator=gen)[:near] + labels[idx] += 1e-9 + return labels, base + + +@pytest.mark.parametrize("duplicates", [True, False]) +def test_search_unique_labels_matches_brute_force(duplicates): + if duplicates: + labels, base = _dup_labels() + query = torch.cat([base, base[:5] + 0.3, torch.randn(10, 4)]) + query = query[torch.randint(len(query), (200, ))] + else: + labels = torch.randn(80, 4) + query = torch.randn(50, 4) + sampler = _unified_sampler([labels, labels[:30]], random_ties=False) + # distinct labels are only used when they are at most half of the rows + num_labels = len(sampler._unique_labels(0)[2]) + assert num_labels == (12 if duplicates else len(labels)) + distance, tied = _brute(sampler, 0, query) + # first tie: exactly argmin over all rows + assert torch.equal(sampler._search(0, query), distance.argmin(dim=0)) + # random ties: always in the tie set, chunk size invariant, seed deterministic + sampler.random_ties = True + ref = sampler._search(0, query, torch.Generator().manual_seed(3)) + assert tied[ref, torch.arange(len(query))].all() + for chunk_rows in (1, 7, 1000): + sampler.max_search_elements = chunk_rows * len(labels) + out = sampler._search(0, query, torch.Generator().manual_seed(3)) + assert torch.equal(out, ref) + sampler.max_search_elements = 2**24 + # same u as the brute-force rank rule: identical draws + u = torch.rand(len(query), generator=torch.Generator().manual_seed(3)) + k = tied.sum(0) + rank = (u * k).floor().long().clamp_max(k - 1) + expected = (tied.cumsum(0) <= rank[None]).sum(0) + assert torch.equal(ref, expected) + # very small distance blocks (unique-query sub-chunks) give the same result + sampler.max_search_elements = 3 * len(labels) + assert torch.equal( + sampler._search(0, query, + torch.Generator().manual_seed(3)), ref) + + +def test_search_unique_labels_uniform_over_tied_rows(): + labels, base = _dup_labels(near=0) + sampler = _unified_sampler([labels, labels[:30]], random_ties=True) + query = base[:1].repeat(6000, 1) + _, tied = _brute(sampler, 0, query[:1]) + tied_rows = tied[:, 0].nonzero().flatten() + out = sampler._search(0, query, torch.Generator().manual_seed(0)) + counts = torch.bincount(out, minlength=len(labels))[tied_rows].double() + assert counts.sum() == len(query) + expected = len(query) / len(tied_rows) + chi2 = ((counts - expected)**2 / expected).sum().item() + # df = len(tied_rows) - 1; 99.9th percentile is well below df + 5 * sqrt(2 df) + 20 + df = len(tied_rows) - 1 + assert chi2 < df + 5 * (2 * df)**0.5 + 20 + + +def test_sample_all_sessions_generator_argument(): + _, labels = _tied_sessions() + sampler = _unified_sampler(labels, random_ties=True) + ref = torch.arange(40) + a = sampler.sample_all_sessions(ref, + 0, + generator=torch.Generator().manual_seed(5)) + b = sampler.sample_all_sessions(ref, + 0, + generator=torch.Generator().manual_seed(5)) + torch.testing.assert_close(a, b) + torch.testing.assert_close(a[0], ref) diff --git a/tests/test_feature_map.py b/tests/test_feature_map.py new file mode 100644 index 00000000..c58e8378 --- /dev/null +++ b/tests/test_feature_map.py @@ -0,0 +1,571 @@ +"""Tests for :py:mod:`cebra.attribution.feature_map`: readout, feature attribution maps and helpers.""" +import numpy as np +import pytest +import torch + +import cebra.attribution +import cebra.data +import cebra.models +import cebra.solver +from cebra.attribution import feature_map +from cebra.models import Model +from cebra.models.multiobjective import \ + SubspaceMultiobjectiveConvolutionalModel + + +@pytest.mark.filterwarnings("ignore:The readout is fitted on every row") +def test_fit_feature_readout_recovers_weights(): + rng = np.random.default_rng(0) + T, D, F = 200, 6, 3 + embedding = rng.normal(size=(T, D)) + W_true = rng.normal(size=(D, F)) + features = embedding @ W_true # noiseless, no intercept + + rows = np.arange(T) + W = feature_map.fit_feature_readout(embedding, + features, + alpha=1e-8, + train_index=rows) + assert W.shape == (D, F) + np.testing.assert_allclose(W, W_true, atol=1e-4) + + # 1-d features are one feature + W_1d = feature_map.fit_feature_readout(embedding, + features[:, 0], + alpha=1e-8, + train_index=rows) + assert W_1d.shape == (D, 1) + + with pytest.raises(ValueError): + feature_map.fit_feature_readout(embedding[:-1], + features, + train_fraction=0.5) + + +def test_fit_feature_readout_train_fraction_and_index(): + from sklearn.linear_model import Ridge + + rng = np.random.default_rng(1) + T, D, F = 50, 4, 2 + embedding = rng.normal(size=(T, D)) + features = rng.normal(size=(T, F)) + n_train = 45 # round(50 * 0.9) + + ref = Ridge(alpha=2.0).fit(embedding[:n_train], features[:n_train]).coef_.T + W_frac = feature_map.fit_feature_readout(embedding, + features, + alpha=2.0, + train_fraction=0.9) + W_idx = feature_map.fit_feature_readout(embedding, + features, + alpha=2.0, + train_index=np.arange(n_train)) + mask = np.arange(T) < n_train + W_mask = feature_map.fit_feature_readout(embedding, + features, + alpha=2.0, + train_index=mask) + for W in (W_frac, W_idx, W_mask): + np.testing.assert_allclose(W, ref, atol=1e-10) + + # Rows outside the training subset do not influence the fit + garbage = embedding.copy() + garbage[n_train:] = 1e3 * rng.normal(size=(T - n_train, D)) + W_garbage = feature_map.fit_feature_readout(garbage, + features, + alpha=2.0, + train_fraction=0.9) + np.testing.assert_allclose(W_garbage, ref, atol=1e-10) + + # every row selected (train_fraction=1.0, or a train_index covering all rows, also with + # duplicates or as a full mask): fitted, with a warning that nothing is held out + all_rows = Ridge(alpha=2.0).fit(embedding, features).coef_.T + for kw in (dict(train_fraction=1.0), dict(train_index=np.arange(T)), + dict(train_index=np.ones(T, dtype=bool))): + with pytest.warns(UserWarning, match="no row is held out"): + W_all = feature_map.fit_feature_readout(embedding, + features, + alpha=2.0, + **kw) + np.testing.assert_allclose(W_all, all_rows, atol=1e-10) + + +def test_fit_feature_readout_default_first_80_percent(capsys): + from sklearn.linear_model import Ridge + + rng = np.random.default_rng(3) + embedding = rng.normal(size=(50, 4)) + features = rng.normal(size=(50, 2)) + W = feature_map.fit_feature_readout(embedding, features, alpha=2.0) + ref = Ridge(alpha=2.0).fit(embedding[:40], features[:40]).coef_.T + np.testing.assert_allclose(W, ref, atol=1e-10) + assert "first 80% of rows" in capsys.readouterr().out + + # an explicit choice prints nothing + feature_map.fit_feature_readout(embedding, features, train_fraction=0.5) + feature_map.fit_feature_readout(embedding, + features, + train_index=np.arange(10)) + assert capsys.readouterr().out == "" + + +def test_fit_feature_readout_subset_errors(): + rng = np.random.default_rng(2) + embedding = rng.normal(size=(20, 3)) + features = rng.normal(size=(20, 2)) + with pytest.raises(ValueError, match="not both"): + feature_map.fit_feature_readout(embedding, + features, + train_fraction=0.5, + train_index=np.arange(5)) + with pytest.raises(ValueError, match="empty"): + feature_map.fit_feature_readout(embedding, + features, + train_index=np.array([], dtype=int)) + with pytest.raises(ValueError, match="empty"): + feature_map.fit_feature_readout(embedding, + features, + train_fraction=0.01) + with pytest.raises(ValueError): + feature_map.fit_feature_readout(embedding, + features, + train_index=np.zeros(7, dtype=bool)) + with pytest.raises(ValueError): + feature_map.fit_feature_readout(embedding, features, train_fraction=1.5) + + +class MLPEncoder(Model): + """Per-sample encoder without offset.""" + + def __init__(self, num_input, num_output): + super().__init__(num_input=num_input, num_output=num_output) + self.net = torch.nn.Sequential(torch.nn.Linear(num_input, 8), + torch.nn.Tanh(), + torch.nn.Linear(8, num_output)) + + def forward(self, x): + return self.net(x) + + def get_offset(self): + return None + + +def _regularized(model): + """Single-session solver trained with the Jacobian regularizer (not fitted here).""" + return cebra.solver.RegularizedSolver(model=model, + criterion=cebra.models.InfoNCE(), + optimizer=torch.optim.Adam( + model.parameters())) + + +def _two_session_dataset(n_time=40, n_neurons=(3, 5)): + # Session 0: labels cycle through 0..4 (repeated trials). Session 1: same labels, shuffled + # order, so the nearest-label match of every reference sample has several ties. + rng = np.random.default_rng(0) + labels = [torch.tensor(np.arange(n_time) % 5, dtype=torch.float32)[:, None]] + labels.append( + torch.tensor(rng.permutation(n_time) % 5, dtype=torch.float32)[:, None]) + assert all(int((labels[1] == v).sum()) > 1 for v in range(5)) # ties exist + inputs = [ + torch.arange(n_time * n, dtype=torch.float32).reshape(n_time, n) + for n in n_neurons + ] + datasets = [ + cebra.data.TensorDataset(inputs[i], + continuous=labels[i], + offset=cebra.data.Offset(0, 1)) + for i in range(2) + ] + return cebra.data.UnifiedDataset(*datasets), inputs, labels + + +class ConvTanhEncoder(cebra.models.Model, cebra.models.ConvolutionalModelMixin): + """Convolutional-offset encoder with a nonlinearity, so the Jacobian varies over time.""" + + def __init__(self, num_input, num_output, left=2, right=1): + super().__init__(num_input=num_input, num_output=num_output) + self.offset = cebra.data.Offset(left, right) + self.linear = torch.nn.Linear(num_input * (left + right), num_output) + + def forward(self, x): # x: (batch, N, L) + return torch.tanh(self.linear(0.01 * x.flatten(1))) + + def get_offset(self): + return self.offset + + +def test_num_valid_rows(): + """One output per window of left + right samples; per-sample models give one per sample.""" + model = ConvTanhEncoder(4, 3, left=2, right=1) # window of 3 samples + assert feature_map._num_valid_rows(model, 20) == 18 # outputs at samples 2..19 + assert feature_map._num_valid_rows(MLPEncoder(4, 3), 20) == 20 + + +def _reference_row_jacobian(model, neural, row): + """Autograd Jacobian of the embedding of one valid row, averaged over the window (D, N).""" + left, right = model.get_offset().left, model.get_offset().right + window = (neural[row:row + left + right].T.detach().clone() + ) # (N, L), model input layout + jac = torch.autograd.functional.jacobian(lambda w: model(w[None])[0], + window) + return jac.mean(-1).detach().double().numpy() # (D, N) + + +def test_per_row_maps_follow_model_window(): + # Row r is sample left + r, its window is neural[r : r + left + right] + torch.manual_seed(0) + rng = np.random.default_rng(3) + model = ConvTanhEncoder(num_input=4, num_output=5, left=2, right=1) + solver = _regularized(model) + neural = torch.randn(20, 4) + n_valid = 20 - 2 - 1 + 1 + W = rng.normal(size=(5, 2)) + + per_row = feature_map.feature_attribution_map(solver, + neural, + W, + average=False, + batch_size=7) + assert per_row.shape == (n_valid, 4, 2) + for row in range(n_valid): + expected = _reference_row_jacobian(model, neural, row).T @ W + np.testing.assert_allclose(per_row[row], expected, atol=1e-6) + + +def test_per_row_batch_size_invariance_and_mean(): + torch.manual_seed(0) + rng = np.random.default_rng(4) + model = ConvTanhEncoder(num_input=4, num_output=5, left=2, right=1) + solver = _regularized(model) + neural = torch.randn(40, 4) + W = rng.normal(size=(5, 2)) + + rows = { + b: + feature_map.feature_attribution_map(solver, + neural, + W, + average=False, + batch_size=b) for b in (1, 7, 64) + } + assert rows[1].shape == (38, 4, 2) + np.testing.assert_allclose(rows[1], rows[7], atol=1e-6) + np.testing.assert_allclose(rows[1], rows[64], atol=1e-6) + + mean = feature_map.feature_attribution_map(solver, neural, W, batch_size=7) + assert mean.shape == (4, 2) + np.testing.assert_allclose(mean, rows[7].mean(axis=0), atol=1e-6) + + +def test_single_session_output_slice_and_split_outputs(): + torch.manual_seed(2) + rng = np.random.default_rng(6) + module = ConvTanhEncoder(num_input=4, num_output=6, left=2, right=1) + model = SubspaceMultiobjectiveConvolutionalModel( + module, + feature_ranges=[slice(0, 3), slice(3, 6)], + renormalize=True, + split_outputs=True, + ) + solver = _regularized(model) + neural = torch.randn(30, 4) + n_valid = 30 - 2 - 1 + 1 + sl = slice(3, 6) + W_slice = rng.normal(size=(3, 3)) # readout on the embedding columns 3:6 + + # Reference: Jacobian of the wrapper's renormalised embedding (split_outputs off), rows 3:6 + model.split_outputs = False + expected = np.stack([ + _reference_row_jacobian(model, neural, row)[sl].T @ W_slice + for row in range(n_valid) + ]) + model.split_outputs = True + + per_row = feature_map.feature_attribution_map(solver, + neural, + W_slice, + output_slice=sl, + average=False, + batch_size=5) + np.testing.assert_allclose(per_row, expected, atol=1e-6) + mean = feature_map.feature_attribution_map(solver, + neural, + W_slice, + output_slice=sl) + np.testing.assert_allclose(mean, expected.mean(axis=0), atol=1e-6) + assert model.split_outputs is True + + +def test_single_session_readout_shape_check(): + rng = np.random.default_rng(7) + module = ConvTanhEncoder(num_input=4, num_output=6, left=2, right=1) + model = SubspaceMultiobjectiveConvolutionalModel( + module, + feature_ranges=[slice(0, 3), slice(3, 6)], + renormalize=True, + split_outputs=True, + ) + solver = _regularized(model) + neural = torch.randn(30, 4) + + # without output_slice, W must have all 6 output rows + feature_map.feature_attribution_map(solver, neural, rng.normal(size=(6, 2))) + with pytest.raises(ValueError, match="rows"): + feature_map.feature_attribution_map(solver, neural, + rng.normal(size=(3, 2))) + # with output_slice, W must have len(output_slice) rows + with pytest.raises(ValueError, match="rows"): + feature_map.feature_attribution_map(solver, + neural, + rng.normal(size=(6, 2)), + output_slice=slice(3, 6)) + with pytest.raises(ValueError): + feature_map.feature_attribution_map(solver, neural, np.ones(6)) + assert model.split_outputs is True + + +def _unified_solver(n_neurons=(3, 5), num_output=4): + model = ConvTanhEncoder(num_input=sum(n_neurons), + num_output=num_output, + left=2, + right=1) + return cebra.solver.UnifiedSolverxCEBRA( + model=model, + criterion=cebra.models.InfoNCE(), + optimizer=torch.optim.Adam(model.parameters()), + feature_ranges=[slice(0, num_output)], + regularizer=cebra.models.jacobian_regularizer.JacobianReg(), + renormalize=True) + + +def test_dispatch_unified_matches_aligned_inputs(): + torch.manual_seed(3) + _, inputs, labels = _two_session_dataset(n_time=40, n_neurons=(3, 5)) + solver = _unified_solver() + W = np.random.default_rng(7).normal(size=(4, 2)) + kwargs = dict(labels=labels, + session_id=0, + random_ties=True, + seed=1, + batch_size=9) + + mean = feature_map.feature_attribution_map(solver, inputs, W, **kwargs) + rows = feature_map.feature_attribution_map(solver, + inputs, + W, + average=False, + **kwargs) + assert mean.shape == (8, 2) + assert rows.shape == (38, 8, 2) # 40 - left - right + 1 + # the mean of the per-row maps == the averaged map == the map of the model on the aligned inputs + np.testing.assert_allclose(rows.mean(axis=0), mean, atol=1e-6) + aligned = solver.aligned_inputs(inputs, labels, 0, random_ties=True, seed=1) + ref = feature_map.feature_attribution_map(_regularized(solver.model), + aligned, + W, + batch_size=9) + np.testing.assert_allclose(mean, ref, atol=1e-6) + + # circular reference session: one row per reference sample + offset = solver.model.get_offset() + indices = torch.arange(-offset.left, + 40 + offset.right - 1) % 40 # window wraps around + wrapped = feature_map.feature_attribution_map(solver, + inputs, + W, + indices=indices, + average=False, + **{ + **kwargs, "batch_size": 64 + }) + assert wrapped.shape == (40, 8, 2) + + with pytest.raises(ValueError, match="labels"): + feature_map.feature_attribution_map(solver, inputs, W) + with pytest.raises(ValueError, match="session_id"): + feature_map.feature_attribution_map(solver, inputs, W, labels=labels) + with pytest.raises(ValueError, match="rows"): + feature_map.feature_attribution_map(solver, + inputs, + np.ones((5, 2)), + labels=labels, + session_id=0) + + +def test_dispatch_single_session_solver(): + torch.manual_seed(4) + model = ConvTanhEncoder(num_input=4, num_output=5, left=2, right=1) + solver = _regularized(model) + neural = torch.randn(20, 4) + W = np.random.default_rng(0).normal(size=(5, 2)) + + mean = feature_map.feature_attribution_map(solver, neural.numpy(), W) + assert mean.shape == (4, 2) + + # input samples can be selected with indices + sub = feature_map.feature_attribution_map(solver, + neural, + W, + indices=np.arange(10), + average=False) + assert sub.shape == (8, 4, 2) + + with pytest.raises(ValueError, match="unified"): + feature_map.feature_attribution_map(solver, neural, W, labels=[neural]) + with pytest.raises(ValueError, match="list"): + feature_map.feature_attribution_map(solver, [neural], W) + + +def test_unregularized_models_are_rejected(): + model = ConvTanhEncoder(num_input=4, num_output=5, left=2, right=1) + neural = torch.randn(20, 4) + W = np.ones((5, 2)) + unregularized = [ + model, # plain module + torch.nn.Linear(4, 5), + cebra.solver.SingleSessionSolver(model=model, + criterion=cebra.models.InfoNCE(), + optimizer=torch.optim.Adam( + model.parameters())), + cebra.solver.UnifiedSolver(model=model, + criterion=cebra.models.InfoNCE(), + optimizer=torch.optim.Adam( + model.parameters())), + ] + for obj in unregularized: + with pytest.raises(TypeError, match="Jacobian regularizer"): + feature_map.feature_attribution_map(obj, neural, W) + with pytest.raises(TypeError, match="sklearn"): + feature_map.feature_attribution_map(cebra.CEBRA(), neural, W) + + +def test_jacobian_in_eval_mode_and_mode_restored(): + torch.manual_seed(0) + + class DropoutEncoder(Model): + + def __init__(self): + super().__init__(num_input=4, num_output=3) + self.net = torch.nn.Sequential(torch.nn.Linear(4, 32), + torch.nn.Dropout(0.5), + torch.nn.Linear(32, 3)) + self.frozen = torch.nn.Dropout( + 0.1) # a submodule already in eval mode + + def forward(self, x): + return self.net(x) + + def get_offset(self): + return None + + model = DropoutEncoder() + solver = _regularized(model) + neural = torch.randn(10, 4) + W = np.random.default_rng(0).normal(size=(3, 2)) + + model.eval() + expected = feature_map.feature_attribution_map(solver, neural, W) + model.train() + model.frozen.eval() + got = feature_map.feature_attribution_map(solver, neural, W) + np.testing.assert_allclose(got, expected) + assert model.training and model.net[1].training and not model.frozen.training + + # in train mode the dropout masks would change the outputs (and so the map) + model.train() + assert not torch.allclose(model(neural), model(neural)) + + +def test_short_input_raises(): + model = ConvTanhEncoder(num_input=4, num_output=5, left=2, right=1) + W = np.ones((5, 2)) + with pytest.raises(ValueError, match="too few"): + feature_map.feature_attribution_map(_regularized(model), + torch.randn(2, 4), W) + _, inputs, labels = _two_session_dataset(n_time=40, n_neurons=(3, 5)) + solver = _unified_solver() + with pytest.raises(ValueError, match="too few"): + feature_map.feature_attribution_map(solver, + inputs, + np.ones((4, 2)), + labels=labels, + session_id=0, + indices=[0, 1]) + + +def test_unified_random_ties_seeded_and_global_rng_untouched(): + _, inputs, labels = _two_session_dataset(n_time=40, n_neurons=(3, 5)) + solver = _unified_solver() + W = np.random.default_rng(2).normal(size=(4, 2)) + + def run(**kw): + return feature_map.feature_attribution_map(solver, + inputs, + W, + labels=labels, + session_id=0, + **kw) + + torch_state, numpy_state = torch.random.get_rng_state(), np.random.get_state()[1].copy() + a = run(random_ties=True, seed=3) + np.testing.assert_allclose(a, run(random_ties=True, seed=3)) + assert not np.allclose(a, run(random_ties=True, seed=4)) + assert torch.equal(torch_state, torch.random.get_rng_state()) + np.testing.assert_array_equal(numpy_state, np.random.get_state()[1]) + np.testing.assert_allclose(run(), run(random_ties=False)) + + +def test_public_api_exports(): + assert set(feature_map.__all__) == { + "fit_feature_readout", "feature_attribution_map", "average_feature_maps" + } + for name in feature_map.__all__: + func = getattr(feature_map, name) + assert getattr(cebra.attribution, name) is func + assert ">>>" in func.__doc__, f"{name} has no example (run by --doctest-modules)" + + +@pytest.mark.parametrize("conv", [False, True]) +def test_feature_map_methods_agree_with_cebra_attribution(conv): + # M_t = J_t^T W with J_t from CEBRA's "jacobian-based" method (and, for a model without an + # offset, the Captum backend "neuron-gradient"); every `method` option gives the same map. + torch.manual_seed(0) + rng = np.random.default_rng(8) + model = ConvTanhEncoder(4, 5, left=2, right=1) if conv else MLPEncoder(4, 5) + solver = _regularized(model) + neural = torch.randn(30, 4) + W = rng.normal(size=(5, 2)) + + jacobian = cebra.attribution.init( + "jacobian-based", + model=model, + input_data=neural.clone().requires_grad_(True), + output_dimension=5).compute_attribution_map(selected_keys=["jf"])["jf"] + expected = np.einsum("tdn,df->tnf", jacobian, W) # J_t^T W, (T_valid, N, F) + if not conv: + gradient = cebra.attribution.init( + "neuron-gradient", + model=model, + input_data=neural.clone().requires_grad_(True), + output_dimension=5).compute_attribution_map()["neuron-gradient"] + np.testing.assert_allclose(np.einsum("tdn,df->tnf", gradient, W), + expected, + rtol=1e-5, + atol=1e-6) + + for method in feature_map.JACOBIAN_METHODS: + per_row = feature_map.feature_attribution_map(solver, + neural, + W, + average=False, + batch_size=7, + method=method) + np.testing.assert_allclose(per_row, expected, rtol=1e-5, atol=1e-6) + mean = feature_map.feature_attribution_map(solver, neural, W, method=method) + np.testing.assert_allclose(mean, expected.mean(axis=0), rtol=1e-5, atol=1e-6) + + with pytest.raises(ValueError, match="method must be one of"): + feature_map.feature_attribution_map(solver, + neural, + W, + method="neuron-gradient") diff --git a/tests/test_integration_xcebra.py b/tests/test_integration_xcebra.py index e213be61..340cd7e2 100644 --- a/tests/test_integration_xcebra.py +++ b/tests/test_integration_xcebra.py @@ -155,14 +155,15 @@ def test_synthetic_data_training(synthetic_data, device): # Test the transform solver.model.split_outputs = False - transform_embedding = solver.transform(data.neural.to(device)) + transform_embedding = solver.transform(data.neural.to(device)).cpu() assert transform_embedding.shape[ 1] == n_latents, "Incorrect embedding dimension" assert not torch.isnan(transform_embedding).any(), "NaN values in embedding" assert np.allclose(embedding, transform_embedding, rtol=1e-4, atol=1e-4) # Test the transform with batching - batched_embedding = solver.transform(data.neural.to(device), batch_size=512) + batched_embedding = solver.transform(data.neural.to(device), + batch_size=512).cpu() assert batched_embedding.shape[ 1] == n_latents, "Incorrect embedding dimension" assert not torch.isnan(batched_embedding).any(), "NaN values in embedding" @@ -175,7 +176,7 @@ def test_synthetic_data_training(synthetic_data, device): # Test and compare the previous transform (transform_deprecated) deprecated_transform_embedding = _reference_implementations.multiobjective_transform_deprecated( - solver, data.neural.to(device)) + solver, data.neural.to(device)).detach().cpu() assert np.allclose(embedding, deprecated_transform_embedding, rtol=1e-4, diff --git a/tests/test_solver.py b/tests/test_solver.py index 6e41e09f..97e2a3d2 100644 --- a/tests/test_solver.py +++ b/tests/test_solver.py @@ -32,6 +32,10 @@ import cebra.models import cebra.solver + +# ---- helpers ---- + + device = "cpu" @@ -152,6 +156,9 @@ def _test_single_session_transform(solver, X, offset): _assert_equal(fitted_solver, solver) +# ---- single-session solvers ---- + + @pytest.mark.parametrize( "data_name, model_architecture, loader_initfunc, solver_initfunc", [(dataset, model, loader, cebra.solver.SingleSessionSolver) @@ -263,6 +270,9 @@ def test_single_session_hybrid(data_name, loader_initfunc, model_architecture, _test_single_session_transform(solver, X, offset) +# ---- multi-session solver ---- + + @pytest.mark.parametrize( "data_name, model_architecture, loader_initfunc, solver_initfunc", [(dataset, model, loader, cebra.solver.MultiSessionSolver) @@ -351,6 +361,9 @@ def test_multi_session(data_name, loader_initfunc, model_architecture, _assert_equal(fitted_solver, solver) +# ---- unified solver ---- + + def _make_val_data(dataset): if isinstance(dataset, cebra.datasets.demo.DemoDataset): return dataset.neural @@ -403,6 +416,9 @@ def test_unified_session(data_name, model_architecture, loader_initfunc, assert emb.shape == (loader.dataset.num_timepoints, 3) +# ---- checkpoint loading ---- + + def test_load_checkpoint_with_numpy_scalars(tmp_path): # Checkpoints of unified solvers saved before n_features was a Python int store it as a # numpy int64; torch>=2.6 loads with weights_only=True by default. @@ -437,3 +453,195 @@ def test_load_checkpoint_rejects_other_objects(tmp_path): with torch.serialization.safe_globals( cebra.solver.base._CHECKPOINT_SAFE_GLOBALS): torch.load(path, weights_only=True) + + +# ---- unified solver: aligned inputs and batched transform ---- + + +class _ConvEncoder(cebra.models.Model, cebra.models.ConvolutionalModelMixin): + """Small convolutional-offset encoder.""" + + def __init__(self, num_input, num_output, left=2, right=1): + super().__init__(num_input=num_input, num_output=num_output) + self.offset = cebra.data.Offset(left, right) + self.conv = torch.nn.Conv1d(num_input, num_output, left + right) + + def forward( + self, + x): # (batch, N, T) -> (batch, num_output, T - left - right + 1) + return torch.tanh(self.conv(x)) + + def get_offset(self): + return self.offset + + +def _tied_sessions( + lengths=(60, 90, 75), n_channels=(3, 4, 5), n_frames=15, seed=0): + """Sessions whose labels repeat exactly (ties), as in repeated stimulus presentations.""" + gen = torch.Generator().manual_seed(seed) + base = torch.randn(n_frames, 2, generator=gen) + inputs, labels = [], [] + for length, n in zip(lengths, n_channels): + reps = -(-length // n_frames) + labels.append(base.repeat(reps, 1)[:length].clone()) + inputs.append(torch.randn(length, n, generator=gen)) + return inputs, labels + + +def _unified_solver(n_total, left=2, right=1, num_output=4): + model = _ConvEncoder(n_total, num_output, left, right) + solver = cebra.solver.UnifiedSolver(model=model, + criterion=cebra.models.InfoNCE(), + optimizer=torch.optim.Adam( + model.parameters())) + solver.n_features, solver.num_sessions = n_total, 3 + return solver + + +def test_aligned_inputs_shape_single_row_and_seed(): + inputs, labels = _tied_sessions() + solver = _unified_solver(12) + out = solver.aligned_inputs(inputs, labels, session_id=1) + assert out.shape == (90, 12) + torch.testing.assert_close(out[:, 3:7], inputs[1]) + + one = solver.aligned_inputs(inputs, labels, session_id=1, indices=[7]) + assert one.shape == (1, 12) + torch.testing.assert_close(one, out[7:8]) + + a = solver.aligned_inputs(inputs, labels, 0, random_ties=True, seed=2) + b = solver.aligned_inputs(inputs, labels, 0, random_ties=True, seed=2) + c = solver.aligned_inputs(inputs, labels, 0, random_ties=True, seed=3) + torch.testing.assert_close(a, b) + assert not torch.equal(a, c) + # random_ties=False is deterministic and takes the first tie + d = solver.aligned_inputs(inputs, labels, 0) + torch.testing.assert_close(d, solver.aligned_inputs(inputs, labels, 0)) + + +@pytest.mark.parametrize("pad", [True, False]) +@pytest.mark.parametrize("batch_size", [1, 7, 64, None]) +def test_unified_transform_batched_matches_full_session_reference( + pad, batch_size): + """Batch by batch inference equals one pass over the full aligned session.""" + inputs, labels = _tied_sessions(lengths=(60, 90, 75)) + solver = _unified_solver(12, left=5, right=5) + ref_in = solver.aligned_inputs(inputs, + labels, + session_id=1, + random_ties=True, + seed=4) + if pad: # repeat the first and last samples, as Solver.transform + ref_in = torch.cat( + [ref_in[:1].repeat(5, 1), ref_in, ref_in[-1:].repeat(4, 1)]) + with torch.no_grad(): + ref = solver.model(ref_in.T.unsqueeze(0)).squeeze(0).T + out = solver.transform(inputs, + labels, + session_id=1, + batch_size=batch_size, + pad_before_transform=pad, + random_ties=True, + seed=4) + assert out.shape == ((90, 4) if pad else (81, 4)) + torch.testing.assert_close(out, ref, atol=1e-5, rtol=1e-5) + + +def test_unified_transform_session_shorter_than_window(): + inputs, labels = _tied_sessions(lengths=(8, 90, 75)) + solver = _unified_solver(12, left=5, right=5) + assert solver.transform(inputs, labels, session_id=0).shape == (8, 4) + with pytest.raises(ValueError, match="receptive field"): + solver.transform(inputs, + labels, + session_id=0, + pad_before_transform=False) + + +def test_unified_transform_random_ties_default_false_and_seed(): + inputs, labels = _tied_sessions() + solver = _unified_solver(12) + a = solver.transform(inputs, labels, session_id=0) + torch.manual_seed(1) + b = solver.transform(inputs, labels, session_id=0) + torch.testing.assert_close(a, b) + r1 = solver.transform(inputs, + labels, + session_id=0, + random_ties=True, + seed=0) + r2 = solver.transform(inputs, + labels, + session_id=0, + random_ties=True, + seed=0) + torch.testing.assert_close(r1, r2) + with pytest.raises(ValueError): + solver.transform(inputs, labels) # session_id is required + + +def test_unified_transform_default_seed_and_random_ties_need_seed(): + """The default seed gives the same tie draws in every call; random ties need a seed.""" + inputs, labels = _tied_sessions() + solver = _unified_solver(12) + a = solver.transform(inputs, labels, session_id=0, random_ties=True) + b = solver.transform(inputs, labels, session_id=0, random_ties=True) + torch.testing.assert_close(a, b) + torch.testing.assert_close( + solver.aligned_inputs(inputs, labels, 0, random_ties=True), + solver.aligned_inputs(inputs, labels, 0, random_ties=True, seed=0)) + with pytest.raises(ValueError, match="needs a seed"): + solver.transform(inputs, labels, session_id=0, random_ties=True, seed=None) + + +# ---- unified xCEBRA solver ---- + + +def _xcebra_solver(): + module = _ConvEncoder(12, 6) + solver = cebra.solver.UnifiedSolverxCEBRA( + model=module, + criterion=cebra.models.InfoNCE(), + optimizer=torch.optim.Adam(module.parameters()), + feature_ranges=[slice(0, 3), slice(3, 6)], + renormalize=True, + ) + solver.n_features, solver.num_sessions = 12, 3 + return solver + + +@pytest.mark.parametrize("initial", [True, False]) +def test_unified_xcebra_transform_concatenated_and_split_mode_restored(initial): + """transform returns the single concatenated embedding and restores the model's split mode, + also when it raises.""" + inputs, labels = _tied_sessions() + solver = _xcebra_solver() + solver.model.set_split_outputs(initial) + emb = solver.transform(inputs, labels, session_id=1, batch_size=10) + assert torch.is_tensor(emb) and emb.shape == (90, 6) + assert solver.model.split_outputs is initial + with pytest.raises(Exception): + solver.transform(inputs, [l[:, :1] * 0 for l in labels][:2], + session_id=0) + assert solver.model.split_outputs is initial + + +# ---- unified checkpoint loading ---- + + +def test_unified_checkpoint_loads_with_weights_only(tmp_path): + inputs, labels = _tied_sessions() + dataset = cebra.data.UnifiedDataset(*[ + cebra.data.TensorDataset(x, continuous=l) + for x, l in zip(inputs, labels) + ]) + assert type(dataset.input_dimension) is int + solver = _unified_solver(sum(x.shape[1] for x in inputs)) + solver._set_fitted_params(cebra.data.UnifiedLoader(dataset, num_steps=1)) + solver.save(str(tmp_path), "model.pt") + + checkpoint = torch.load(tmp_path / "model.pt", weights_only=True) + assert checkpoint["n_features"] == dataset.input_dimension + other = _unified_solver(sum(x.shape[1] for x in inputs)) + other.load(str(tmp_path), "model.pt") + assert other.n_features == dataset.input_dimension From e578253967b03e5e31b23585bb1f6dbe84006b30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Fri, 13 Nov 2026 10:49:19 +0100 Subject: [PATCH 12/27] Refactor documentation and type hints --- cebra/attribution/feature_map.py | 9 +++++---- cebra/data/datasets.py | 7 +++---- cebra/data/masking.py | 6 ++++++ cebra/distributions/multisession.py | 9 +++++---- cebra/solver/base.py | 2 +- cebra/solver/unified_session.py | 23 ++++++++++++----------- docs/source/api/pytorch/data.rst | 4 +--- 7 files changed, 33 insertions(+), 27 deletions(-) diff --git a/cebra/attribution/feature_map.py b/cebra/attribution/feature_map.py index e592aadb..cae5cd23 100644 --- a/cebra/attribution/feature_map.py +++ b/cebra/attribution/feature_map.py @@ -230,7 +230,7 @@ def _check_readout(W, n_outputs: int) -> np.ndarray: def _check_method(method: str): - """Raise if ``method`` is not one of :data:`JACOBIAN_METHODS`.""" + """Raise if ``method`` is not one of ``JACOBIAN_METHODS``.""" if method not in JACOBIAN_METHODS: raise ValueError( f"method must be one of {JACOBIAN_METHODS}, got {method!r}.") @@ -431,7 +431,7 @@ def feature_attribution_map( indices: Rows of the (reference) session's inputs at which the map is computed. For a unified solver the other sessions are aligned to these rows. Default: all. output_slice: Single session only. Embedding columns of one head, e.g. one subspace of a - :py:class:`~cebra.models.SubspaceMultiobjectiveModel`. + :py:class:`~cebra.models.multiobjective.SubspaceMultiobjectiveModel`. average: ``True`` for the time mean ``(N, F)``, ``False`` for one map per valid row ``(T_valid, N, F)`` (see the module notes). random_ties: Unified only. Break nearest-label ties at random instead of taking the @@ -442,10 +442,11 @@ def feature_attribution_map( latent_batch_size: Embedding dimensions per autograd pass. Only used by the default ``method``. method: Attribution method that computes the Jacobian, one of - :data:`JACOBIAN_METHODS`. + ``JACOBIAN_METHODS``. Returns: - Array, float64: ``(N, F)`` for ``average=True``, ``(T_valid, N, F)`` for ``average=False``. + The map as a float64 array, ``(N, F)`` for ``average=True`` and ``(T_valid, N, F)`` for + ``average=False``. Raises: TypeError: If ``solver`` was not trained with the Jacobian regularizer. diff --git a/cebra/data/datasets.py b/cebra/data/datasets.py index 1285eef9..a19a53c0 100644 --- a/cebra/data/datasets.py +++ b/cebra/data/datasets.py @@ -626,10 +626,9 @@ def load_batch_contrastive(self, index: BatchIndex) -> Batch: - positive: list of (num_sessions, num_samples) tensors, one per objective Returns: - Batch with: - - reference: concatenated across sessions - - negative: concatenated across sessions - - positive: list of tensors, each concatenated across sessions per objective + A :py:class:`~cebra.data.datatypes.Batch` whose ``reference`` and ``negative`` are + concatenated across sessions and whose ``positive`` is a list of tensors, one per + objective, each concatenated across sessions. """ # Get reference and negative once (shared across objectives) temp_index = BatchIndex( diff --git a/cebra/data/masking.py b/cebra/data/masking.py index e4830aea..2abe4715 100644 --- a/cebra/data/masking.py +++ b/cebra/data/masking.py @@ -47,6 +47,7 @@ def set_masks( """Set the mask types and parameters for the dataset. Supports two input formats: + - Dict[str, params]: One instance per mask type; replaces any previous instance of the same class (backward compatible). - List[ (name, params) | {name: params} ]: Adds one instance per entry, @@ -186,6 +187,11 @@ def apply_mask(self, class Mask: + """Base class of the masks: subclasses implement ``apply_mask``. + + Args: + masking_value: Masking parameter(s) of the subclass, e.g. the fraction of the data to mask. + """ def __init__(self, masking_value: Union[float, List[float], Tuple[float]]): self._check_masking_parameters(masking_value) diff --git a/cebra/distributions/multisession.py b/cebra/distributions/multisession.py index 823005e3..367f725d 100644 --- a/cebra/distributions/multisession.py +++ b/cebra/distributions/multisession.py @@ -40,10 +40,11 @@ def _normalize_cuda_device(device_name: str) -> str: return device_name # Prefer the concrete device index from dataset tensors if available. - if hasattr(dataset, "continuous_index"): - idx_device = dataset.continuous_index.device - if idx_device.type == "cuda" and idx_device.index is not None: - return f"cuda:{idx_device.index}" + index = getattr(dataset, "continuous_index", None) + if index is None: + index = getattr(dataset, "discrete_index", None) + if index is not None and index.device.type == "cuda" and index.device.index is not None: + return f"cuda:{index.device.index}" # Fall back to currently selected CUDA device instead of implicit cuda:0. if torch.cuda.is_available(): diff --git a/cebra/solver/base.py b/cebra/solver/base.py index 04ed9f88..1c58fb32 100644 --- a/cebra/solver/base.py +++ b/cebra/solver/base.py @@ -346,7 +346,7 @@ class Solver(abc.ABC, cebra.io.HasDevice): "temperature": [] })) tqdm_on: bool = True - scheduler: torch.optim.lr_scheduler = None + scheduler: Optional[torch.optim.lr_scheduler.LRScheduler] = None def __post_init__(self): cebra.io.HasDevice.__init__(self) diff --git a/cebra/solver/unified_session.py b/cebra/solver/unified_session.py index a23fe6b2..2cfb2759 100644 --- a/cebra/solver/unified_session.py +++ b/cebra/solver/unified_session.py @@ -25,7 +25,7 @@ This allows users to align and embed multiple sessions into a common latent space using a single shared model. -This module implements the :py:class:`~cebra.solver.unified.UnifiedSolver`, which +This module implements the :py:class:`~cebra.solver.unified_session.UnifiedSolver`, which is designed for training a single embedding model across multiple recording sessions. Unlike the standard multi-session solvers, the unified session approach uses a global model that requires session-specific information for sampling but maintains @@ -34,12 +34,12 @@ Features: - Single model inference across all sessions. - Batched transform. -- Compatibility with :py:class:`~cebra.data.UnifiedDataset` and :py:class:`~cebra.data.UnifiedLoader`. +- Compatibility with :py:class:`~cebra.data.datasets.UnifiedDataset` and :py:class:`~cebra.data.multi_session.UnifiedLoader`. See Also: :py:class:`~cebra.solver.base.Solver` - :py:class:`~cebra.data.UnifiedDataset` - :py:class:`~cebra.data.UnifiedLoader` + :py:class:`~cebra.data.datasets.UnifiedDataset` + :py:class:`~cebra.data.multi_session.UnifiedLoader` """ from typing import List, Optional, Union @@ -156,7 +156,7 @@ def _gather_aligned_inputs(inputs: List[torch.Tensor], return out -class _AlignedInputsMixin: +class AlignedInputsMixin: """Shared aligned-input building and whole-session transform of the unified solvers.""" def aligned_inputs(self, @@ -269,7 +269,7 @@ def _transform_session(self, inputs, labels, pad_before_transform, @register("unified-session") @dataclasses.dataclass -class UnifiedSolver(_AlignedInputsMixin, abc_.Solver): +class UnifiedSolver(AlignedInputsMixin, abc_.Solver): """Multi session training, considering a single model for all sessions.""" _variant_name = "unified-session" @@ -411,7 +411,8 @@ def transform(self, seed: Optional[int] = 0) -> torch.Tensor: """Compute the embedding of session ``session_id``. - The other sessions are aligned on ``session_id`` (see :py:meth:`aligned_inputs`), then + The other sessions are aligned on ``session_id`` (see + :py:meth:`~cebra.solver.unified_session.AlignedInputsMixin.aligned_inputs`), then the session is embedded in batches. Each batch keeps its real neighbouring samples, so the result does not depend on ``batch_size``. @@ -557,13 +558,13 @@ def decoding(self, deprecated=True) # NOTE: earlier name, kept for compatibility @register("unified-xcebra") @dataclasses.dataclass -class UnifiedSolverxCEBRA(_AlignedInputsMixin, MultiobjectiveSolverBase): +class UnifiedSolverxCEBRA(AlignedInputsMixin, MultiobjectiveSolverBase): """Unified CEBRA solver with Jacobian regularization (unified xCEBRA). Trains one model shared by all sessions, like :py:class:`~cebra.solver.unified_session.UnifiedSolver`, and adds the Jacobian regularization of xCEBRA (:py:class:`~cebra.models.jacobian_regularizer.JacobianReg`, passed as ``regularizer``, with its - weight set over training by ``scheduler_regularizer`` in :py:meth:`fit`). It builds on the + weight set over training by ``scheduler_regularizer`` in ``fit``). It builds on the multi-objective solver only because that solver supports the regularizer. Unified xCEBRA uses a single objective: one slice covering the whole embedding, with a @@ -572,7 +573,7 @@ class UnifiedSolverxCEBRA(_AlignedInputsMixin, MultiobjectiveSolverBase): ``set_loss`` / ``set_distribution`` / ``push``). Several slices (subspaces) are accepted by the code but have not been used or validated with the unified sampler. - Takes batches from :py:class:`~cebra.data.multiobjective.UnifiedContrastiveMultiObjectiveLoader`, + Takes batches from ``cebra.data.multiobjective.UnifiedContrastiveMultiObjectiveLoader``, in which the samples of all sessions are already aligned and concatenated. Example: @@ -589,7 +590,7 @@ class UnifiedSolverxCEBRA(_AlignedInputsMixin, MultiobjectiveSolverBase): >>> solver.fit(loader, scheduler_regularizer=weight_scheduler) # doctest: +SKIP See Also: - :py:class:`cebra.data.multiobjective.UnifiedContrastiveMultiObjectiveLoader` + ``cebra.data.multiobjective.UnifiedContrastiveMultiObjectiveLoader`` :py:class:`cebra.solver.multiobjective.MultiObjectiveConfig` :py:class:`cebra.models.multicriterions.MultiCriterions` """ diff --git a/docs/source/api/pytorch/data.rst b/docs/source/api/pytorch/data.rst index 09e6c0bd..e8f319dc 100644 --- a/docs/source/api/pytorch/data.rst +++ b/docs/source/api/pytorch/data.rst @@ -45,9 +45,7 @@ under *Multi Session Dataloaders*. Masking -------------------------------- -.. automodule:: cebra.data.masking - :members: - :show-inheritance: +The masks (:py:mod:`cebra.data.masking`) are documented under :doc:`Helper functions `. Single Session Dataloaders From 73f996a7f11e7534bc8c68cb4066749e66fc1211 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Fri, 13 Nov 2026 11:17:31 +0100 Subject: [PATCH 13/27] Remove dataset classes; update documentation for clarity --- cebra/data/multiobjective.py | 5 +- cebra/datasets/__init__.py | 3 - cebra/datasets/allen/single_session_ca.py | 15 +- cebra/datasets/make_nlb_data.py | 169 --------------- cebra/datasets/nlb_data.py | 248 ---------------------- cebra/datasets/perich.py | 156 -------------- cebra/datasets/poyo_data.py | 58 ----- cebra/solver/unified_session.py | 3 + 8 files changed, 15 insertions(+), 642 deletions(-) delete mode 100644 cebra/datasets/make_nlb_data.py delete mode 100644 cebra/datasets/nlb_data.py delete mode 100644 cebra/datasets/perich.py delete mode 100644 cebra/datasets/poyo_data.py diff --git a/cebra/data/multiobjective.py b/cebra/data/multiobjective.py index 0c166653..6db7ba51 100644 --- a/cebra/data/multiobjective.py +++ b/cebra/data/multiobjective.py @@ -189,7 +189,10 @@ class UnifiedContrastiveMultiObjectiveLoader(cebra_data.Loader): Reference and negative samples are shared across all objectives and sampled uniformly across sessions via UnifiedSampler. Positive samples are drawn per-objective using time_delta sampling with random shifts. - + + The historical ``MultiObjective`` name is retained; the current unified xCEBRA + workflow uses a single objective. + Yields batches of the specified size from the given UnifiedDataset. """ diff --git a/cebra/datasets/__init__.py b/cebra/datasets/__init__.py index c1b30311..8b8fb4fe 100644 --- a/cebra/datasets/__init__.py +++ b/cebra/datasets/__init__.py @@ -97,9 +97,6 @@ def get_datapath(path: str = None) -> str: from cebra.datasets.hippocampus import * from cebra.datasets.monkey_reaching import * from cebra.datasets.synthetic_data import * - from cebra.datasets.nlb_data import * - from cebra.datasets.poyo_data import * - from cebra.datasets.perich import * except ModuleNotFoundError as e: warnings.warn(f"Could not initialize one or more datasets: {e}. " diff --git a/cebra/datasets/allen/single_session_ca.py b/cebra/datasets/allen/single_session_ca.py index 46388141..a2434aa1 100644 --- a/cebra/datasets/allen/single_session_ca.py +++ b/cebra/datasets/allen/single_session_ca.py @@ -117,16 +117,17 @@ def __getitem__(self, index): class SingleSessionAllenCaCortex(SingleSessionAllenCa): - """A single mouse 30Hz calcium events dataset during the allen MOVIE1 stimulus. + """Single-session Allen calcium data with configurable cortex and neuron type. - A dataset of a single mouse 30Hz calcium events from the excitatory neurons in the primary visual cortex - during the 10 repeats of the MOVIE1 stimulus in session type A. The preprocessed data from *Deitch et al. (2021) are used. - The continuous labels corresponding to a DINO embedding of each stimulus frame. + Unlike :class:`SingleSessionAllenCa`, which selects one of four fixed VISp + excitatory sessions by index, this class selects a recording by its + experiment-container ID and allows the cortex and neuron type to vary. Args: - session_id: The integer value to pick a session among 4 sessions with the largest number of recorded neruons. Choose between 0-3. - frame_feature_path: The path of the movie frame features. - + session_id: Allen experiment-container ID, e.g. ``680156909``. + frame_feature_path: Path to the movie frame features. + cortex: Cortical area, e.g. ``"VISp"``. + neuron_type: Neuron data directory, e.g. ``"calcium_excitatory"``. """ def __init__( diff --git a/cebra/datasets/make_nlb_data.py b/cebra/datasets/make_nlb_data.py deleted file mode 100644 index 61e8e25e..00000000 --- a/cebra/datasets/make_nlb_data.py +++ /dev/null @@ -1,169 +0,0 @@ -""" -Example on how to run in folder cebra/datasets: -``` -python make_nlb_data.py --dataset_name mc_maze_large -``` -""" - -import argparse -import os -import pathlib - -import joblib as jl -import numpy as np -import scipy.signal as signal -from nlb_tools.make_tensors import make_eval_input_tensors -from nlb_tools.make_tensors import make_eval_target_tensors -from nlb_tools.make_tensors import make_train_input_tensors -from nlb_tools.nwb_interface import NWBDataset - -dataset_dict = { - "mc_maze": "000128/sub-Jenkins/", - "mc_maze_small": "000140/sub-Jenkins/", - "mc_maze_medium": "000139/sub-Jenkins/", - "mc_maze_large": "000138/sub-Jenkins/", - "mc_rtt": "000129/sub-Indy", - "area2_bump": "000127/sub-Han/", - "dmfc_rsg": "000130/sub-Haydn", -} - -parser = argparse.ArgumentParser() -parser.add_argument("--datapath", type=str, default="/data/celia/nlb") -parser.add_argument("--dataset_name", type=str, required=True) -parser.add_argument("--savepath", - type=str, - default="/mnt/data_storage/celia/nlb/data") -parser.add_argument("--bin_width", type=int, default=5) -parser.add_argument("--smoothing_width", type=int, default=50) -parser.add_argument("--split", type=str, default="train") - -args = parser.parse_args() -args.datapath = pathlib.Path(args.datapath) -args.savepath = pathlib.Path(args.savepath) - -if args.dataset_name not in dataset_dict.keys(): - raise NotImplementedError(f"{args.dataset_name}") - -if args.split == "full-train": - prefix = "" - phase = "test" - -elif args.split != "test": - prefix = "*train" - phase = "val" - -elif args.split == "test": - prefix = "*test" - phase = "test" - -dataset = NWBDataset(args.datapath / dataset_dict[args.dataset_name], prefix) -dataset.resample(args.bin_width) - -suffix = "" if (args.bin_width == 5) else f"_{int(round(args.bin_width))}" - -if args.smoothing_width != 0: - smoothing_tag = f"_smth{args.smoothing_width}" -else: - smoothing_tag = "" - - -def smoothing(kern_sd, spikes, bin_size_ms): - window = signal.gaussian(int(6 * kern_sd / bin_size_ms), - int(kern_sd / bin_size_ms), - sym=True) - window /= np.sum(window) - - def filt(x): - return np.convolve(x, window, "same") - - if kern_sd != 0: - convolved = np.apply_along_axis(filt, 1, spikes) - return convolved - else: - return spikes - - -eval_dict = make_eval_input_tensors(dataset, - dataset_name=args.dataset_name, - trial_split=phase, - save_file=False) -eval_spikes_heldin = eval_dict["eval_spikes_heldin"] - -if args.split != "test": - train_trial_split = "train" if (phase == "val") else ["train", "val"] - train_dict = make_train_input_tensors( - dataset, - dataset_name=args.dataset_name, - trial_split=train_trial_split, - save_file=False, - include_behavior=True, - include_forward_pred=False, - ) - - train_spikes_heldin = train_dict["train_spikes_heldin"] - train_spikes_heldout = train_dict["train_spikes_heldout"] - - # Generate target data - target_dict = make_eval_target_tensors( - dataset, - dataset_name=args.dataset_name, - train_trial_split="train", - eval_trial_split="val", - include_psth=False, - save_file=False, - ) - - train_behavior = target_dict[f"{args.dataset_name}{suffix}"][ - "train_behavior"] - - if args.split == "train": - eval_spikes_heldout = eval_dict["eval_spikes_heldout"] - eval_behavior = target_dict[f"{args.dataset_name}{suffix}"][ - "eval_behavior"] - data_dict = { - "train_behavior": - train_behavior, - "eval_behavior": - eval_behavior, - "train_neural_heldin": - smoothing(args.smoothing_width, train_spikes_heldin, - args.bin_width), - "eval_neural_heldin": - smoothing(args.smoothing_width, eval_spikes_heldin, - args.bin_width), - "train_neural_heldout": - train_spikes_heldout, - "eval_neural_heldout": - eval_spikes_heldout, - } - elif args.split == "full-train": - data_dict = { - "train_behavior": - train_behavior, - "train_neural_heldin": - smoothing(args.smoothing_width, train_spikes_heldin, - args.bin_width), - "train_neural_heldout": - train_spikes_heldout, - "eval_neural_heldin": - smoothing(args.smoothing_width, eval_spikes_heldin, - args.bin_width), - } - -elif args.split == "test": - data_dict = { - "eval_neural_heldin": - smoothing(args.smoothing_width, eval_spikes_heldin, args.bin_width) - } - -jl.dump( - data_dict, - args.savepath / - f"{args.dataset_name}_{args.split}{suffix}{smoothing_tag}.jl", -) - -if args.split != "test": - jl.dump( - target_dict, - args.savepath / f"target_dict_{args.dataset_name}{suffix}.jl", - ) diff --git a/cebra/datasets/nlb_data.py b/cebra/datasets/nlb_data.py deleted file mode 100644 index 8c0d688e..00000000 --- a/cebra/datasets/nlb_data.py +++ /dev/null @@ -1,248 +0,0 @@ -import os - -import joblib as jl -import numpy as np -import scipy.stats -import sklearn.cluster -import torch - -import cebra.data -import cebra.io -from cebra.datasets import get_datapath -from cebra.datasets import parametrize - -_DEFAULT_DATADIR = get_datapath() - - -class NLBDataset(cebra.data.SingleSessionDataset): - - def __init__(self, bin_width, split="train"): - super().__init__() - self.bin_width = int(bin_width) - self.split_tag = split - - def define_dataset(self, bin_width, smoothing, split): - if bin_width == str(5): - name_bin = "" - else: - name_bin = f"_{bin_width}" - - if smoothing != 0: - smth = f"_smth{smoothing}" - else: - smth = "" - - if split == "valid": - self.split = "eval" - file_name = "train" - elif split == "train": - self.split = "train" - file_name = "train" - elif split == "test": - self.split = "eval" - file_name = "test" - elif split == "train+valid": - self.split = "train" - file_name = "full-train" - - return name_bin, smth, file_name - - def __getitem__(self, index): - index = self.expand_index_in_trial(index, - trial_ids=self.trial_ids, - trial_borders=self.trial_borders) - return self.neural[index].transpose(2, 1) - - def __len__(self): - return len(self.neural) - - @property - def input_dimension(self): - return self.neural.size(1) - - @property - def continuous_index(self): - if self.split_tag != "test": - return self.index - else: - return None - - @property - def discrete_index(self): - if self.split_tag != "test": - return self.trial_type - else: - return None - - -@parametrize("mc-maze-{size}-{bin_width}", - size=["standard", "small", "medium", "large"], - bin_width=["20", "5"]) -class MCMazeDataset(NLBDataset): - - def __init__(self, - size, - bin_width, - smoothing=50, - split="train", - zscored_index=False): - super().__init__(bin_width=bin_width, split=split) - if size == "standard" or size == "": - name_size = "" - else: - name_size = f"_{size}" - - self.name_size = name_size - name_bin, smth, file_name = self.define_dataset(bin_width=bin_width, - smoothing=smoothing, - split=split) - - dataset_name = f"mc_maze{name_size}_{file_name}{name_bin}{smth}.jl" - data_dict = jl.load(os.path.join(_DEFAULT_DATADIR, dataset_name)) - - self.neural_trial = torch.from_numpy( - data_dict[f"{self.split}_neural_heldin"]).float() - self.neural = self.neural_trial.reshape(-1, self.neural_trial.shape[-1]) - self.trial_len = self.neural_trial.shape[1] - self.num_trials = self.neural_trial.shape[0] - self.trial_ids = np.concatenate( - [[n] * self.trial_len for n in range(self.num_trials)]) - self.trial_borders = [ - self.trial_len * i for i in range(self.num_trials + 1) - ] - self.trial_indices = np.concatenate( - [np.arange(self.trial_len) for n in range(self.num_trials)]) - - if self.split_tag != "test": - self.neural_trial_heldout = torch.from_numpy( - data_dict[f"{self.split}_neural_heldout"]).float() - self.neural_heldout = self.neural_trial_heldout.reshape( - -1, self.neural_trial_heldout.shape[-1]) - self.index_trial = torch.from_numpy( - data_dict[f"{self.split}_behavior"]).float() - self.index = self.index_trial.reshape(-1, - self.index_trial.shape[-1]) - if zscored_index: - self.index = scipy.stats.zscore(self.index) - - self.index = torch.from_numpy(self.index).float() - - def __repr__(self): - return f"MC-Maze{self.name_size}" - - -@parametrize("area2-bump-{bin_width}", bin_width=["20", "5"]) -class AREA2Dataset(NLBDataset): - - def __init__(self, - bin_width, - smoothing=40, - split="train", - zscored_index=False): - super().__init__(bin_width=bin_width, split=split) - name_bin, smth, file_name = self.define_dataset(bin_width=bin_width, - smoothing=smoothing, - split=split) - - dataset_name = f"area2_bump_{file_name}{name_bin}{smth}.jl" - data_dict = jl.load(os.path.join(_DEFAULT_DATADIR, dataset_name)) - - self.neural_trial = torch.from_numpy( - data_dict[f"{self.split}_neural_heldin"]).float() - self.neural = self.neural_trial.reshape(-1, self.neural_trial.shape[-1]) - self.trial_len = self.neural_trial.shape[1] - self.num_trials = self.neural_trial.shape[0] - self.trial_ids = np.concatenate( - [[n] * self.trial_len for n in range(self.num_trials)]) - self.trial_borders = [ - self.trial_len * i for i in range(self.num_trials + 1) - ] - self.trial_indices = np.concatenate( - [np.arange(self.trial_len) for n in range(self.num_trials)]) - self.timepoint_labels = torch.from_numpy( - np.linspace(0, 10, - self.trial_len).reshape(1, -1).repeat(self.num_trials, - axis=0).flatten()) - - if self.split_tag != "test": - self.neural_trial_heldout = torch.from_numpy( - data_dict[f"{self.split}_neural_heldout"]).float() - self.neural_heldout = self.neural_trial_heldout.reshape( - -1, self.neural_trial_heldout.shape[-1]) - self.index_trial = torch.from_numpy( - data_dict[f"{self.split}_behavior"]).float() - self.pos_trial = self.index_trial.cumsum(axis=1) - kmeans = sklearn.cluster.KMeans(9) - X = self.pos_trial[:, -10:].mean(1) - kmeans.fit(X) - trial_labels = kmeans.predict(X) - passive_idx = np.linalg.norm(kmeans.cluster_centers_, - axis=1).argmin() - active_trials = trial_labels != passive_idx - self.trial_type = torch.from_numpy( - active_trials.reshape(1, -1).repeat(self.trial_len, - axis=1).flatten()).long() - self.index = self.index_trial.reshape(-1, - self.index_trial.shape[-1]) - if zscored_index: - self.index = scipy.stats.zscore(self.index) - - self.index = torch.from_numpy(self.index).float() - - def __repr__(self): - return f"Area2-Bump" - - -@parametrize("mc-rtt-{bin_width}", bin_width=["20", "5"]) -class MCRTTDataset(NLBDataset): - - def __init__(self, - bin_width, - smoothing=40, - split="train", - zscored_index=False): - super().__init__(bin_width=bin_width, split=split) - name_bin, smth, file_name = self.define_dataset(bin_width=bin_width, - smoothing=smoothing, - split=split) - - dataset_name = f"mc_rtt_{file_name}{name_bin}{smth}.jl" - data_dict = jl.load(os.path.join(_DEFAULT_DATADIR, dataset_name)) - - self.neural_trial = torch.from_numpy( - data_dict[f"{self.split}_neural_heldin"]).float() - self.neural = self.neural_trial.reshape(-1, self.neural_trial.shape[-1]) - self.trial_len = self.neural_trial.shape[1] - self.num_trials = self.neural_trial.shape[0] - self.trial_ids = np.concatenate( - [[n] * self.trial_len for n in range(self.num_trials)]) - self.trial_borders = [ - self.trial_len * i for i in range(self.num_trials + 1) - ] - self.trial_indices = np.concatenate( - [np.arange(self.trial_len) for n in range(self.num_trials)]) - - if self.split_tag != "test": - self.neural_trial_heldout = torch.from_numpy( - data_dict[f"{self.split}_neural_heldout"]).float() - self.neural_heldout = self.neural_trial_heldout.reshape( - -1, self.neural_trial_heldout.shape[-1]) - self.index_trial = torch.from_numpy( - data_dict[f"{self.split}_behavior"]).float() - self.index = self.index_trial.reshape(-1, - self.index_trial.shape[-1]) - if zscored_index: - self.index = scipy.stats.zscore(self.index) - - self.index = torch.from_numpy(self.index).float() - - self.trial_ids = np.concatenate( - [[n] * self.trial_len for n in range(self.num_trials)]) - self.trial_borders = [ - self.trial_len * i for i in range(self.num_trials + 1) - ] - self.trial_indices = np.concatenate( - [np.arange(self.trial_len) for n in range(self.num_trials)]) - - def __repr__(self): - return f"MC-RTT" diff --git a/cebra/datasets/perich.py b/cebra/datasets/perich.py deleted file mode 100644 index b43dad5c..00000000 --- a/cebra/datasets/perich.py +++ /dev/null @@ -1,156 +0,0 @@ -# -# CEBRA: Consistent EmBeddings of high-dimensional Recordings using Auxiliary variables -# © Mackenzie W. Mathis & Steffen Schneider (v0.4.0+) -# Source code: -# https://github.com/AdaptiveMotorControlLab/CEBRA -# -# Please see LICENSE.md for the full license document: -# https://github.com/AdaptiveMotorControlLab/CEBRA/blob/main/LICENSE.md -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import pathlib -from enum import Enum -from typing import Union - -import joblib as jl -import numpy as np -import pandas as pd - -import cebra.data -import cebra.io -from cebra.datasets import get_datapath - -_DEFAULT_DATADIR = get_datapath() - - -class Task(Enum): - CO = 0 - RT = 1 - - -class PerichDataset(cebra.data.SingleSessionDataset): - - def __init__(self, - file: Union[pathlib.Path, str], - drop_outliers: bool = True): - super().__init__() - - dataset = self.load_dataset(path=file) - - # Extract recording_id from path for data retrieval - path_obj = pathlib.Path(file) - if path_obj.suffix == '.h5': - recording_id = f"{path_obj.parent.name}/{path_obj.stem}" - else: - raise ValueError("File path must point to an h5 file") - - # Get the full recording data using brain_torch API - # brain_torch.Dataset.get_recording_data() returns full data without slicing - data = dataset.get_recording_data(recording_id) - - self.trial_id = self.get_trial_numbers(data) - trial_mask = (self.trial_id != -1) - - self.subtask_index = data.cursor.subtask_index - if drop_outliers: - subtask_mask = self.subtask_index != 5 - else: - subtask_mask = np.ones_like(self.subtask_index, dtype=bool) - - self.neural, self.index = self.get_neural_and_vel_data(data) - self.neural = self.neural[trial_mask & subtask_mask] - self.index = self.index[trial_mask & subtask_mask] - - self.session = pathlib.Path(data.session).name - self.train_mask = data.cursor.train_mask[trial_mask & subtask_mask] - self.test_mask = data.cursor.test_mask[trial_mask & subtask_mask] - self.valid_mask = data.cursor.valid_mask[trial_mask & subtask_mask] - - self.trial_id = self.trial_id[trial_mask & subtask_mask] - self.subtask_index = self.subtask_index[trial_mask & subtask_mask] - - def __len__(self): - return len(self.neural) - - @property - def input_dimension(self): - return self.neural.size(1) - - def __getitem__(self, index): - """Return [ No.Samples x Neurons x 10 ]""" - index = self.expand_index(index) - return self.neural[index].transpose(2, 1) - - def load_dataset(self, path: str, split: str = "train"): - """Load dataset from processed torch_brain format. - - Args: - path: Path to the h5 file or parent directory - split: Which split to use (used for sampling intervals) - - Returns: - Dataset object containing the recording - """ - # torch_brain is an optional dependency, imported lazily. - from torch_brain.data import Dataset - - # Extract the recording_id from the path - # torch_brain expects: root/brainset/session.h5 - # Format: recording_id = "brainset/session" - - path_obj = pathlib.Path(path) - if path_obj.suffix == '.h5': - # If path is a file, extract parent (brainset) and stem (session) - root = str(path_obj.parent.parent) - recording_id = f"{path_obj.parent.name}/{path_obj.stem}" - else: - # If path is a directory, use it as root - root = str(path_obj) - recording_id = None # Will need to be specified differently - - return Dataset(root=root, - recording_id=recording_id, - split=split, - keep_files_open=True) - - def get_neural_and_vel_data(self, data): - spike_times = data.spikes.timestamps - unit_indices = data.spikes.unit_index - - n_neurons = np.max(data.spikes.unit_index) + 1 - time_bins = data.cursor.timestamps - total_time = len(time_bins) - - psth = np.zeros((n_neurons, total_time)) - for i, spike_time in enumerate(spike_times): - unit_index = unit_indices[i] - time_bin = np.digitize(spike_time, time_bins) - 1 - if 0 <= time_bin < total_time: - psth[unit_index, time_bin] += 1 - - vel = data.cursor.vel - return psth.T, vel - - def get_trial_numbers(self, data): - cursor_timestamps = data.cursor.timestamps - trial_starts = data.trials.start - trial_ends = data.trials.end - - trial_numbers = np.full(cursor_timestamps.shape, -1) - - for trial_num, (start, end) in enumerate(zip(trial_starts, trial_ends)): - in_trial = (cursor_timestamps >= start) & (cursor_timestamps <= end) - trial_numbers[in_trial] = trial_num - - return trial_numbers diff --git a/cebra/datasets/poyo_data.py b/cebra/datasets/poyo_data.py deleted file mode 100644 index 249b44fa..00000000 --- a/cebra/datasets/poyo_data.py +++ /dev/null @@ -1,58 +0,0 @@ -import pathlib -from enum import Enum -from typing import Union - -import joblib as jl -import pandas as pd - -import cebra.data -import cebra.io -from cebra.datasets import get_datapath - -_DEFAULT_DATADIR = get_datapath() - - -class Task(Enum): - CO = 0 - RT = 1 - - -class PoyoDataset(cebra.data.SingleSessionDataset): - - def __init__(self, file: Union[pathlib.Path, str], drop_outliers: bool): - super().__init__() - - data_dict = jl.load(file) - data_df = pd.DataFrame.from_dict(data_dict) - - # e.g. filename: perich_sub-C_ses-CO-20131003_samplNone_smthNone - if "perich" in str(file): - file_list = str(file).split("-") - if file_list[2] in Task.__members__: - data_df["task"] = Task[file_list[2]].value - else: - raise NotImplementedError("Only CO and RT tasks are supported.") - else: - raise NotImplementedError("Only perich dataset is supported.") - - if drop_outliers: - data_df = data_df[data_df[("subtask_index", "subtask_idx")] != 5] - - self.neural = data_df["Spikes"].values - self.index = data_df["hand_vel"].values - self.trial_id = data_df["trial_id"].values - self.subtask_index = data_df[("subtask_index", "subtask_idx")].values - - self.task = data_df["task"].values[0] - - def __len__(self): - return len(self.neural) - - @property - def input_dimension(self): - return self.neural.size(1) - - def __getitem__(self, index): - """Return [ No.Samples x Neurons x 10 ]""" - index = self.expand_index(index) - return self.neural[index].transpose(2, 1) diff --git a/cebra/solver/unified_session.py b/cebra/solver/unified_session.py index 2cfb2759..d9b74d12 100644 --- a/cebra/solver/unified_session.py +++ b/cebra/solver/unified_session.py @@ -573,6 +573,9 @@ class UnifiedSolverxCEBRA(AlignedInputsMixin, MultiobjectiveSolverBase): ``set_loss`` / ``set_distribution`` / ``push``). Several slices (subspaces) are accepted by the code but have not been used or validated with the unified sampler. + The loader's historical ``MultiObjective`` name is retained; this solver currently uses one + objective. + Takes batches from ``cebra.data.multiobjective.UnifiedContrastiveMultiObjectiveLoader``, in which the samples of all sessions are already aligned and concatenated. From f5f12c1d8e757d6dadc7cdd3d4164b8ad72f38e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Fri, 13 Nov 2026 11:22:45 +0100 Subject: [PATCH 14/27] Remove MLPDecoder class and related imports from sklearn decoder --- cebra/__init__.py | 1 - cebra/integrations/sklearn/decoder.py | 82 --------------------------- 2 files changed, 83 deletions(-) diff --git a/cebra/__init__.py b/cebra/__init__.py index e1202889..6e0388af 100644 --- a/cebra/__init__.py +++ b/cebra/__init__.py @@ -32,7 +32,6 @@ from cebra.integrations.sklearn.cebra import DCL from cebra.integrations.sklearn.decoder import KNNDecoder from cebra.integrations.sklearn.decoder import L1LinearRegressor - from cebra.integrations.sklearn.decoder import MLPDecoder is_sklearn_available = True except ImportError: diff --git a/cebra/integrations/sklearn/decoder.py b/cebra/integrations/sklearn/decoder.py index 09340f8a..03b93238 100644 --- a/cebra/integrations/sklearn/decoder.py +++ b/cebra/integrations/sklearn/decoder.py @@ -30,10 +30,6 @@ import sklearn.base import sklearn.neighbors import torch -import torch.nn as nn -import torch.optim as optim -from torch.utils.data import DataLoader -from torch.utils.data import TensorDataset import cebra.helper @@ -252,81 +248,3 @@ def iter_hyperparams() -> Generator[dict, None, None]: """ for alpha in [0.001, 0.01, 0.1, 1, 10, 100]: yield dict(alpha=alpha) - - -class MLPDecoder(Decoder): - """Decoder implementing a simple MLP in PyTorch.""" - - def __init__( - self, - model_type: str = "two_layers", # "single_linear_layer" or "two_layers" - lr: float = 1e-3, - batch_size: int = 500, - num_epochs: int = 20, - device: str = "cuda", - ): - self.model_type = model_type - self.lr = lr - self.batch_size = batch_size - self.num_epochs = num_epochs - self.device = device if torch.cuda.is_available() else "cpu" - - def _build_model(self, input_dim: int, output_dim: int): - if self.model_type == "single_linear_layer": # Single-layer linear model - return nn.Linear(input_dim, output_dim) - elif self.model_type == "two_layers": # Two-layer MLP with GELU non-linearity - return nn.Sequential( - nn.Linear(input_dim, 32), - nn.GELU(), - nn.Linear(32, output_dim), - ) - else: - raise ValueError(f"Unknown hidden type: {self.hidden}") - - def fit( - self, - X: Union[npt.NDArray, torch.Tensor], - y: Union[npt.NDArray, torch.Tensor], - ) -> "MLPDecoder": - if isinstance(X, np.ndarray): - X = torch.from_numpy(X).float() - if isinstance(y, np.ndarray): - y = torch.from_numpy(y).float() - if y.ndim == 1: - y = y[:, None] - - self.input_dim = X.shape[1] - self.output_dim = y.shape[1] - - self.model_ = self._build_model(self.input_dim, - self.output_dim).to(self.device) - optimizer = optim.Adam(self.model_.parameters(), lr=self.lr) - criterion = nn.MSELoss() - - dataset = TensorDataset(X.to(self.device), y.to(self.device)) - loader = DataLoader(dataset, batch_size=self.batch_size, shuffle=True) - - self.model_.train() - for _ in range(self.num_epochs): - for xb, yb in loader: - optimizer.zero_grad() - pred = self.model_(xb) - loss = criterion(pred, yb) - loss.backward() - optimizer.step() - - return self - - def predict(self, X: Union[npt.NDArray, torch.Tensor]) -> npt.NDArray: - if isinstance(X, np.ndarray): - X = torch.from_numpy(X).float() - self.model_.eval() - with torch.no_grad(): - pred = self.model_(X.to(self.device)).cpu().numpy() - return pred - - @staticmethod - def iter_hyperparams() -> Generator[dict, None, None]: - for lr in [1e-2, 1e-3]: - for hidden in ["single", "two"]: - yield dict(lr=lr, hidden=hidden) From 4e3cd775c6dcd0329b9e9e1329b9c14e441ee5bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Fri, 13 Nov 2026 11:41:19 +0100 Subject: [PATCH 15/27] Refactor attribution models to import Captum classes only when needed and update feature map tests for clarity --- cebra/attribution/attribution_models.py | 14 ++++++---- tests/test_feature_map.py | 34 ++++++++++++++++--------- 2 files changed, 31 insertions(+), 17 deletions(-) diff --git a/cebra/attribution/attribution_models.py b/cebra/attribution/attribution_models.py index b5794052..44903d70 100644 --- a/cebra/attribution/attribution_models.py +++ b/cebra/attribution/attribution_models.py @@ -22,17 +22,12 @@ import dataclasses import time -import cvxpy as cp import numpy as np import scipy.linalg import sklearn.metrics import torch import torch.nn as nn import tqdm -from captum.attr import NeuronFeatureAblation -from captum.attr import NeuronGradient -from captum.attr import NeuronGradientShap -from captum.attr import NeuronIntegratedGradients import cebra import cebra.attribution._jacobian @@ -283,6 +278,7 @@ def _inverse_lsq_cvxpy(matrix: np.ndarray, Returns: np.ndarray: Least squares inverse matrix """ + import cvxpy as cp matrix_param = cp.Parameter((matrix.shape[0], matrix.shape[1])) matrix_param.value = matrix @@ -542,6 +538,8 @@ class NeuronGradientMethod(AttributionMap): def __post_init__(self): super().__post_init__() + from captum.attr import NeuronGradient + self.captum_model = NeuronGradient(forward_func=self.model, layer=self.model) @@ -616,6 +614,8 @@ class FeatureAblationMethod(AttributionMap): def __post_init__(self): super().__post_init__() + from captum.attr import NeuronFeatureAblation + self.captum_model = NeuronFeatureAblation(forward_func=self.model, layer=self.model) @@ -689,6 +689,8 @@ class IntegratedGradientsMethod(AttributionMap): def __post_init__(self): super().__post_init__() + from captum.attr import NeuronIntegratedGradients + self.captum_model = NeuronIntegratedGradients(forward_func=self.model, layer=self.model) @@ -771,6 +773,8 @@ class NeuronGradientShapMethod(AttributionMap): def __post_init__(self): super().__post_init__() + from captum.attr import NeuronGradientShap + self.captum_model = NeuronGradientShap(forward_func=self.model, layer=self.model) diff --git a/tests/test_feature_map.py b/tests/test_feature_map.py index c58e8378..6cf6888c 100644 --- a/tests/test_feature_map.py +++ b/tests/test_feature_map.py @@ -527,8 +527,8 @@ def test_public_api_exports(): @pytest.mark.parametrize("conv", [False, True]) def test_feature_map_methods_agree_with_cebra_attribution(conv): - # M_t = J_t^T W with J_t from CEBRA's "jacobian-based" method (and, for a model without an - # offset, the Captum backend "neuron-gradient"); every `method` option gives the same map. + # M_t = J_t^T W with J_t from CEBRA's "jacobian-based" method; every `method` option gives + # the same map. torch.manual_seed(0) rng = np.random.default_rng(8) model = ConvTanhEncoder(4, 5, left=2, right=1) if conv else MLPEncoder(4, 5) @@ -542,16 +542,6 @@ def test_feature_map_methods_agree_with_cebra_attribution(conv): input_data=neural.clone().requires_grad_(True), output_dimension=5).compute_attribution_map(selected_keys=["jf"])["jf"] expected = np.einsum("tdn,df->tnf", jacobian, W) # J_t^T W, (T_valid, N, F) - if not conv: - gradient = cebra.attribution.init( - "neuron-gradient", - model=model, - input_data=neural.clone().requires_grad_(True), - output_dimension=5).compute_attribution_map()["neuron-gradient"] - np.testing.assert_allclose(np.einsum("tdn,df->tnf", gradient, W), - expected, - rtol=1e-5, - atol=1e-6) for method in feature_map.JACOBIAN_METHODS: per_row = feature_map.feature_attribution_map(solver, @@ -569,3 +559,23 @@ def test_feature_map_methods_agree_with_cebra_attribution(conv): neural, W, method="neuron-gradient") + + +def test_neuron_gradient_backend_matches_jacobian(): + pytest.importorskip("captum") + torch.manual_seed(0) + rng = np.random.default_rng(8) + model = MLPEncoder(4, 5) + neural = torch.randn(30, 4) + W = rng.normal(size=(5, 2)) + jacobian = cebra.attribution.init( + "jacobian-based", + model=model, + input_data=neural.clone().requires_grad_(True), + output_dimension=5).compute_attribution_map(selected_keys=["jf"])["jf"] + gradient = cebra.attribution.init( + "neuron-gradient", + model=model, + input_data=neural.clone().requires_grad_(True), + output_dimension=5).compute_attribution_map()["neuron-gradient"] + np.testing.assert_allclose(gradient, jacobian, rtol=1e-5, atol=1e-6) From c31391f0c5e6cbe602c643d36220896fca193c11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Fri, 13 Nov 2026 12:32:12 +0100 Subject: [PATCH 16/27] Handle masks so that instance owned --- cebra/data/masking.py | 2 ++ tests/test_data_masking.py | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/cebra/data/masking.py b/cebra/data/masking.py index 2abe4715..81012a37 100644 --- a/cebra/data/masking.py +++ b/cebra/data/masking.py @@ -58,6 +58,7 @@ def set_masks( Note: - By default, no masks are applied. + - Mask configuration is local to this dataset instance. - When using the dict format, existing instances of the same mask class are replaced. When using the list format, entries are appended, allowing duplicates with different parameters. @@ -116,6 +117,7 @@ def _create_mask(mask_key: str, params: Any) -> None: # List mode: append semantics; allow duplicates of the same mask class if isinstance(masking, list): + self._masks = list(self._masks) for entry in masking: if isinstance(entry, tuple) and len(entry) == 2: mask_key, params = entry diff --git a/tests/test_data_masking.py b/tests/test_data_masking.py index 24ed7e34..6c54915e 100644 --- a/tests/test_data_masking.py +++ b/tests/test_data_masking.py @@ -66,6 +66,31 @@ def test_masked_mixin_no_masks(): masked_data), "Data should remain unchanged when no masks are applied" +@pytest.mark.parametrize("entry", [ + ("RandomNeuronMask", 0.5), + {"RandomNeuronMask": 0.5}, +]) +def test_list_masks_are_dataset_local(entry, monkeypatch): + monkeypatch.setattr(cebra.data.masking.MaskedMixin, "_masks", []) + train = cebra.data.TensorDataset(torch.ones((10, 20)), + continuous=torch.ones((10, 1))) + valid = cebra.data.TensorDataset(torch.ones((10, 20)), + continuous=torch.ones((10, 1))) + + train.set_masks([entry]) + first_mask = train._masks[0] + train.set_masks([entry]) + + assert len(train._masks) == 2 + assert train._masks[0] is first_mask + assert valid._masks == [] + untouched = cebra.data.TensorDataset(torch.ones((10, 20)), + continuous=torch.ones((10, 1))) + assert untouched._masks == [] + data = torch.ones((10, 20, 30)) + assert torch.equal(valid.apply_mask(data.clone()), data) + + @pytest.mark.parametrize( "mask", ["RandomNeuronMask", "RandomTimestepMask", "NeuronBlockMask"]) def test_masked_mixin_random_mask(mask): From fb82865cbd2947419c6fb55736a39caff59c214e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Fri, 13 Nov 2026 12:47:04 +0100 Subject: [PATCH 17/27] Refactor dtype handling in safe globals to support NumPy<1.25 --- cebra/integrations/sklearn/cebra.py | 10 ++++++---- cebra/solver/base.py | 7 +++---- tests/test_solver.py | 14 ++++++++++++++ 3 files changed, 23 insertions(+), 8 deletions(-) diff --git a/cebra/integrations/sklearn/cebra.py b/cebra/integrations/sklearn/cebra.py index bb422ece..42e6d0b3 100644 --- a/cebra/integrations/sklearn/cebra.py +++ b/cebra/integrations/sklearn/cebra.py @@ -52,14 +52,16 @@ # NOTE(stes): "numpy.dtypes.Int32DType" was added due to this issue with # windows (https://github.com/AdaptiveMotorControlLab/CEBRA/pull/281#issuecomment-3764185072) # on build (windows-latest, torch 2.6.0, python 3.12, latest sklearn) +# NOTE(celia): Derive the same concrete dtype classes from instances to preserve that fix while also +# supporting NumPy<1.25, where the ``np.dtypes`` namespace does not exist. CEBRA_LOAD_SAFE_GLOBALS = [ cebra.data.Offset, torch.torch_version.TorchVersion, np.dtype, - np.dtypes.Int32DType, - np.dtypes.Int64DType, - np.dtypes.Float32DType, - np.dtypes.Float64DType, + type(np.dtype(np.int32)), + type(np.dtype(np.int64)), + type(np.dtype(np.float32)), + type(np.dtype(np.float64)), ] diff --git a/cebra/solver/base.py b/cebra/solver/base.py index 1c58fb32..b9c5c445 100644 --- a/cebra/solver/base.py +++ b/cebra/solver/base.py @@ -59,15 +59,14 @@ # and saved in ``n_features`` or in the training ``log``, then fails to load. These globals let # ``Solver.load`` rebuild numpy scalars, and nothing else. The module of the scalar function is # ``numpy._core`` for files written with numpy>=2 and ``numpy.core`` with numpy<2, so both names -# are listed. +# are listed. Concrete dtype classes are derived from instances to also support numpy<1.25. _CHECKPOINT_SAFE_GLOBALS = [ (_numpy_scalar, "numpy._core.multiarray.scalar"), (_numpy_scalar, "numpy.core.multiarray.scalar"), np.dtype, ] + [ - getattr(np.dtypes, name) - for name in ("Int32DType", "Int64DType", "Float32DType", "Float64DType") - if hasattr(np, "dtypes") + type(np.dtype(dtype)) + for dtype in (np.int32, np.int64, np.float32, np.float64) ] diff --git a/tests/test_solver.py b/tests/test_solver.py index 97e2a3d2..15d9b08d 100644 --- a/tests/test_solver.py +++ b/tests/test_solver.py @@ -419,6 +419,20 @@ def test_unified_session(data_name, model_architecture, loader_initfunc, # ---- checkpoint loading ---- +@pytest.mark.parametrize("dtype", [np.int32, np.int64, np.float32, np.float64]) +@pytest.mark.skipif( + tuple(int(part) for part in torch.__version__.split(".")[:2]) < (2, 6), + reason="torch<2.6 does not support named safe-global tuples") +def test_weights_only_checkpoint_with_numpy_scalar(tmp_path, dtype): + path = tmp_path / "model.pt" + torch.save({"value": dtype(4)}, path) + with torch.serialization.safe_globals( + cebra.solver.base._CHECKPOINT_SAFE_GLOBALS): + checkpoint = torch.load(path, weights_only=True) + assert checkpoint["value"] == dtype(4) + assert type(checkpoint["value"]) is dtype + + def test_load_checkpoint_with_numpy_scalars(tmp_path): # Checkpoints of unified solvers saved before n_features was a Python int store it as a # numpy int64; torch>=2.6 loads with weights_only=True by default. From 4e21ca91b9d4e859e44bc0456348b40763cf3d9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Fri, 13 Nov 2026 12:49:39 +0100 Subject: [PATCH 18/27] Add scheduler state handling in checkpointing and loading --- cebra/solver/base.py | 15 ++++++++++--- tests/test_solver.py | 53 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 3 deletions(-) diff --git a/cebra/solver/base.py b/cebra/solver/base.py index b9c5c445..ed387f7f 100644 --- a/cebra/solver/base.py +++ b/cebra/solver/base.py @@ -330,7 +330,8 @@ class Solver(abc.ABC, cebra.io.HasDevice): criterions in CEBRA, also contains the value of the ``temperature``. tqdm_on: Use ``tqdm`` for showing a progress bar during training. scheduler: An optional PyTorch learning rate scheduler. If set, it is stepped - after every optimizer step (i.e., once per training iteration). + after every optimizer step (i.e., once per training iteration). Its state is + saved and restored when a scheduler is configured on the receiving solver. """ model: torch.nn.Module @@ -356,8 +357,8 @@ def state_dict(self) -> dict: Returns: State dictionary, including the state dictionary of the models and - optimizer. Also contains the training history and the CEBRA version - the model was trained with. + optimizer, and the scheduler when configured. Also contains the training + history and the CEBRA version the model was trained with. """ state_dict = { @@ -369,6 +370,8 @@ def state_dict(self) -> dict: "version": cebra.__version__, "log": self.log, } + if self.scheduler is not None: + state_dict["scheduler"] = self.scheduler.state_dict() if hasattr(self, "n_features"): state_dict["n_features"] = self.n_features @@ -385,6 +388,10 @@ def load_state_dict(self, state_dict: dict, strict: bool = True): and the past loss history for the solver. strict: Make sure all states can be loaded. Set to `False` to allow to partially load the state for all given keys. + + Note: + Scheduler state is restored only when a scheduler is configured and the + checkpoint contains it. Older checkpoints leave the scheduler unchanged. """ def _contains(key): @@ -405,6 +412,8 @@ def _get(key): self.criterion.load_state_dict(_get("criterion")) if _contains("optimizer"): self.optimizer.load_state_dict(_get("optimizer")) + if self.scheduler is not None and "scheduler" in state_dict: + self.scheduler.load_state_dict(_get("scheduler")) # TODO(stes): This will be deprecated at some point; the "log" attribute # holds the same information. if _contains("loss"): diff --git a/tests/test_solver.py b/tests/test_solver.py index 15d9b08d..37cab440 100644 --- a/tests/test_solver.py +++ b/tests/test_solver.py @@ -419,6 +419,59 @@ def test_unified_session(data_name, model_architecture, loader_initfunc, # ---- checkpoint loading ---- +@pytest.mark.parametrize("scheduler_type", ["lambda", "cosine"]) +def test_checkpoint_resumes_scheduler(tmp_path, scheduler_type): + def make_solver(): + model = torch.nn.Linear(4, 3) + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + if scheduler_type == "lambda": + scheduler = torch.optim.lr_scheduler.LambdaLR( + optimizer, lr_lambda=lambda epoch: 0.9**epoch) + else: + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, T_max=10) + return cebra.solver.SingleSessionSolver( + model=model, + criterion=cebra.models.InfoNCE(), + optimizer=optimizer, + scheduler=scheduler) + + original = make_solver() + original.n_features = 4 + for _ in range(4): + original.optimizer.step() + original.scheduler.step() + original.save(str(tmp_path), "model.pt") + + resumed = make_solver() + resumed.load(str(tmp_path), "model.pt") + assert resumed.scheduler.state_dict() == original.scheduler.state_dict() + for _ in range(3): + original.optimizer.step() + original.scheduler.step() + resumed.optimizer.step() + resumed.scheduler.step() + assert resumed.optimizer.param_groups[0]["lr"] == pytest.approx( + original.optimizer.param_groups[0]["lr"]) + + +def test_load_legacy_checkpoint_without_scheduler(): + model = torch.nn.Linear(4, 3) + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + solver = cebra.solver.SingleSessionSolver( + model=model, + criterion=cebra.models.InfoNCE(), + optimizer=optimizer) + checkpoint = solver.state_dict() + assert "scheduler" not in checkpoint + + solver.scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, T_max=10) + scheduler_state = copy.deepcopy(solver.scheduler.state_dict()) + solver.load_state_dict(checkpoint) + assert solver.scheduler.state_dict() == scheduler_state + + @pytest.mark.parametrize("dtype", [np.int32, np.int64, np.float32, np.float64]) @pytest.mark.skipif( tuple(int(part) for part in torch.__version__.split(".")[:2]) < (2, 6), From 592a2e7ddfdc8fdd37487622edcbfff66a1d08ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Fri, 13 Nov 2026 12:52:33 +0100 Subject: [PATCH 19/27] Add scheduler step handling in solver classes and tests --- cebra/solver/base.py | 2 ++ cebra/solver/multiobjective.py | 2 ++ cebra/solver/regularized.py | 2 ++ cebra/solver/supervised.py | 2 ++ tests/test_solver.py | 43 ++++++++++++++++++++++++++++++++++ 5 files changed, 51 insertions(+) diff --git a/cebra/solver/base.py b/cebra/solver/base.py index ed387f7f..838d5233 100644 --- a/cebra/solver/base.py +++ b/cebra/solver/base.py @@ -923,6 +923,8 @@ def step(self, batch: cebra.data.Batch) -> dict: loss = behavior_loss + time_loss loss.backward() self.optimizer.step() + if self.scheduler is not None: + self.scheduler.step() self.history.append(loss.item()) return dict( behavior_pos=behavior_align.item(), diff --git a/cebra/solver/multiobjective.py b/cebra/solver/multiobjective.py index 72c88b99..4f5b3eef 100644 --- a/cebra/solver/multiobjective.py +++ b/cebra/solver/multiobjective.py @@ -363,6 +363,8 @@ def step(self, loss.backward() self.optimizer.step(closure) + if self.scheduler is not None: + self.scheduler.step() self.optimizer.zero_grad() if weights_regularizer is not None: diff --git a/cebra/solver/regularized.py b/cebra/solver/regularized.py index 41284529..bb2d2ead 100644 --- a/cebra/solver/regularized.py +++ b/cebra/solver/regularized.py @@ -78,6 +78,8 @@ def step(self, batch: cebra.data.Batch) -> dict: loss_reg.backward() self.optimizer.step() + if self.scheduler is not None: + self.scheduler.step() self.history.append(loss.item()) stats = dict(pos=align.item(), neg=uniform.item(), diff --git a/cebra/solver/supervised.py b/cebra/solver/supervised.py index 54a2da3a..202da53d 100644 --- a/cebra/solver/supervised.py +++ b/cebra/solver/supervised.py @@ -81,6 +81,8 @@ def step(self, batch) -> dict: loss = self.criterion(prediction, batch["label"].squeeze()) loss.backward() self.optimizer.step() + if self.scheduler is not None: + self.scheduler.step() self.history.append(loss.item()) return dict(total=loss.item()) diff --git a/tests/test_solver.py b/tests/test_solver.py index 37cab440..f0be1d68 100644 --- a/tests/test_solver.py +++ b/tests/test_solver.py @@ -31,6 +31,7 @@ import cebra.datasets import cebra.models import cebra.solver +from cebra.solver.supervised import SupervisedNNSolver # ---- helpers ---- @@ -251,12 +252,15 @@ def test_single_session_hybrid(data_name, loader_initfunc, model_architecture, solver = solver_initfunc(model=model, criterion=criterion, optimizer=optimizer) + solver.scheduler = torch.optim.lr_scheduler.StepLR( + optimizer, step_size=1, gamma=0.5) batch = next(iter(loader)) inference = solver._inference(batch) assert len(inference) == 2 log = solver.step(batch) assert isinstance(log, dict) + assert optimizer.param_groups[0]["lr"] == pytest.approx(5e-4) X = loader.dataset.neural with pytest.raises(ValueError, match="not.*fitted"): @@ -419,6 +423,45 @@ def test_unified_session(data_name, model_architecture, loader_initfunc, # ---- checkpoint loading ---- +@pytest.mark.parametrize("variant", ["regularized", "multiobjective", "unified", "supervised"]) +def test_custom_solver_steps_scheduler(variant, monkeypatch): + model = cebra.models.init("offset1-model", num_neurons=4, num_units=8, + num_output=3) + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + scheduler = torch.optim.lr_scheduler.StepLR( + optimizer, step_size=1, gamma=0.5) + kwargs = dict(model=model, optimizer=optimizer, scheduler=scheduler) + batch = cebra.data.Batch(torch.randn(8, 4, 1), torch.randn(8, 4, 1), + torch.randn(8, 4, 1)) + if variant == "regularized": + solver = cebra.solver.RegularizedSolver( + **kwargs, criterion=cebra.models.InfoNCE(), lambda_JR=0.01) + elif variant in ("multiobjective", "unified"): + criterion = cebra.models.MultiCriterions([{ + "indices": (0, 3), + "contrastive_loss": {"name": "InfoNCE", "kwargs": {}}, + }], mode="contrastive") + solver_type = (cebra.solver.ContrastiveMultiobjectiveSolverxCEBRA + if variant == "multiobjective" else cebra.solver.UnifiedSolverxCEBRA) + solver = solver_type(**kwargs, criterion=criterion, + feature_ranges=[slice(0, 3)], renormalize=False) + batch.positive = [batch.positive] + else: + solver = cebra.solver.SingleSessionSolver( + **kwargs, criterion=torch.nn.MSELoss()) + monkeypatch.setattr(solver, "_inference", + lambda batch: solver.model(batch["neural"])) + batch = {"neural": batch.reference, "label": torch.randn(8, 3)} + initial_epoch = scheduler.last_epoch + for iteration in range(1, 3): + if variant == "supervised": + SupervisedNNSolver.step(solver, batch) + else: + solver.step(batch) + assert scheduler.last_epoch == initial_epoch + iteration + assert optimizer.param_groups[0]["lr"] == pytest.approx(0.1 * 0.5**iteration) + + @pytest.mark.parametrize("scheduler_type", ["lambda", "cosine"]) def test_checkpoint_resumes_scheduler(tmp_path, scheduler_type): def make_solver(): From cd8a6bcaf82871db0286bbf5ecb121a39b919b27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Fri, 13 Nov 2026 12:58:17 +0100 Subject: [PATCH 20/27] Add tests for resampling models to ignore batch size in transformations --- cebra/solver/unified_session.py | 17 +++++++++++------ tests/test_solver.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/cebra/solver/unified_session.py b/cebra/solver/unified_session.py index d9b74d12..ba370510 100644 --- a/cebra/solver/unified_session.py +++ b/cebra/solver/unified_session.py @@ -222,7 +222,8 @@ def _transform_session(self, inputs, labels, pad_before_transform, Returns: Tensor ``(T, output_dimension)`` (``T - len(offset) + 1`` rows without padding) - on the model device. + on the model device. Resampling models produce fewer rows and are evaluated + in one pass to preserve their stride grid, including when wrapped. """ if not isinstance(inputs, list): raise ValueError( @@ -248,7 +249,9 @@ def _transform_session(self, inputs, labels, pad_before_transform, raise ValueError( f"Session {session_id} has {num_samples} samples, fewer than the " f"receptive field of the model ({len(offset)}).") - if batch_size is None: + if batch_size is None or any( + isinstance(module, cebra.models.ResampleModelMixin) + for module in self.model.modules()): batch_size = len(targets) window = torch.arange(-offset.left, offset.right) @@ -420,9 +423,10 @@ def transform(self, inputs: Neural data of all sessions, ``(T_s, N_s)``. labels: Auxiliary variables of all sessions, ``(T_s, d)``, used for the alignment. pad_before_transform: Pad the session edges by replication, so that the output has - one row per sample. + one row per sample before any model downsampling. session_id: Session to embed, between 0 and the number of sessions - 1. batch_size: Output rows per forward pass. ``None``: the whole session at once. + Ignored for resampling models, including wrapped models. random_ties: Break nearest-label ties at random instead of taking the first. Training uses ``True``. seed: Seed of the tie draws. The default 0 gives the same draws in every @@ -431,7 +435,7 @@ def transform(self, Returns: The embedding ``(T, output_dimension)``, with ``T - len(offset) + 1`` rows without - padding. + padding. Resampling models downsample these rows. Example: >>> import torch @@ -732,9 +736,10 @@ def transform(self, inputs: Neural data of all sessions, ``(T_s, N_s)``. labels: Auxiliary variables of all sessions, ``(T_s, d)``, used for the alignment. pad_before_transform: Pad the session edges by replication, so that the output has - one row per sample. + one row per sample before any model downsampling. session_id: Session to embed. Required. batch_size: Output rows per forward pass. ``None``: the whole session at once. + Ignored for resampling models, including wrapped models. random_ties: Break nearest-label ties at random instead of taking the first. Training uses ``True``. seed: Seed of the tie draws. The default 0 gives the same draws in every @@ -742,7 +747,7 @@ def transform(self, seed in all of them. ``None`` is only allowed with ``random_ties=False``. Returns: - The embedding ``(T, output_dimension)``. + The embedding ``(T, output_dimension)``. Resampling models produce fewer rows. Example: >>> # ``solver`` is a fitted UnifiedSolverxCEBRA, ``inputs``/``labels`` diff --git a/tests/test_solver.py b/tests/test_solver.py index f0be1d68..945bb384 100644 --- a/tests/test_solver.py +++ b/tests/test_solver.py @@ -668,6 +668,34 @@ def test_unified_transform_session_shorter_than_window(): pad_before_transform=False) +@pytest.mark.parametrize("wrapped", [False, True]) +@pytest.mark.parametrize("pad", [False, True]) +def test_unified_resampling_transform_ignores_batch_size(wrapped, pad): + inputs, labels = _tied_sessions(lengths=(60, 90, 75)) + module = cebra.models.init("offset40-model-4x-subsample", + num_neurons=12, num_units=8, num_output=4) + kwargs = dict(model=module, criterion=cebra.models.InfoNCE(), + optimizer=torch.optim.Adam(module.parameters())) + if wrapped: + solver = cebra.solver.UnifiedSolverxCEBRA( + **kwargs, feature_ranges=[slice(0, 4)], renormalize=False) + else: + solver = cebra.solver.UnifiedSolver(**kwargs) + solver.n_features, solver.num_sessions = 12, 3 + aligned = solver.aligned_inputs(inputs, labels, session_id=1) + module.eval() + with torch.no_grad(): + expected = cebra.solver.base._not_batched_transform( + model=module, inputs=aligned, pad_before_transform=pad, + offset=module.get_offset()) + assert expected.shape[0] < len(inputs[1]) + for batch_size in (None, 1, 7): + actual = solver.transform( + inputs, labels, session_id=1, batch_size=batch_size, + pad_before_transform=pad) + torch.testing.assert_close(actual, expected) + + def test_unified_transform_random_ties_default_false_and_seed(): inputs, labels = _tied_sessions() solver = _unified_solver(12) From e502c924c1d32a3500ab215a6c13feb14fdca46b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Fri, 13 Nov 2026 13:05:34 +0100 Subject: [PATCH 21/27] Remove unified_time_delta distribution handling from ContrastiveMultiObjectiveLoader --- cebra/data/multiobjective.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/cebra/data/multiobjective.py b/cebra/data/multiobjective.py index 6db7ba51..459b213e 100644 --- a/cebra/data/multiobjective.py +++ b/cebra/data/multiobjective.py @@ -137,12 +137,6 @@ def add_config(self, config): kwargs_distribution['label_name']], delta=kwargs_distribution['delta'], device=self.device) - elif config["distribution"] == "unified_time_delta": - distribution = cebra.distributions.UnifiedSampler( - self.dataset, - kwargs_distribution['time_delta'], - device=self.device, - ) else: raise NotImplementedError( f"Distribution {config['distribution']} is not implemented yet." From 659097b2f05a699254ea3f50a8305522124d3c32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Fri, 13 Nov 2026 13:13:38 +0100 Subject: [PATCH 22/27] Enhance Jacobian computation tests with dropout and training mode handling --- cebra/attribution/_jacobian.py | 9 ++++--- tests/test_attribution.py | 44 ++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/cebra/attribution/_jacobian.py b/cebra/attribution/_jacobian.py index 311e61c5..5562e476 100644 --- a/cebra/attribution/_jacobian.py +++ b/cebra/attribution/_jacobian.py @@ -100,8 +100,8 @@ def compute_jacobian( hybrid_solver: If True, concatenate multiple outputs along dimension 1 output_batch_size: Optional number of output/latent dimensions to process per autograd chunk. If ``None``, process all outputs in one retained - graph as before. Smaller values reduce peak GPU memory without - changing the Jacobian math. + graph as before. Smaller values reduce peak GPU memory for + deterministic evaluation-mode models. Returns: Jacobian matrix as either PyTorch tensor or numpy array @@ -135,7 +135,10 @@ def _forward_outputs(prepared_model, prepared_inputs): output_vars = _forward_outputs(prepared_model, prepared_inputs) n_outputs = int(output_vars.shape[1]) effective_output_batch_size = ( - n_outputs if output_batch_size is None else min(int(output_batch_size), n_outputs) + n_outputs + if output_batch_size is None or any( + module.training for module in prepared_model.modules()) + else min(int(output_batch_size), n_outputs) ) jacob_chunks = [] diff --git a/tests/test_attribution.py b/tests/test_attribution.py index 52d7eff9..9e6eabdd 100644 --- a/tests/test_attribution.py +++ b/tests/test_attribution.py @@ -313,6 +313,50 @@ def test_compute_jacobian_output_batching(output_batch_size): np.testing.assert_allclose(batched, full, atol=1e-10) +@pytest.mark.parametrize("mixed_mode", [False, True]) +def test_compute_jacobian_output_batching_with_dropout(mixed_mode): + torch.manual_seed(0) + model = torch.nn.Sequential(torch.nn.Linear(6, 8), + torch.nn.Dropout(0.5), + torch.nn.Linear(8, 5)) + if mixed_mode: + model.eval() + model[1].train() + x = torch.randn(7, 6) + rng_state = torch.random.get_rng_state() + full = cebra.attribution._jacobian.compute_jacobian( + model, [x.clone().requires_grad_(True)], double_precision=True) + expected_rng_state = torch.random.get_rng_state() + torch.random.set_rng_state(rng_state) + batched = cebra.attribution._jacobian.compute_jacobian( + model, [x.clone().requires_grad_(True)], + output_batch_size=2, + double_precision=True) + np.testing.assert_allclose(batched, full, atol=1e-10) + assert torch.equal(torch.random.get_rng_state(), expected_rng_state) + assert model.training == (not mixed_mode) + assert model[1].training + + +@pytest.mark.parametrize("training", [False, True]) +def test_compute_jacobian_output_batching_forward_count(training): + model = torch.nn.Sequential(torch.nn.BatchNorm1d(6), + torch.nn.Linear(6, 5)) + model.train(training) + forwards = [] + handle = model.register_forward_hook( + lambda module, inputs, output: forwards.append(None)) + try: + cebra.attribution._jacobian.compute_jacobian( + model, [torch.randn(7, 6, requires_grad=True)], + output_batch_size=2, + double_precision=True) + finally: + handle.remove() + assert len(forwards) == (1 if training else 3) + assert model[0].num_batches_tracked.item() == (1 if training else 0) + + def test_compute_jacobian_invalid_output_batch_size(): model = torch.nn.Linear(3, 2) with pytest.raises(ValueError): From 4e8edf35080fc2383973b8cc934ec4c89fe32d4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Fri, 13 Nov 2026 13:24:01 +0100 Subject: [PATCH 23/27] Update UnifiedContrastiveMultiObjectiveLoader to utilize time_delta from kwargs and add tests for time_delta handling --- cebra/data/multiobjective.py | 11 ++++------- tests/test_multiobjective.py | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 7 deletions(-) diff --git a/cebra/data/multiobjective.py b/cebra/data/multiobjective.py index 459b213e..003ec1a0 100644 --- a/cebra/data/multiobjective.py +++ b/cebra/data/multiobjective.py @@ -205,8 +205,9 @@ def add_config(self, config): Args: config: Dict with ``"distribution"``, which must be ``"unified_time_delta"``, and - ``"kwargs"``. Note: ``kwargs["time_delta"]`` and ``kwargs["label_name"]`` are - ignored; the sampler uses the loader's ``time_offset`` and the dataset's + ``"kwargs"``. ``kwargs["time_delta"]`` sets the label-difference offset, + falling back to the loader's ``time_offset`` when omitted. + ``kwargs["label_name"]`` is ignored; the sampler uses the dataset's ``continuous_index``. """ kwargs_distribution = config['kwargs'] @@ -222,13 +223,9 @@ def add_config(self, config): "UnifiedDataset must have 'continuous_index' attribute." ) - # Not handled: the sampler always uses the loader's ``time_offset`` - # (default 10), not ``kwargs['time_delta']``, and always samples on the dataset's primary - # ``continuous_index``; per-objective labels (``label_name`` / ``add_labels``) are ignored. - # Every current launcher passes time_delta=10, so the two agree. distribution = cebra.distributions.UnifiedSampler( self.dataset, - self.time_offset, + kwargs_distribution.get('time_delta', self.time_offset), device=self.device, ) self.distributions.append(distribution) diff --git a/tests/test_multiobjective.py b/tests/test_multiobjective.py index a4c601ac..1d07b392 100644 --- a/tests/test_multiobjective.py +++ b/tests/test_multiobjective.py @@ -130,6 +130,41 @@ def test_finalize(config): assert config.loader.distributions[1].time_delta == 3 +@pytest.mark.parametrize("time_offset,time_delta,expected_delta", [ + (None, 1, 1), + (None, 10, 10), + (None, None, 10), + (4, None, 4), + (4, 2, 2), +]) +def test_unified_config_time_delta(time_offset, time_delta, expected_delta): + dataset = cebra.data.UnifiedxCEBRADataset( + cebra.data.TensorDataset( + torch.randn(100, neurons), + continuous=torch.arange(100).float()[:, None]) + for neurons in (3, 5)) + loader_kwargs = {} if time_offset is None else {"time_offset": time_offset} + loader = cebra.data.UnifiedContrastiveMultiObjectiveLoader( + dataset=dataset, num_steps=1, batch_size=16, **loader_kwargs) + config = MultiObjectiveConfig(loader) + config.set_slice(0, 3) + config.set_loss("FixedCosineInfoNCE", temperature=1.) + distribution_kwargs = {"label_name": "continuous_index"} + if time_delta is not None: + distribution_kwargs["time_delta"] = time_delta + config.set_distribution("unified_time_delta", **distribution_kwargs) + config.push() + config.finalize() + + sampler = loader.distributions[0] + differences = torch.from_numpy(sampler.time_difference) + torch.testing.assert_close( + differences, torch.full_like(differences, expected_delta)) + reference = torch.arange(20, 36).repeat(2, 1) + positive = torch.from_numpy(sampler.sample_conditional(reference.numpy())) + torch.testing.assert_close(positive, reference + expected_delta) + + def test_non_unique_feature_ranges_error(config): config.set_slice(0, 10) config.set_loss("FixedEuclideanInfoNCE", temperature=1.) From a3593e05391bef42ed37d86dafcd09b9c2f27f7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Mon, 16 Nov 2026 08:42:31 +0100 Subject: [PATCH 24/27] Refactor jacobian test to use local keys and update learning rate scheduler handling in solver tests --- tests/test_attribution.py | 10 ++++------ tests/test_solver.py | 13 ++++++++----- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/tests/test_attribution.py b/tests/test_attribution.py index 9e6eabdd..1c248499 100644 --- a/tests/test_attribution.py +++ b/tests/test_attribution.py @@ -231,12 +231,10 @@ def _optimized_and_reference(model, input_data, batch_size, **kwargs): reference.compute_attribution_map(batch_size=batch_size)) -_JACOBIAN_KEYS = ("jf", "jf-convabs", "jf-inv-lsq", "jf-inv-svd", - "jf-convabs-inv-lsq", "jf-convabs-inv-svd") - - @pytest.mark.parametrize("conv", [False, True]) def test_jacobian_batched_optimized_matches_batched(conv): + keys = ("jf", "jf-convabs", "jf-inv-lsq", "jf-inv-svd", "jf-convabs-inv-lsq", + "jf-convabs-inv-svd") torch.manual_seed(0) if conv: model = cebra.models.init("offset10-model", @@ -249,7 +247,7 @@ def test_jacobian_batched_optimized_matches_batched(conv): input_data = torch.randn(70, 6, requires_grad=True) # batch_size does not divide the number of samples: the last batch is smaller. full, reference = _optimized_and_reference(model, input_data, batch_size=32) - for key in _JACOBIAN_KEYS: + for key in keys: np.testing.assert_allclose(full[key], reference[key], rtol=1e-5, atol=1e-6) mean, _ = _optimized_and_reference(model, @@ -257,7 +255,7 @@ def test_jacobian_batched_optimized_matches_batched(conv): batch_size=32, return_full=False) assert mean["num_samples"] == len(reference["jf"]) - for key in _JACOBIAN_KEYS: + for key in keys: np.testing.assert_allclose(mean[key], reference[key].mean(axis=0), rtol=1e-5, diff --git a/tests/test_solver.py b/tests/test_solver.py index 945bb384..f5b99f97 100644 --- a/tests/test_solver.py +++ b/tests/test_solver.py @@ -248,19 +248,22 @@ def test_single_session_hybrid(data_name, loader_initfunc, model_architecture, data.configure_for(model) offset = model.get_offset() criterion = cebra.models.InfoNCE() - optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) + lr, gamma = 1e-3, 0.5 + optimizer = torch.optim.Adam(model.parameters(), lr=lr) solver = solver_initfunc(model=model, criterion=criterion, optimizer=optimizer) + # StepLR with step_size=1 multiplies the learning rate by gamma at every training step. solver.scheduler = torch.optim.lr_scheduler.StepLR( - optimizer, step_size=1, gamma=0.5) + optimizer, step_size=1, gamma=gamma) batch = next(iter(loader)) inference = solver._inference(batch) assert len(inference) == 2 - log = solver.step(batch) - assert isinstance(log, dict) - assert optimizer.param_groups[0]["lr"] == pytest.approx(5e-4) + for n_steps in (1, 2): + log = solver.step(batch) + assert isinstance(log, dict) + assert optimizer.param_groups[0]["lr"] == pytest.approx(lr * gamma**n_steps) X = loader.dataset.neural with pytest.raises(ValueError, match="not.*fitted"): From 2b7f0cd47ae04f8ad7165c35d6828e22bd583882 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Wed, 18 Nov 2026 11:36:59 +0100 Subject: [PATCH 25/27] Update demo notebook thumbnails for unified hippocampus and allen attribution --- docs/source/conf.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/source/conf.py b/docs/source/conf.py index 1b6daaae..3397c334 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -271,8 +271,10 @@ def get_years(start_year=2021): "_static/thumbnails/dandi_demo_monkey.png", "demo_notebooks/Demo_xCEBRA_RatInABox": "_static/thumbnails/xCEBRA.png", - "demo_notebooks/Demo_hippocampus_unified": + "demo_notebooks/Demo_unified_hippocampus": "_static/thumbnails/UnifiedCEBRA.png", + "demo_notebooks/Demo_unified_allen_attribution": + "_static/thumbnails/UnifiedCEBRA_attribution.png", "demo_notebooks/Demo_DeepLabCut_CEBRA": "_static/thumbnails/DeepLabCutCEBRA.png" } From 87a09041075f4dc20543e90afdce28290914451a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Wed, 18 Nov 2026 12:26:26 +0100 Subject: [PATCH 26/27] Add unified demo helper and corresponding tests for Allen dataset --- cebra/datasets/allen/unified_demo.py | 255 +++++++++++++++++++++++++++ tests/test_unified_demo.py | 49 +++++ 2 files changed, 304 insertions(+) create mode 100644 cebra/datasets/allen/unified_demo.py create mode 100644 tests/test_unified_demo.py diff --git a/cebra/datasets/allen/unified_demo.py b/cebra/datasets/allen/unified_demo.py new file mode 100644 index 00000000..512009b4 --- /dev/null +++ b/cebra/datasets/allen/unified_demo.py @@ -0,0 +1,255 @@ +# +# CEBRA: Consistent EmBeddings of high-dimensional Recordings using Auxiliary variables +# © Mackenzie W. Mathis & Steffen Schneider (v0.4.0+) +# Source code: +# https://github.com/AdaptiveMotorControlLab/CEBRA +# +# Please see LICENSE.md for the full license document: +# https://github.com/AdaptiveMotorControlLab/CEBRA/blob/main/LICENSE.md +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +"""Data helpers for the Unified CEBRA attribution demo on the Allen dataset. + +Loads the metadata cache and the event trains, and builds the per-session inputs of the unified model. +Numpy only at import time; ``cebra.data`` and ``scipy`` are imported lazily by the functions that need them. + +Cache file: ``allen_demo_cache.npz``, archived on figshare (see :py:data:`CACHE_URL`). Contents: + (no events: they are read from the processed Allen .mat files, see events_from_visual_drift) + neuron_* (N,) session index (model order), session id, cell class, area, mouse, depth. + session_* (234,) per session; session_n_neurons sums to N. + frame_features (900, 768) DINO ViT-B features, the alignment labels of the unified model. + movie_features (900, 6) z-scored movie features (readout target); names in movie_feature_names. + meta_json provenance and model hyper-parameters (see AllenDemo.meta). + +Typical use in a notebook:: + + from cebra.datasets.allen.unified_demo import load_allen_demo, session_tensor_datasets, TRAIN_REPEATS + demo = load_allen_demo(visual_drift_dir) # events from the processed Allen .mat files + datasets = session_tensor_datasets(demo, TRAIN_REPEATS, device=device) + dataset = cebra.data.UnifiedxCEBRADataset(*datasets) # the trainer's class, 234 sessions +""" +from __future__ import annotations + +import dataclasses +import json +import pathlib +import shutil +import urllib.request +import zipfile +from typing import List, Sequence, Tuple + +import numpy as np + +from cebra.datasets import get_datapath + +# figshare article holding allen_demo_cache.npz and the reference checkpoints: +# https://figshare.com/s/ae8099185f5e2f5e8185 (downloaded as one zip archive) +CACHE_URL = "https://ndownloader.figshare.com/articles/29275358?private_link=ae8099185f5e2f5e8185" +DEFAULT_CACHE = pathlib.Path(get_datapath("allen/allen_demo_cache.npz")) +NEURON_TYPE_DIR = {"Exc": "calcium_excitatory", "Vip": "calcium_inhibitory", "Pvalb": "calcium_inhibitory", + "Sst": "calcium_inhibitory"} +TRAIN_REPEATS = tuple(range(9)) # repeats the unified model was trained on +VALID_REPEAT = 9 # held-out repeat, used for every score + + +@dataclasses.dataclass +class AllenDemo: + events: np.ndarray # (repeats, frames, N) uint8; 10 repeats, 0-8 train, 9 held out + neuron_session_index: np.ndarray # (N,) model-order session index + neuron_session_id: np.ndarray + neuron_cell_class: np.ndarray + neuron_area: np.ndarray + neuron_mouse: np.ndarray + neuron_depth_um: np.ndarray + neuron_mat_column: np.ndarray + session_id: np.ndarray + session_area: np.ndarray + session_cell_class: np.ndarray + session_n_neurons: np.ndarray + session_neuron_start: np.ndarray + session_mouse: np.ndarray + session_depth_um: np.ndarray + frame_features: np.ndarray # (frames, 768) float32 + movie_features: np.ndarray # (frames, 6) float64, z-scored + movie_feature_names: List[str] + meta: dict + + @property + def n_neurons(self) -> int: + return int(self.events.shape[2]) + + @property + def n_sessions(self) -> int: + return int(len(self.session_n_neurons)) + + @property + def n_frames(self) -> int: + return int(self.events.shape[1]) + + +_ARRAY_FIELDS = [f.name for f in dataclasses.fields(AllenDemo) + if f.name not in ("movie_feature_names", "meta")] + + +def load_allen_demo(visual_drift_dir=None, path=DEFAULT_CACHE) -> AllenDemo: + """Read the metadata cache, add the events, and check that the parts agree with each other. + + visual_drift_dir: folder of the processed Allen data (the ``data`` folder with ``calcium_excitatory/`` and + ``calcium_inhibitory/``; the notebook downloads it from figshare). The events are read from its .mat files + (events_from_visual_drift). It may be None only if the cache file itself has an ``events`` array. + """ + with np.load(pathlib.Path(path), allow_pickle=False) as z: + raw = {k: z[k] for k in z.files} + if visual_drift_dir is not None: + raw["events"] = events_from_visual_drift(raw, visual_drift_dir) + elif "events" not in raw: + raise ValueError(f"{path} holds no events: pass visual_drift_dir, the folder with calcium_excitatory/ " + "and calcium_inhibitory/ of the processed Allen data") + missing = [k for k in _ARRAY_FIELDS + ["movie_feature_names", "meta_json"] if k not in raw] + if missing: + raise ValueError(f"{path} is missing keys: {missing}") + demo = AllenDemo( + **{k: raw[k] for k in _ARRAY_FIELDS}, + movie_feature_names=[str(x) for x in raw["movie_feature_names"]], + meta=json.loads(str(raw["meta_json"])), + ) + n = demo.n_neurons + if int(demo.session_n_neurons.sum()) != n: + raise ValueError("session_n_neurons does not sum to the number of neurons") + if demo.events.ndim != 3 or demo.events.dtype != np.uint8: + raise ValueError("events must be (repeats, frames, neurons) uint8") + if demo.frame_features.shape[0] != demo.n_frames or demo.movie_features.shape[0] != demo.n_frames: + raise ValueError("frame_features / movie_features must have one row per frame") + if len(demo.movie_feature_names) != demo.movie_features.shape[1]: + raise ValueError("movie_feature_names does not match movie_features") + return demo + + +def split_sessions(neural: np.ndarray, n_neurons_per_session: Sequence[int]) -> List[np.ndarray]: + """Split the last (neuron) axis into per-session arrays, in model order. + + neural: (T, N) or (R, T, N). Returns views of shape (T, n_i) or (R, T, n_i). + """ + counts = [int(n) for n in n_neurons_per_session] + if sum(counts) != neural.shape[-1]: + raise ValueError(f"sessions have {sum(counts)} neurons, array has {neural.shape[-1]}") + out, start = [], 0 + for n in counts: + out.append(neural[..., start:start + n]) + start += n + return out + + +def repeat_frames(demo: AllenDemo, repeats: Sequence[int] = TRAIN_REPEATS) -> Tuple[np.ndarray, np.ndarray]: + """Stack the chosen repeats in time. + + Returns neural (len(repeats) * 900, N) uint8 and labels (len(repeats) * 900, 768) float32. + The labels are frame_features tiled once per repeat, the same as the trainer's repeat(10, 1). + """ + reps = list(repeats) + neural = demo.events[reps].reshape(-1, demo.n_neurons) + labels = np.tile(demo.frame_features, (len(reps), 1)).astype(np.float32) + return neural, labels + + +def session_arrays(demo: AllenDemo, repeats: Sequence[int] = TRAIN_REPEATS): + """Per-session (neural (T, n_i) uint8, labels (T, 768) float32) pairs, in model order.""" + neural, labels = repeat_frames(demo, repeats) + return [(x, labels) for x in split_sessions(neural, demo.session_n_neurons)] + + +def session_tensor_datasets(demo: AllenDemo, repeats: Sequence[int] = TRAIN_REPEATS, device: str = "cpu"): + """One cebra.data.TensorDataset per session (234), with continuous = DINO labels. + + Pass the list to cebra.data.UnifiedxCEBRADataset(*datasets) (the class the trainer uses). + Offset is left at its default; the model's configure_for() sets it. + """ + import cebra.data # lazy import: the rest of this module needs numpy only + return [ + cebra.data.TensorDataset(neural=x.astype(np.float32), continuous=y, device=device) + for x, y in session_arrays(demo, repeats) + ] + + +def download_cache(url: str = CACHE_URL, path=DEFAULT_CACHE, overwrite: bool = False) -> pathlib.Path: + """Fetch allen_demo_cache.npz from the figshare archive to `path` (skipped if it exists).""" + path = pathlib.Path(path) + if path.exists() and not overwrite: + return path + path.parent.mkdir(parents=True, exist_ok=True) + archive_path = path.with_suffix(".zip.part") + tmp = path.with_suffix(path.suffix + ".part") + try: + with urllib.request.urlopen(url, timeout=600) as r, open(archive_path, "wb") as f: + shutil.copyfileobj(r, f) + if not zipfile.is_zipfile(archive_path): + raise RuntimeError(f"Expected a zip archive from {url}.") + with zipfile.ZipFile(archive_path) as archive: + members = [m for m in archive.namelist() if pathlib.PurePosixPath(m).name == path.name] + if len(members) != 1: + raise RuntimeError(f"Expected one {path.name} in the archive from {url}, found {len(members)}.") + with archive.open(members[0]) as source, open(tmp, "wb") as destination: + shutil.copyfileobj(source, destination) + tmp.replace(path) + finally: + archive_path.unlink(missing_ok=True) + tmp.unlink(missing_ok=True) + return path + + +def events_from_visual_drift(meta, visual_drift_dir) -> np.ndarray: + """Event trains of the demo neurons, read from the processed Allen .mat files. + + meta: an AllenDemo or the cache arrays (needs session_id, session_area, session_cell_class, + session_n_neurons, neuron_mat_column). Each session file is + ``///.mat``; its + ``filtered_traces_days_events[0, 0]`` holds (neurons, 10 repeats x 900 frames) binary events for natural movie + one of session A. The neurons of the model are the columns ``neuron_mat_column`` of each file, in model order. + + Returns (10, 900, N) uint8, i.e. ``AllenDemo.events``. + """ + import scipy.io # lazy: only needed for this route + get = (lambda k: getattr(meta, k)) if isinstance(meta, AllenDemo) else (lambda k: meta[k]) + root = pathlib.Path(visual_drift_dir) + n_per = [int(n) for n in get("session_n_neurons")] + columns = np.asarray(get("neuron_mat_column")) + out, start = [], 0 + for sid, area, cls, n in zip(get("session_id"), get("session_area"), get("session_cell_class"), n_per): + path = root / NEURON_TYPE_DIR[str(cls)] / str(area) / f"{int(sid)}.mat" + if not path.exists(): + raise FileNotFoundError(f"{path} not found: is {root} the visual_drift 'data' folder " + "(with calcium_excitatory/ and calcium_inhibitory/)?") + m = np.asarray(scipy.io.loadmat(str(path))["filtered_traces_days_events"][0, 0]) + if m.shape[1] % 900: + raise ValueError(f"{path}: expected 10 x 900 frames per neuron, got {m.shape[1]}") + cols = columns[start:start + n] + out.append(m[cols].T.reshape(-1, 900, n)) + start += n + return np.concatenate(out, axis=2).astype(np.uint8) + + +def wrapped_window_indices(start: int, end: int, length: int, offset) -> np.ndarray: + """Input samples that give one model output per reference sample of a looping stimulus. + + For a stimulus shown back to back (e.g. movie repeats), the model window of the first and last + samples wraps around: for reference samples ``start`` to ``end - 1``, returns the samples + ``start - left`` to ``end + right - 2`` modulo ``length``. ``offset`` has ``left`` and ``right`` + (a CEBRA ``model.get_offset()``). + """ + left, right = int(offset.left), int(offset.right) + if not 0 <= start < end: + raise ValueError(f"Need 0 <= start < end, got start={start}, end={end}.") + if int(length) <= 0: + raise ValueError(f"length must be positive, got {length}.") + return np.arange(start - left, end + right - 1) % int(length) diff --git a/tests/test_unified_demo.py b/tests/test_unified_demo.py new file mode 100644 index 00000000..230aca12 --- /dev/null +++ b/tests/test_unified_demo.py @@ -0,0 +1,49 @@ +# +# CEBRA: Consistent EmBeddings of high-dimensional Recordings using Auxiliary variables +# © Mackenzie W. Mathis & Steffen Schneider (v0.4.0+) +# Source code: +# https://github.com/AdaptiveMotorControlLab/CEBRA +# +# Please see LICENSE.md for the full license document: +# https://github.com/AdaptiveMotorControlLab/CEBRA/blob/main/LICENSE.md +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import types + +import numpy as np +import pytest + +from cebra.datasets.allen import unified_demo + + +def test_split_sessions(): + neural = np.arange(2 * 5 * 7).reshape(2, 5, 7) + parts = unified_demo.split_sessions(neural, [3, 4]) + assert [p.shape for p in parts] == [(2, 5, 3), (2, 5, 4)] + np.testing.assert_array_equal(np.concatenate(parts, axis=-1), neural) + with pytest.raises(ValueError): + unified_demo.split_sessions(neural, [3, 3]) + + +def test_wrapped_window_indices(): + offset = types.SimpleNamespace(left=2, right=3) + idx = unified_demo.wrapped_window_indices(0, 4, 10, offset) + np.testing.assert_array_equal(idx, [8, 9, 0, 1, 2, 3, 4, 5]) + with pytest.raises(ValueError): + unified_demo.wrapped_window_indices(4, 4, 10, offset) + + +def test_default_cache_in_data_dir(): + assert unified_demo.DEFAULT_CACHE.name == "allen_demo_cache.npz" + assert unified_demo.DEFAULT_CACHE.parent.name == "allen" From 9b18fb5512ffee9029ab14ab27a0bd78206884da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9lia=20Benquet?= Date: Mon, 23 Nov 2026 10:41:22 +0100 Subject: [PATCH 27/27] Move pandas imports to the methods in ca_movie and ca_movie_decoding scripts --- cebra/datasets/allen/ca_movie.py | 3 ++- cebra/datasets/allen/ca_movie_decoding.py | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/cebra/datasets/allen/ca_movie.py b/cebra/datasets/allen/ca_movie.py index 083527ee..1debf11f 100644 --- a/cebra/datasets/allen/ca_movie.py +++ b/cebra/datasets/allen/ca_movie.py @@ -37,7 +37,6 @@ import joblib import numpy as np -import pandas as pd import scipy.io import torch from numpy.random import Generator @@ -127,6 +126,8 @@ def _get_pseudo_mice(self, area: str): """ + import pandas as pd + self.area = area path = pathlib.Path( _DEFAULT_DATADIR diff --git a/cebra/datasets/allen/ca_movie_decoding.py b/cebra/datasets/allen/ca_movie_decoding.py index aefd5d57..9cb4571b 100644 --- a/cebra/datasets/allen/ca_movie_decoding.py +++ b/cebra/datasets/allen/ca_movie_decoding.py @@ -37,7 +37,6 @@ import joblib import numpy as np -import pandas as pd import scipy.io import torch from numpy.random import Generator @@ -182,6 +181,8 @@ def _get_pseudo_mice(self, area, num_movie): """ + import pandas as pd + path = pathlib.Path( _DEFAULT_DATADIR ) / "allen" / "visual_drift" / "data" / "calcium_excitatory" / str(area)