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/_jacobian.py b/cebra/attribution/_jacobian.py index 00102aeb..5562e476 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,76 @@ 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 for + deterministic evaluation-mode models. 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 or any( + module.training for module in prepared_model.modules()) + 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..44903d70 100644 --- a/cebra/attribution/attribution_models.py +++ b/cebra/attribution/attribution_models.py @@ -22,23 +22,46 @@ 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 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): + """Map names as a set (``_`` read as ``-``), or ``None``; raise on unknown names.""" + 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. @@ -255,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 @@ -324,7 +348,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 +357,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 +369,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 +393,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 +411,117 @@ 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 + ) + + return result - result[f"{key}-inv-{method}"], result[ - f'time_inversion_{method}'] = self._inverse(value, - method=method) + +@dataclasses.dataclass +@register("jacobian-based-batched-optimized") +class JFMethodBasedBatchedOptimized(JFMethodBased): + """Jacobian-based attribution computed in mini-batches, with an optional running mean. + + Same results as ``jacobian-based-batched``, with less memory. + """ + + def compute_attribution_map( + self, + batch_size=1024, + return_full=True, + 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( + 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: + 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 @@ -402,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) @@ -476,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) @@ -549,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) @@ -631,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/cebra/attribution/feature_map.py b/cebra/attribution/feature_map.py new file mode 100644 index 00000000..cae5cd23 --- /dev/null +++ b/cebra/attribution/feature_map.py @@ -0,0 +1,538 @@ +# +# 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 ``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.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 + 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 + ``JACOBIAN_METHODS``. + + Returns: + 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. + 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/data/datasets.py b/cebra/data/datasets.py index 8549000f..a19a53c0 100644 --- a/cebra/data/datasets.py +++ b/cebra/data/datasets.py @@ -141,6 +141,23 @@ 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) @@ -304,6 +321,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): @@ -458,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.""" @@ -529,3 +554,119 @@ 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: + 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( + 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/masking.py b/cebra/data/masking.py index 90faf51e..81012a37 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,108 @@ 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, + ) -> 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. Note: - By default, no masks are applied. + - 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. """ - if masking is not None: - for mask_key in masking: + 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): + self._masks = list(self._masks) + 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, @@ -110,6 +189,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) @@ -245,7 +329,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 +430,138 @@ def _select_masking_params(self) -> float: return selected_value +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) + # 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: + """Build a mask that hides the neurons of the selected sessions. + + The same sessions are masked for the whole batch. + + Args: + data: Batch of shape ``(batch_size, n_neurons, offset)``. + + Returns: + Mask of the same shape as ``data``: 0 for masked neurons, 1 otherwise. + """ + 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/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..003ec1a0 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 @@ -171,3 +173,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. + + 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. + """ + + 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 the positive-sample distribution of one objective. + + Args: + config: Dict with ``"distribution"``, which must be ``"unified_time_delta"``, and + ``"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'] + + 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." + ) + + distribution = cebra.distributions.UnifiedSampler( + self.dataset, + kwargs_distribution.get('time_delta', 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/datasets/__init__.py b/cebra/datasets/__init__.py index 5716e399..8b8fb4fe 100644 --- a/cebra/datasets/__init__.py +++ b/cebra/datasets/__init__.py @@ -97,6 +97,7 @@ def get_datapath(path: str = None) -> str: from cebra.datasets.hippocampus import * from cebra.datasets.monkey_reaching import * from cebra.datasets.synthetic_data 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..a2434aa1 100644 --- a/cebra/datasets/allen/single_session_ca.py +++ b/cebra/datasets/allen/single_session_ca.py @@ -116,6 +116,55 @@ def __getitem__(self, index): return self.neural[index].transpose(2, 1) +class SingleSessionAllenCaCortex(SingleSessionAllenCa): + """Single-session Allen calcium data with configurable cortex and neuron type. + + 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: 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__( + 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/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..367f725d 100644 --- a/cebra/distributions/multisession.py +++ b/cebra/distributions/multisession.py @@ -31,7 +31,31 @@ import cebra.distributions as cebra_distr import cebra.io -_device = cebra.io.device() + +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 + + # Prefer the concrete device index from dataset tensors if available. + 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(): + 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 +169,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,19 +183,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)) - 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 @@ -247,9 +274,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 +308,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() @@ -293,9 +321,8 @@ def __init__(self, dataset): self.lengths[0] = 0 self.index = [ - cebra_distr.DiscreteUniform( - dataset.discrete_index.int().to(_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 @@ -370,10 +397,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() @@ -392,13 +419,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 @@ -430,6 +464,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 @@ -438,6 +478,136 @@ 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, + seed: Optional[int] = None): + """ + Args: + 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) + + if not self.random_ties: + 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. @@ -496,6 +666,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,24 +677,24 @@ 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) - - def sample_all_sessions(self, ref_idx: torch.Tensor, - session_id: int) -> torch.Tensor: - """Sample sessions based on a reference session. + return torch.from_numpy(query).to(self.device) - 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 @@ -534,8 +708,9 @@ 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), - device=_device).long() + 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, aligned=True) # same query for all + no time diff added @@ -550,8 +725,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.index[i].search( - 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]) @@ -579,12 +754,12 @@ 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() + device=self.device).long() for session_id in range(self.num_sessions): 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/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/models/jacobian_regularizer.py b/cebra/models/jacobian_regularizer.py index a909a31b..053b3424 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,19 @@ 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) + #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 def _jacobian_vector_product(self, 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/cebra/solver/base.py b/cebra/solver/base.py index 2766cd79..838d5233 100644 --- a/cebra/solver/base.py +++ b/cebra/solver/base.py @@ -36,6 +36,7 @@ from typing import Callable, Dict, List, Literal, Optional, Tuple, Union import literate_dataclasses as dataclasses +import numpy as np import torch import torch.nn.functional as F from torch.utils.data import DataLoader @@ -48,6 +49,34 @@ from cebra.solver.util import Meter from cebra.solver.util import ProgressBar +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. 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, +] + [ + type(np.dtype(dtype)) + for dtype in (np.int32, np.int64, np.float32, np.float64) +] + + +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, offset: cebra.data.Offset, num_samples: int): @@ -300,6 +329,9 @@ 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). Its state is + saved and restored when a scheduler is configured on the receiving solver. """ model: torch.nn.Module @@ -314,6 +346,7 @@ class Solver(abc.ABC, cebra.io.HasDevice): "temperature": [] })) tqdm_on: bool = True + scheduler: Optional[torch.optim.lr_scheduler.LRScheduler] = None def __post_init__(self): cebra.io.HasDevice.__init__(self) @@ -324,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 = { @@ -337,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 @@ -353,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): @@ -373,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"): @@ -499,6 +540,9 @@ 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()) stats = dict( pos=align.item(), @@ -740,7 +784,7 @@ def load(self, logdir: str, filename: str = "checkpoint.pth"): 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 = _load_checkpoint(savepath, map_location=self.device) self.load_state_dict(checkpoint, strict=True) n_features = self.n_features @@ -879,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 98587bd7..4f5b3eef 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` @@ -359,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: @@ -435,6 +441,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: 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/cebra/solver/unified_session.py b/cebra/solver/unified_session.py index 3524700f..ba370510 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 @@ -54,11 +54,225 @@ 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. 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( + 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 or any( + isinstance(module, cebra.models.ResampleModelMixin) + for module in self.model.modules()): + 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" @@ -195,90 +409,52 @@ def transform(self, labels: List[torch.Tensor], pad_before_transform: bool = True, session_id: Optional[int] = None, - batch_size: Optional[int] = 512) -> torch.Tensor: - """Compute the embedding for the `session_id`th session of the dataset. + batch_size: Optional[int] = 512, + 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:`~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``. 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. - - 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 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 + 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. Resampling models downsample these rows. + + 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) - - # 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, @@ -380,3 +556,213 @@ 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 ``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. + + 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. + + 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: + ``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 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 + 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)``. Resampling models produce fewer rows. + + 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/data.rst b/docs/source/api/pytorch/data.rst index 4f35932a..e8f319dc 100644 --- a/docs/source/api/pytorch/data.rst +++ b/docs/source/api/pytorch/data.rst @@ -34,6 +34,20 @@ 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 +-------------------------------- + +The masks (:py:mod:`cebra.data.masking`) are documented under :doc:`Helper functions `. + + Single Session Dataloaders -------------------------------- diff --git a/docs/source/api/pytorch/solvers.rst b/docs/source/api/pytorch/solvers.rst index 1a4445bc..1b14c8e4 100644 --- a/docs/source/api/pytorch/solvers.rst +++ b/docs/source/api/pytorch/solvers.rst @@ -25,6 +25,23 @@ Multi session training :members: :show-inheritance: +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: + +Multi-objective training +------------------------ + +The multi-objective solvers (:py:mod:`cebra.solver.multiobjective`) are documented under +:doc:`Multi-objective models `. + Training utilities ------------------ diff --git a/tests/test_attribution.py b/tests/test_attribution.py index cfb8ad7a..1c248499 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,151 @@ 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)) + + +@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", + 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 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 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) + + +@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): + 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..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): @@ -213,3 +238,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_distributions.py b/tests/test_distributions.py index 656559bb..8e012c9c 100644 --- a/tests/test_distributions.py +++ b/tests/test_distributions.py @@ -26,11 +26,15 @@ 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 +# ---- helpers ---- + + def assert_is_tensor(T, device=None): assert isinstance(T, torch.Tensor) if device is not None: @@ -50,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() @@ -93,6 +100,9 @@ def test_init_index(): assert torch.eq(b, torch.arange(10)).all() +# ---- mixed distributions ---- + + class _TestMixedBase: @functools.cached_property @@ -187,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() @@ -230,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. @@ -276,6 +292,9 @@ def test_single_session_discrete(): pass +# ---- multi-session samplers ---- + + def test_multi_session_time_delta(): pass @@ -323,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): """ @@ -413,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") @@ -424,3 +449,164 @@ 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_random_ties_default_is_true(): + dataset, _ = _tiled_unified_dataset() + 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() + 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]) + + +# ---- 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..6cf6888c --- /dev/null +++ b/tests/test_feature_map.py @@ -0,0 +1,581 @@ +"""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; 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) + + 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") + + +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) 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_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) 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.) diff --git a/tests/test_solver.py b/tests/test_solver.py index cf2c62ad..f5b99f97 100644 --- a/tests/test_solver.py +++ b/tests/test_solver.py @@ -31,6 +31,11 @@ import cebra.datasets import cebra.models import cebra.solver +from cebra.solver.supervised import SupervisedNNSolver + + +# ---- helpers ---- + device = "cpu" @@ -152,6 +157,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) @@ -240,16 +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=gamma) batch = next(iter(loader)) inference = solver._inference(batch) assert len(inference) == 2 - log = solver.step(batch) - assert isinstance(log, dict) + 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"): @@ -263,6 +277,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 +368,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 @@ -401,3 +421,368 @@ 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) + + +# ---- 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(): + 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), + 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. + 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) + + +# ---- 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) + + +@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) + 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