diff --git a/cebra/__init__.py b/cebra/__init__.py index 6e0388af..f55bf7fa 100644 --- a/cebra/__init__.py +++ b/cebra/__init__.py @@ -92,6 +92,10 @@ def __getattr__(key): from cebra.integrations.sklearn.cebra import CEBRA return CEBRA + elif key == "DYSCO": + from cebra.integrations.sklearn.dysco import DYSCO + + return DYSCO elif key == "DCL": from cebra.integrations.sklearn.cebra import DCL @@ -101,7 +105,8 @@ def __getattr__(key): return KNNDecoder elif key == "L1LinearRegressor": - from cebra.integrations.sklearn.decoder import L1LinearRegressor # noqa: F811 + from cebra.integrations.sklearn.decoder import \ + L1LinearRegressor # noqa: F811 return L1LinearRegressor elif not key.startswith("_"): diff --git a/cebra/data/__init__.py b/cebra/data/__init__.py index 145ff835..caa391b0 100644 --- a/cebra/data/__init__.py +++ b/cebra/data/__init__.py @@ -52,3 +52,5 @@ from cebra.data.datasets import * from cebra.data.helper import * from cebra.data.masking import * +from cebra.data.aligned_trials import (AlignedTrialBatch, AlignedTrialDataset, + AlignedTrialLoader, AlignedWindowIndex) diff --git a/cebra/data/aligned_trials.py b/cebra/data/aligned_trials.py new file mode 100644 index 00000000..c29adca5 --- /dev/null +++ b/cebra/data/aligned_trials.py @@ -0,0 +1,342 @@ +# +# 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. +# +"""Explicitly aligned repeated-trial windows for dynamics learning.""" + +import math +import numbers +from dataclasses import dataclass +from typing import Optional, Sequence + +import literate_dataclasses as dataclasses +import torch + +from cebra.data.base import Dataset +from cebra.data.base import Loader + + +def _positive_int(value, name): + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise ValueError(f"{name} must be a positive integer.") + + +def _copy_float(value, device): + if isinstance(value, torch.Tensor): + return value.detach().to(device=device, dtype=torch.float32).clone() + return torch.tensor(value, dtype=torch.float32, device=device) + + +@dataclass +class AlignedWindowIndex: + """Trial identities and core starts; negatives are independent windows.""" + + trials: torch.Tensor + starts: torch.Tensor + negative_trials: torch.Tensor + negative_starts: torch.Tensor + core_length: int + + def to(self, device): + """Move tensor indices to a device, retaining the window length.""" + for name in ('trials', 'starts', 'negative_trials', 'negative_starts'): + setattr(self, name, getattr(self, name).to(device)) + return self + + +@dataclass +class AlignedTrialBatch: + """Raw aligned windows and their core time/control nodes. + + ``observations`` has shape ``(batch, view, raw_time, feature)``; + ``negative`` has shape ``(negative_batch, raw_time, feature)``. Raw time + includes encoder context. Time and controls contain only core nodes. + """ + + observations: torch.Tensor + negative: torch.Tensor + time: torch.Tensor + negative_time: torch.Tensor + controls: Optional[torch.Tensor] + negative_controls: Optional[torch.Tensor] + index: AlignedWindowIndex + + def to(self, device): + """Move data, controls and index metadata together.""" + for name in self.__dataclass_fields__: + value = getattr(self, name) + if value is not None: + setattr(self, name, value.to(device)) + return self + + +class AlignedTrialDataset(Dataset): + """Repeated trials with caller-specified temporal alignment groups. + + Args: + trials: Sequence of finite ``(time, feature)`` arrays. Features share + one observation space; the arrays are not heterogeneous sessions. + alignment_ids: One hashable label per trial. Trials in each group must + have equal lengths and their time indices must already align. + sample_interval: Positive constant time between adjacent samples. + controls: Optional sequence of observed ``(time, control)`` arrays. + time_origin: Time represented by the first sample of every trial. + device: Device holding observations, controls and indexing tensors. + """ + + def __init__(self, + trials: Sequence, + alignment_ids: Sequence, + sample_interval: float, + controls: Optional[Sequence] = None, + time_origin: float = 0., + device: str = 'cpu'): + super().__init__(device=device) + if not math.isfinite(sample_interval) or sample_interval <= 0: + raise ValueError('sample_interval must be finite and positive.') + if not math.isfinite(time_origin): + raise ValueError('time_origin must be finite.') + if len(trials) == 0 or len(alignment_ids) != len(trials): + raise ValueError( + 'Supply one alignment ID for every nonempty trial sequence.') + arrays = [_copy_float(x, device) for x in trials] + if any(x.ndim != 2 or min(x.shape) == 0 or not torch.isfinite(x).all() + for x in arrays): + raise ValueError( + 'Trials must be finite, nonempty (time, feature) arrays.') + if any(x.shape[1] != arrays[0].shape[1] for x in arrays): + raise ValueError( + 'Aligned trials must share an observation feature dimension.') + grouped = {} + for i, label in enumerate(alignment_ids): + if isinstance(label, torch.Tensor): + if label.ndim != 0: + raise ValueError('Tensor alignment IDs must be scalars.') + label = label.item() + if isinstance(label, numbers.Real) and not math.isfinite(label): + raise ValueError('Numeric alignment IDs must be finite.') + try: + grouped.setdefault(label, []).append(i) + except TypeError as error: + raise ValueError('Alignment IDs must be hashable.') from error + self.groups = tuple(tuple(indices) for indices in grouped.values()) + self.group_lengths = tuple( + len(arrays[group[0]]) for group in self.groups) + for group in self.groups: + if len({len(arrays[i]) for i in group}) != 1: + raise ValueError( + 'Trials in each alignment group must have equal lengths.') + self.neural = torch.cat(arrays) + self.lengths = torch.tensor([len(x) for x in arrays], device=device) + self.trial_starts = torch.cat( + (self.lengths.new_zeros(1), self.lengths.cumsum(0)[:-1])) + self.group_index = self.lengths.new_empty(len(arrays)) + for i, group in enumerate(self.groups): + self.group_index[list(group)] = i + self.sample_interval = float(sample_interval) + self.time_origin = float(time_origin) + self.controls = None + if controls is not None: + if len(controls) != len(arrays): + raise ValueError('Supply controls for every trial.') + control_arrays = [_copy_float(u, device) for u in controls] + if any(u.ndim != 2 or u.shape[0] != len(x) or u.shape[1] == 0 or + not torch.isfinite(u).all() + for x, u in zip(arrays, control_arrays)): + raise ValueError( + 'Controls must be finite (trial_time, control) arrays.') + if any(u.shape[1] != control_arrays[0].shape[1] + for u in control_arrays): + raise ValueError('Control feature dimensions must match.') + self.controls = torch.cat(control_arrays) + + @property + def input_dimension(self): + """Number of observation features shared by all trials.""" + return self.neural.shape[1] + + def __len__(self): + """Total observed samples, retaining explicit trial boundaries.""" + return len(self.neural) + + def _indices(self, trials, starts, core_length, context=True): + trials = torch.as_tensor(trials, device=self.neural.device) + starts = torch.as_tensor(starts, device=self.neural.device) + if trials.dtype != torch.long or starts.dtype != torch.long: + raise ValueError('Trial and time indices must be int64 tensors.') + if torch.any((trials < 0) | (trials >= len(self.lengths))): + raise ValueError('Invalid trial index.') + starts = torch.broadcast_to(starts, trials.shape) + left = self.offset.left if context else 0 + right = self.offset.right if context else 1 + if torch.any(starts < left) or torch.any(starts + core_length - 1 + + right > self.lengths[trials]): + raise ValueError( + 'Requested window or encoder context crosses a trial boundary.') + return self.trial_starts[trials][..., None] + starts[ + ..., None] + torch.arange( + -left, core_length - 1 + right, device=self.neural.device) + + def __getitem__(self, index): + """Load individual encoder inputs from explicit (trial, time) pairs.""" + index = torch.as_tensor(index, device=self.neural.device) + if index.ndim != 2 or index.shape[1] != 2: + raise ValueError( + 'Expected explicit (trial, time) pairs with shape (batch, 2).') + idx = self._indices(index[:, 0], index[:, 1], 1) + return self.neural[idx].transpose(-1, -2) + + def load_batch(self, index: AlignedWindowIndex) -> AlignedTrialBatch: + """Load aligned windows without crossing any trial boundaries.""" + _positive_int(index.core_length, 'core_length') + index.to(self.device) + if index.trials.ndim != 2 or index.starts.shape != index.trials.shape[: + 1]: + raise ValueError( + 'Reference indices require (batch, view) trials and (batch,) starts.' + ) + if index.negative_trials.ndim != 1 or index.negative_starts.shape != index.negative_trials.shape: + raise ValueError( + 'Negative trial and start vectors must have matching shapes.') + raw = self._indices(index.trials, index.starts[:, None], + index.core_length) + neg = self._indices(index.negative_trials, index.negative_starts, + index.core_length) + groups = self.group_index[index.trials] + if not torch.all(groups == groups[:, :1]): + raise ValueError( + 'Positive views must belong to the same alignment group.') + if index.trials.shape[1] > 1 and torch.any( + index.trials.sort(dim=1).values.diff(dim=1) == 0): + raise ValueError( + 'Repeated copies of a trial cannot be used as independent views.' + ) + core = self._indices(index.trials, + index.starts[:, None], + index.core_length, + context=False) + neg_core = self._indices(index.negative_trials, + index.negative_starts, + index.core_length, + context=False) + relative = torch.arange(index.core_length, device=self.neural.device) + time = self.time_origin + (index.starts[:, None] + + relative) * self.sample_interval + neg_time = self.time_origin + (index.negative_starts[:, None] + + relative) * self.sample_interval + return AlignedTrialBatch( + self.neural[raw], self.neural[neg], + time[:, None].expand(-1, index.trials.shape[1], -1), neg_time, + None if self.controls is None else self.controls[core], + None if self.controls is None else self.controls[neg_core], index) + + +@dataclasses.dataclass +class AlignedTrialLoader(Loader): + """Uniform alignment-group sampling with distinct views and independent negatives. + + All groups must contain enough views and enough samples for the requested + horizon and encoder context. Singleton groups are supported with + ``num_views=1``. Negative windows use the same group-uniform marginal, + independently of the reference draw; collisions are retained in metadata + for the objective's candidate policy. No unrelated groups are paired as + positive views. ``batch_size_negatives`` counts negative windows. + + Args: + See dataclass fields and the base Loader. + """ + + time_offset: int = dataclasses.field( + default=1, doc='Sample stride; only one is supported.') + rollout_steps: int = dataclasses.field( + default=8, doc='Number of transitions in a core window.') + num_views: int = dataclasses.field( + default=2, doc='Distinct repetitions per reference window.') + seed: int = dataclasses.field( + default=42, doc='Seed for a private CPU sampling generator.') + candidate_mode: str = dataclasses.field( + default='independent', + doc='Independent negative windows or in_batch trajectory candidates.') + + def __post_init__(self): + super().__post_init__() + if self.candidate_mode not in ('independent', 'in_batch'): + raise ValueError('candidate_mode must be independent or in_batch.') + if not isinstance(self.dataset, AlignedTrialDataset): + raise ValueError( + 'AlignedTrialLoader requires an AlignedTrialDataset.') + for name in ('num_steps', 'batch_size', 'rollout_steps', 'num_views'): + _positive_int(getattr(self, name), name) + if self.batch_size_negatives is None: + self.batch_size_negatives = self.batch_size + _positive_int(self.batch_size_negatives, 'batch_size_negatives') + if self.time_offset != 1: + raise ValueError( + 'Aligned-trial sampling currently requires time_offset=1.') + self.generator = torch.Generator(device='cpu').manual_seed(self.seed) + self._check_groups() + + def _check_groups(self): + required = self.rollout_steps + len(self.dataset.offset) + for group, length in zip(self.dataset.groups, + self.dataset.group_lengths): + if len(group) < self.num_views: + raise ValueError( + 'Every group must contain num_views distinct trials; use num_views=1 for singletons.' + ) + if length < required: + raise ValueError( + 'A trial group is too short for rollout and encoder context.' + ) + + def _sample(self, count, views): + trials, starts = [], [] + for group_id in torch.randint(len(self.dataset.groups), (count,), + generator=self.generator).tolist(): + group = self.dataset.groups[group_id] + choice = torch.randperm(len(group), + generator=self.generator)[:views].tolist() + trials.append([group[i] for i in choice]) + lower = self.dataset.offset.left + upper = self.dataset.group_lengths[ + group_id] - self.rollout_steps - self.dataset.offset.right + starts.append( + torch.randint(lower, upper + 1, (), + generator=self.generator).item()) + return torch.tensor(trials, + dtype=torch.long), torch.tensor(starts, + dtype=torch.long) + + def get_indices(self, num_samples: int, num_negatives: int = None): + """Draw reproducible windows; return explicit trial identities and starts.""" + _positive_int(num_samples, 'num_samples') + if num_negatives is None: + num_negatives = self.batch_size_negatives + _positive_int(num_negatives, 'num_negatives') + self._check_groups() + trials, starts = self._sample(num_samples, self.num_views) + if self.candidate_mode == 'in_batch': + negative_trials = torch.empty((0, 1), dtype=torch.long) + negative_starts = torch.empty(0, dtype=torch.long) + else: + negative_trials, negative_starts = self._sample(num_negatives, 1) + return AlignedWindowIndex(trials, starts, negative_trials[:, 0], + negative_starts, self.rollout_steps + 1).to( + self.dataset.device) diff --git a/cebra/dynamics/__init__.py b/cebra/dynamics/__init__.py index f272b92f..6adc9740 100644 --- a/cebra/dynamics/__init__.py +++ b/cebra/dynamics/__init__.py @@ -5,3 +5,4 @@ cebra.registry.add_helper_functions(__name__) from cebra.dynamics.linear import * +from cebra.dynamics.polynomial import PolynomialField, PolynomialFlow, RK4Flow diff --git a/cebra/dynamics/polynomial.py b/cebra/dynamics/polynomial.py new file mode 100644 index 00000000..27e1f0df --- /dev/null +++ b/cebra/dynamics/polynomial.py @@ -0,0 +1,310 @@ +# +# 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. +# +"""Polynomial vector fields and differentiable, fixed-step flow maps. + +The registry exposes a flow map for use with the existing DCL solver. The +underlying vector field is also available for continuous-time diagnostics. +""" + +import itertools +import keyword +import math +from typing import Optional + +import torch +from torch import nn + +from cebra.dynamics import register + + +def _positive_integer(value, name): + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise ValueError(f"{name} must be a positive integer.") + + +class PolynomialField(nn.Module): + """A trainable polynomial vector field with optional observed controls. + + Monomials use increasing total degree and lexicographic combinations of + input indices. For two states, degree two and a bias the order is + ``1, z0, z1, z0*z0, z0*z1, z1*z1``. Controls follow states in the input + vector and participate in the same polynomial library. + + Args: + latent_dim: Number of state coordinates. + degree: Maximum total polynomial degree. + control_dim: Number of observed control coordinates. + include_bias: Include the constant monomial. + """ + + def __init__(self, + latent_dim: int, + degree: int = 2, + control_dim: int = 0, + include_bias: bool = True): + super().__init__() + _positive_integer(latent_dim, "latent_dim") + _positive_integer(degree, "degree") + if isinstance( + control_dim, + bool) or not isinstance(control_dim, int) or control_dim < 0: + raise ValueError("control_dim must be a nonnegative integer.") + if not isinstance(include_bias, bool): + raise ValueError("include_bias must be a boolean.") + self.latent_dim = latent_dim + self.degree = degree + self.control_dim = control_dim + self.include_bias = include_bias + self.terms = tuple( + term for order in range(0 if include_bias else 1, degree + 1) + for term in itertools.combinations_with_replacement( + range(latent_dim + control_dim), order)) + self.coefficients = nn.Parameter( + torch.empty(latent_dim, len(self.terms))) + nn.init.normal_(self.coefficients, std=1e-3) + + def features(self, + state: torch.Tensor, + control: Optional[torch.Tensor] = None) -> torch.Tensor: + """Evaluate monomials, preserving all leading state dimensions. + + Args: + state: State tensor with last dimension ``latent_dim``. + control: Controls with matching leading dimensions and final size + ``control_dim``; required exactly when ``control_dim > 0``. + + Returns: + Monomials with shape ``(*state.shape[:-1], len(terms))``. + """ + if state.ndim < 1 or state.shape[-1] != self.latent_dim: + raise ValueError("The final state dimension must equal latent_dim.") + if not state.is_floating_point(): + raise ValueError("State must have a floating-point dtype.") + if self.control_dim: + if control is None or control.shape != (*state.shape[:-1], + self.control_dim): + raise ValueError( + "Controls must match the state batch shape and control_dim." + ) + if control.dtype != state.dtype or control.device != state.device: + raise ValueError( + "State and controls must have the same dtype and device.") + inputs = torch.cat((state, control), dim=-1) + else: + if control is not None: + raise ValueError("Controls supplied to an autonomous field.") + inputs = state + return torch.stack([ + inputs[..., list(term)].prod( + dim=-1) if term else torch.ones_like(inputs[..., 0]) + for term in self.terms + ], + dim=-1) + + def forward(self, + state: torch.Tensor, + control: Optional[torch.Tensor] = None) -> torch.Tensor: + """Evaluate the vector field at each state and observed control.""" + return self.features(state, control) @ self.coefficients.T + + def equations(self, + precision=6, + threshold=0.0, + variable_names=None, + control_names=None): + """Return one readable differential equation per latent coordinate. + + Args: + precision: Positive number of significant coefficient digits. + threshold: Omit coefficients with absolute value at most this + nonnegative value. This changes only the displayed equations. + variable_names: Unique Python identifiers for states; defaults to + ``z0``, ``z1``, etc. + control_names: Unique Python identifiers for observed controls; + defaults to ``u0``, ``u1``, etc. Must differ from state names. + + Returns: + List of strings such as ``dz0/dt = -10*z0 + 10*z1``. Coefficients + describe the learned latent coordinates and original time units. + No coordinate alignment, sparsification or refitting is applied. + """ + _positive_integer(precision, "precision") + if not math.isfinite(threshold) or threshold < 0: + raise ValueError("threshold must be finite and nonnegative.") + + def names_or_default(names, count, prefix): + if names is None: + return [f"{prefix}{i}" for i in range(count)] + if isinstance(names, str): + raise ValueError("Names must be a sequence of identifiers.") + names = list(names) + if len(names) != count or any( + not isinstance(name, str) or not name.isidentifier() or + keyword.iskeyword(name) for name in names): + raise ValueError( + "Supply one valid identifier per state or control coordinate." + ) + return names + + states = names_or_default(variable_names, self.latent_dim, "z") + names = states + names_or_default(control_names, self.control_dim, "u") + if len(set(names)) != len(names): + raise ValueError("State and control names must be unique.") + monomials = [] + for term in self.terms: + factors = [] + for index, repeated in itertools.groupby(term): + power = len(list(repeated)) + factors.append(names[index] if power == + 1 else f"{names[index]}**{power}") + monomials.append("*".join(factors)) + equations = [] + for name, row in zip(states, self.coefficients.detach().cpu().tolist()): + terms = [] + for coefficient, monomial in zip(row, monomials): + if not math.isfinite(coefficient): + raise ValueError("Cannot display nonfinite coefficients.") + if abs(coefficient) <= threshold: + continue + value = f"{abs(coefficient):.{precision}g}" + term = f"{value}*{monomial}" if monomial else value + sign = "-" if coefficient < 0 else "+" + terms.append((sign, term)) + if terms: + sign, term = terms[0] + rhs = ("-" if sign == "-" else "") + term + rhs += "".join(f" {sign} {term}" for sign, term in terms[1:]) + else: + rhs = "0" + equations.append(f"d{name}/dt = {rhs}") + return equations + + +class RK4Flow(nn.Module): + """A differentiable flow map for a state/control vector field. + + Args: + field: Module accepting ``field(state, control)``. Autonomous calls + receive ``None`` for control. + dt: Positive observation interval, in the field's time units. + substeps: Number of RK4 steps per observation interval. + + ``forward`` advances by one observation interval. ``rollout`` returns + every observation including the initial state, and supports signed time + steps for backward integration. Provided controls are linearly + interpolated between observation nodes at every RK4 stage. + """ + + def __init__(self, field: nn.Module, dt: float = 0.02, substeps: int = 1): + super().__init__() + if not math.isfinite(dt) or dt <= 0: + raise ValueError("dt must be finite and positive.") + _positive_integer(substeps, "substeps") + self.field = field + self.dt = float(dt) + self.substeps = substeps + + def forward(self, state: torch.Tensor) -> torch.Tensor: + """Advance an autonomous state by one configured observation interval.""" + return self.rollout(state, 1)[..., -1, :] + + def rollout(self, + state: torch.Tensor, + num_steps: int, + controls: Optional[torch.Tensor] = None, + dt: Optional[float] = None) -> torch.Tensor: + """Integrate at evenly spaced observation nodes. + + Args: + state: Initial states, shape ``(*batch, latent_dim)``. + num_steps: Positive number of observation intervals. + controls: Shape ``(*batch, num_steps + 1, control_dim)``. For a + negative ``dt``, supply nodes in backward chronological order. + dt: Signed interval override; defaults to the configured interval. + + Returns: + States with shape ``(*batch, num_steps + 1, latent_dim)``. + """ + _positive_integer(num_steps, "num_steps") + step = self.dt if dt is None else float(dt) + if not math.isfinite(step) or step == 0: + raise ValueError( + "The integration interval must be finite and nonzero.") + if state.ndim < 1 or not state.is_floating_point(): + raise ValueError( + "State must be a floating-point tensor with a feature axis.") + if controls is not None: + if controls.ndim != state.ndim + 1 or controls.shape[:-2] != state.shape[:-1] or controls.shape[ + -2] != num_steps + 1: + raise ValueError( + "Controls must match state batch dimensions and include every time node." + ) + h = step / self.substeps + trajectory = [state] + for index in range(num_steps): + for substep in range(self.substeps): + if controls is None: + u0 = um = u1 = None + else: + start, end = controls[..., index, :], controls[..., + index + 1, :] + delta = end - start + u0 = start + (substep / self.substeps) * delta + um = start + ((substep + 0.5) / self.substeps) * delta + u1 = start + ((substep + 1) / self.substeps) * delta + k1 = self.field(state, u0) + k2 = self.field(state + h * k1 / 2, um) + k3 = self.field(state + h * k2 / 2, um) + k4 = self.field(state + h * k3, u1) + state = state + (h / 6) * (k1 + 2 * k2 + 2 * k3 + k4) + trajectory.append(state) + return torch.stack(trajectory, dim=-2) + + +@register("polynomial-flow") +class PolynomialFlow(RK4Flow): + """Polynomial ODE flow compatible with DCL's dynamics-model registry. + + Args: + latent_dim: Number of latent coordinates. + degree: Maximum total polynomial degree. + dt: Positive interval for one application of the flow map. + substeps: Number of RK4 steps per interval. + control_dim: Number of observed controls for explicit rollouts. + include_bias: Include a constant term in the field library. + + The default autonomous map accepts ``(batch, latent_dim)`` states, as + required by the DCL solver. Controlled rollouts use ``rollout`` directly; + DCL's current data loader does not supply control segments. + """ + + def __init__(self, + latent_dim: int, + degree: int = 2, + dt: float = 0.02, + substeps: int = 1, + control_dim: int = 0, + include_bias: bool = True): + super().__init__(PolynomialField(latent_dim, degree, control_dim, + include_bias), + dt=dt, + substeps=substeps) diff --git a/cebra/integrations/sklearn/cebra.py b/cebra/integrations/sklearn/cebra.py index 42e6d0b3..09820dd0 100644 --- a/cebra/integrations/sklearn/cebra.py +++ b/cebra/integrations/sklearn/cebra.py @@ -1515,6 +1515,14 @@ def save(self, "Saving a non-fitted model is not supported.") return checkpoint + @classmethod + def _from_checkpoint(cls, checkpoint, map_location=None): + """Reconstruct an estimator after loading its dictionary checkpoint.""" + if checkpoint.get("metadata", {}).get("estimator") == "DYSCO": + from cebra.integrations.sklearn.dysco import DYSCO + return DYSCO._from_checkpoint(checkpoint, map_location=map_location) + return _load_cebra_with_sklearn_backend(checkpoint) + @classmethod def load(cls, filename: str, @@ -1612,7 +1620,8 @@ def load(cls, "Cannot use 'sklearn' backend a non dictionary-based checkpoint. " f"Please try a different backend. Got: {type(checkpoint)}") - cebra_ = _load_cebra_with_sklearn_backend(checkpoint) + cebra_ = cls._from_checkpoint(checkpoint, + map_location=kwargs.get("map_location")) n_features = cebra_.n_features_ cebra_.solver_.n_features = ([ diff --git a/cebra/integrations/sklearn/dysco.py b/cebra/integrations/sklearn/dysco.py new file mode 100644 index 00000000..8526d0d2 --- /dev/null +++ b/cebra/integrations/sklearn/dysco.py @@ -0,0 +1,451 @@ +# +# 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. +# +"""Scikit-learn entry point for aligned-trial dynamics learning.""" + +import copy +import itertools +import math + +import numpy as np +import torch +from sklearn.utils.validation import check_is_fitted + +import cebra.data +import cebra.models +import cebra.solver +from cebra.dynamics.polynomial import PolynomialFlow +from cebra.integrations.sklearn.cebra import CEBRA +from cebra.integrations.sklearn.utils import check_device +from cebra.models.dysco import DYSCOInfoNCE +from cebra.models.dysco import KDEPotential +from cebra.models.dysco import MLPPotential + + +class DYSCO(CEBRA): + """Learn an encoder and polynomial dynamics from explicitly aligned trials. + + Trials share an observation space and evenly sampled time. Alignment IDs + group repetitions whose time indices already correspond. Optional controls + are observed at every node; no controls are inferred. Heterogeneous sessions + and irregular sampling are outside this interface. + + Args: + model_architecture: Encoder name from the existing CEBRA registry. + Defaults to an unnormalized Euclidean encoder. + output_dimension: Number of latent coordinates. + num_hidden_units: Encoder and optional potential hidden width. + polynomial_degree: Maximum total state/control polynomial degree. + sample_interval: Positive observation interval, in field time units. + rollout_steps: Number of transitions per training window. + integration_substeps: RK4 substeps per observation interval. + num_views: Distinct aligned repetitions per window; one for singletons. + num_positive: Events sampled per reference window. + candidate_mode: ``in_batch`` for submitted candidate sampling, or + ``independent`` for separately sampled negative windows. + bidirectional: Full three-block objective, or forward-only ablation. + potential: ``kde``, ``mlp``, or ``None``. + potential_bandwidth: Fixed positive KDE bandwidth, or automatic if None. + temperature: Positive noise scale, squared before horizon scaling. + negative_temperature: Negative noise scale, defaults to temperature. + batch_size: Reference window count; at least two for in_batch candidates. + batch_size_negatives: Negative event count, defaults to batch_size. + max_iterations: Optimizer updates per fit or partial_fit call. + learning_rate: Adam learning rate. + dynamics_learning_rate: Optional finite, nonnegative Adam rate for + polynomial coefficients; defaults to learning_rate. Encoder and + potential keep learning_rate. + optimizer_kwargs: Adam options as key/value pairs, following CEBRA. + device: CEBRA device string. + random_state: Private initialization and sampling seed. + verbose: Show the common solver progress bar. + pad_before_transform: Preserve input length during embedding transforms. + """ + + def __init__(self, + model_architecture="offset1-model-mse", + output_dimension=3, + num_hidden_units=32, + polynomial_degree=2, + sample_interval=0.02, + rollout_steps=8, + integration_substeps=1, + num_views=2, + num_positive=1, + candidate_mode="in_batch", + bidirectional=True, + potential="kde", + potential_bandwidth=None, + temperature=1.0, + negative_temperature=None, + batch_size=64, + batch_size_negatives=None, + max_iterations=1000, + learning_rate=3e-4, + dynamics_learning_rate=None, + optimizer_kwargs=(("betas", (0.9, 0.999)), ("eps", 1e-8)), + device="cuda_if_available", + random_state=42, + verbose=False, + pad_before_transform=True): + super().__init__(model_architecture=model_architecture, + output_dimension=output_dimension, + num_hidden_units=num_hidden_units, + batch_size=batch_size, + batch_size_negatives=batch_size_negatives, + max_iterations=max_iterations, + learning_rate=learning_rate, + optimizer_kwargs=optimizer_kwargs, + device=device, + verbose=verbose, + temperature=temperature, + distance="euclidean", + pad_before_transform=pad_before_transform) + self.polynomial_degree = polynomial_degree + self.sample_interval = sample_interval + self.rollout_steps = rollout_steps + self.integration_substeps = integration_substeps + self.num_views = num_views + self.num_positive = num_positive + self.candidate_mode = candidate_mode + self.bidirectional = bidirectional + self.potential = potential + self.potential_bandwidth = potential_bandwidth + self.negative_temperature = negative_temperature + self.random_state = random_state + self.dynamics_learning_rate = dynamics_learning_rate + + def _prepare_criterion(self): + if self.potential == "kde": + potential = KDEPotential(self.potential_bandwidth) + elif self.potential == "mlp": + potential = MLPPotential(self.output_dimension, + self.num_hidden_units) + elif self.potential is None: + potential = None + else: + raise ValueError("potential must be kde, mlp, or None.") + return DYSCOInfoNCE(sample_interval=self.sample_interval, + temperature=self.temperature, + negative_temperature=self.negative_temperature, + num_positive=self.num_positive, + num_negatives=self.batch_size_negatives or + self.batch_size, + candidate_mode=self.candidate_mode, + bidirectional=self.bidirectional, + potential=potential, + seed=self.random_state) + + def _initialize(self, num_features, num_controls): + if self.dynamics_learning_rate is not None and ( + not math.isfinite(self.dynamics_learning_rate) or + self.dynamics_learning_rate < 0): + raise ValueError( + "dynamics_learning_rate must be finite and nonnegative.") + self.device_ = check_device(self.device) + with torch.random.fork_rng(devices=[]): + torch.random.default_generator.manual_seed(self.random_state) + self.model_ = cebra.models.init( + self.model_architecture, + num_neurons=num_features, + num_units=self.num_hidden_units, + num_output=self.output_dimension).to(self.device_) + if isinstance(self.model_, cebra.models.ResampleModelMixin): + raise ValueError( + "DYSCO requires one embedding per observation node; resampling encoders are unsupported." + ) + self.dynamics_model_ = PolynomialFlow( + self.output_dimension, + degree=self.polynomial_degree, + dt=self.sample_interval, + substeps=self.integration_substeps, + control_dim=num_controls).to(self.device_) + criterion = self._prepare_criterion().to(self.device_) + optimizer = torch.optim.Adam([ + dict(params=itertools.chain(self.model_.parameters(), + criterion.parameters())), + dict(params=self.dynamics_model_.parameters(), + lr=self.learning_rate if self.dynamics_learning_rate is None + else self.dynamics_learning_rate) + ], + lr=self.learning_rate, + **dict(self.optimizer_kwargs)) + self.solver_name_ = "aligned-trial-dysco" + self.solver_ = cebra.solver.init(self.solver_name_, + model=self.model_, + dynamics_model=self.dynamics_model_, + criterion=criterion, + optimizer=optimizer, + tqdm_on=self.verbose).to(self.device_) + self.offset_ = self.model_.get_offset() + self.control_dimension_ = num_controls + self.label_types_ = [] + self.sampling_state_ = torch.Generator().manual_seed( + self.random_state).get_state() + self._fit_configuration = copy.deepcopy(self.get_params()) + + def _fit_trials(self, X, alignment_ids, controls, reset, callback, + callback_frequency): + if not reset: + self._check_fit_configuration() + device = check_device(self.device) if reset else self.device_ + dataset = cebra.data.AlignedTrialDataset(X, + alignment_ids, + self.sample_interval, + controls=controls, + device=device) + num_controls = 0 if dataset.controls is None else dataset.controls.shape[ + -1] + if reset: + self._initialize(dataset.input_dimension, num_controls) + elif dataset.input_dimension != self.n_features_in_ or num_controls != self.control_dimension_: + raise ValueError( + "Observation and control dimensions must match the fitted model." + ) + self._configure_for_all(dataset, self.model_, is_multisession=False) + loader = cebra.data.AlignedTrialLoader( + dataset=dataset, + num_steps=self.max_iterations, + batch_size=self.batch_size, + batch_size_negatives=self.batch_size_negatives, + rollout_steps=self.rollout_steps, + num_views=self.num_views, + candidate_mode=self.candidate_mode, + seed=self.random_state) + loader.generator.set_state(self.sampling_state_.cpu()) + self._active_window_generator = loader.generator + # Establish metadata before training so callbacks may save even on + # the first fit call, through the standard checkpoint envelope. + self.n_features_ = dataset.input_dimension + self.n_features_in_ = dataset.input_dimension + self.num_sessions_ = None + self.solver_.tqdm_on = self.verbose + try: + self._partial_fit(self.solver_, + self.model_, + loader, + False, + callback=callback, + callback_frequency=callback_frequency) + finally: + self.sampling_state_ = loader.generator.get_state() + del self._active_window_generator + return self + + def _check_fit_configuration(self): + """Reject changes that would reconstruct a different training model.""" + mutable = {"max_iterations", "verbose", "pad_before_transform"} + changed = [ + name for name, value in self.get_params().items() + if name not in mutable and value != self._fit_configuration[name] + ] + if changed: + raise ValueError( + "Fitted DYSCO configuration changed: " + ", ".join(changed) + + ". Call fit to apply new parameters; use to() to move devices.") + + def fit(self, + X, + y=None, + *, + alignment_ids=None, + controls=None, + callback=None, + callback_frequency=None): + """Fit on trial arrays with explicit temporal alignment metadata. + + Args: + X: Sequence of (time, observed_feature) arrays. + y: Unused sklearn target; use alignment_ids explicitly. + alignment_ids: Group label per trial; members must already align. + controls: Optional sequence of (time, control_feature) arrays. + callback: Common CEBRA solver callback. + callback_frequency: Callback interval in optimizer steps. + """ + if y is not None: + raise ValueError( + "Use alignment_ids for explicit aligned-trial metadata.") + if alignment_ids is None: + raise ValueError("alignment_ids must be supplied explicitly.") + # A fresh fit builds new modules and optimizer state. Keep the old + # references until the new loader and training loop have succeeded. + previous = vars(self).copy() + try: + return self._fit_trials(X, alignment_ids, controls, True, callback, + callback_frequency) + except Exception: + self.__dict__ = previous + raise + + def partial_fit(self, + X, + y=None, + *, + alignment_ids=None, + controls=None, + callback=None, + callback_frequency=None): + """Continue training, preserving optimizer and private sampler states.""" + if not hasattr(self, "n_features_"): + return self.fit(X, + y, + alignment_ids=alignment_ids, + controls=controls, + callback=callback, + callback_frequency=callback_frequency) + if y is not None or alignment_ids is None: + raise ValueError( + "Supply alignment_ids explicitly and leave y unset.") + return self._fit_trials(X, alignment_ids, controls, False, callback, + callback_frequency) + + def fit_transform(self, X, y=None, *, alignment_ids=None, controls=None): + """Fit aligned trials and return one embedding array per trial.""" + self.fit(X, y, alignment_ids=alignment_ids, controls=controls) + return self.transform(X) + + def transform(self, X, batch_size=None, session_id=None): + """Embed one recording or a sequence of trials with the shared encoder. + + A two-dimensional recording returns an array. A sequence of trial + arrays, or a three-dimensional array, returns a list of arrays. Trial + lengths may differ; all observations share the same feature space. + """ + if getattr(X, "ndim", None) == 3 or (isinstance(X, (list, tuple)) and + len(X) > 0 and + getattr(X[0], "ndim", None) == 2): + return [ + super(DYSCO, self).transform(trial, + batch_size=batch_size, + session_id=session_id) + for trial in X + ] + return super().transform(X, + batch_size=batch_size, + session_id=session_id) + + def vector_field(self, states, controls=None): + """Evaluate derivatives at latent states, returning a NumPy array.""" + check_is_fitted(self, "n_features_") + reference = next(self.dynamics_model_.parameters()) + states = torch.as_tensor(states, + dtype=reference.dtype, + device=self.device_) + controls = None if controls is None else torch.as_tensor( + controls, dtype=reference.dtype, device=self.device_) + with torch.no_grad(): + return self.dynamics_model_.field(states, controls).cpu().numpy() + + def equations(self, + precision=6, + threshold=0.0, + variable_names=None, + control_names=None): + """Inspect the learned polynomial dynamics as a list of equation strings. + + ``print(*model.equations(), sep="\\n")`` prints the complete field. + Names default to ``z0``, ``z1``, etc., and ``u0``, ``u1`` for controls. + ``precision`` controls significant digits; ``threshold`` hides terms + with absolute coefficients at most that value, without changing the + model. Equations use learned latent coordinates and the time units of + ``sample_interval``. They do not perform coordinate alignment or infer + a sparse model. See + :meth:`cebra.dynamics.polynomial.PolynomialField.equations` for arguments. + """ + check_is_fitted(self, "n_features_") + return self.dynamics_model_.field.equations( + precision=precision, + threshold=threshold, + variable_names=variable_names, + control_names=control_names) + + def rollout(self, states, num_steps, controls=None, direction="forward"): + """Integrate latent initial states, including the initial node. + + Controls are supplied in chronological order. Backward integration starts + at the final state and returns nodes in decreasing-time order. + """ + check_is_fitted(self, "n_features_") + if direction not in ("forward", "backward"): + raise ValueError("direction must be forward or backward.") + reference = next(self.dynamics_model_.parameters()) + states = torch.as_tensor(states, + dtype=reference.dtype, + device=self.device_) + controls = None if controls is None else torch.as_tensor( + controls, dtype=reference.dtype, device=self.device_) + if direction == "backward" and controls is not None: + controls = controls.flip(-2) + step = self.dynamics_model_.dt + if direction == "backward": + step = -step + with torch.no_grad(): + return self.dynamics_model_.rollout(states, + num_steps, + controls=controls, + dt=step).cpu().numpy() + + def to(self, device): + """Move every owned model and criterion through the common solver.""" + check_is_fitted(self, "n_features_") + target = check_device(str(device)) + self.solver_.to(target) + self.solver_.criterion.to(target) + # Torch's optimizer loader casts moment tensors to their parameter + # devices while retaining the appropriate device for scalar steps. + optimizer = self.solver_.optimizer + optimizer.load_state_dict(optimizer.state_dict()) + self.device = self.device_ = target + self._fit_configuration["device"] = target + return self + + def _get_state(self): + self._check_fit_configuration() + state = super()._get_state() + sampling_state = self.sampling_state_ + if hasattr(self, "_active_window_generator"): + sampling_state = self._active_window_generator.get_state() + state.update(control_dimension_=self.control_dimension_, + sampling_state_=sampling_state) + return state + + def _get_state_dict(self): + checkpoint = super()._get_state_dict() + checkpoint["metadata"].update(estimator="DYSCO", dysco_version=1) + return checkpoint + + @classmethod + def _from_checkpoint(cls, checkpoint, map_location=None): + if checkpoint.get("metadata", {}).get("dysco_version") != 1: + raise ValueError( + "Unsupported DYSCO checkpoint version. Unversioned development " + "checkpoints require the matching implementation revision.") + args, state = dict(checkpoint["args"]), checkpoint["state"] + if isinstance(map_location, (str, torch.device)): + args["device"] = str(map_location) + estimator = cls(**args) + estimator._initialize(state["n_features_in_"], + state["control_dimension_"]) + for key, value in state.items(): + if key != "device_": + setattr(estimator, key, value) + estimator.solver_.load_state_dict(checkpoint["state_dict"]) + return estimator diff --git a/cebra/integrations/sklearn/metrics.py b/cebra/integrations/sklearn/metrics.py index d8fd791d..34057868 100644 --- a/cebra/integrations/sklearn/metrics.py +++ b/cebra/integrations/sklearn/metrics.py @@ -29,6 +29,17 @@ import cebra.integrations.sklearn.cebra as cebra_sklearn_cebra import cebra.integrations.sklearn.helpers as cebra_sklearn_helpers +from cebra.models.dysco import DYSCOInfoNCE + + +def _check_standard_infonce(model): + """Keep single-session scoring and its information baseline explicit.""" + criterion = getattr(getattr(model, "solver_", None), "criterion", None) + if isinstance(criterion, DYSCOInfoNCE): + raise NotImplementedError( + "CEBRA InfoNCE/goodness-of-fit metrics do not support DYSCO's " + "aligned-trial objective. Evaluate held-out embeddings, vector " + "fields and rollouts; raw loss is available in solver_.history.") def infonce_loss( @@ -69,6 +80,7 @@ def infonce_loss( """ sklearn_utils_validation.check_is_fitted(cebra_model, "n_features_") + _check_standard_infonce(cebra_model) # score is computed on single session dataset only if isinstance(X, list) and isinstance(X[0], Iterable) and len( @@ -222,6 +234,7 @@ def infonce_to_goodness_of_fit( ValueError: If both ``model`` and ``(batch_size, num_sessions)`` are provided. """ if model is not None: + _check_standard_infonce(model) if batch_size is not None or num_sessions is not None: raise ValueError( "batch_size and num_sessions should not be provided if model is provided." diff --git a/cebra/models/__init__.py b/cebra/models/__init__.py index 2d170e24..1e4a2cd9 100644 --- a/cebra/models/__init__.py +++ b/cebra/models/__init__.py @@ -32,11 +32,14 @@ cebra.registry.add_helper_functions(__name__) -from cebra.models.model import * -from cebra.models.multiobjective import * -from cebra.models.layers import * from cebra.models.criterions import * -from cebra.models.multicriterions import * +from cebra.models.dysco import DYSCOInfoNCE +from cebra.models.dysco import KDEPotential +from cebra.models.dysco import MLPPotential from cebra.models.jacobian_regularizer import * +from cebra.models.layers import * +from cebra.models.model import * +from cebra.models.multicriterions import * +from cebra.models.multiobjective import * cebra.registry.add_docstring(__name__) diff --git a/cebra/models/dysco.py b/cebra/models/dysco.py new file mode 100644 index 00000000..f0409a02 --- /dev/null +++ b/cebra/models/dysco.py @@ -0,0 +1,260 @@ +# +# 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. +# +"""Trajectory contrastive learning using CEBRA's InfoNCE reduction.""" + +import math +from typing import Optional + +import torch +from torch import nn + +from cebra.models.criterions import ContrastiveLoss +from cebra.models.criterions import euclidean_similarity +from cebra.models.criterions import infonce_full_denominator + + +class KDEPotential(nn.Module): + """Log kernel density on detached encoded support, with Scott bandwidth. + + Args: + epsilon: Positive bandwidth, or ``None`` for Scott's isotropic rule. + min_epsilon: Lower bound for an estimated bandwidth. + """ + + def __init__(self, + epsilon: Optional[float] = None, + min_epsilon: float = 1e-6): + super().__init__() + if epsilon is not None and (not math.isfinite(epsilon) or epsilon <= 0): + raise ValueError("epsilon must be finite and positive.") + if not math.isfinite(min_epsilon) or min_epsilon <= 0: + raise ValueError("min_epsilon must be finite and positive.") + self.epsilon = epsilon + self.min_epsilon = min_epsilon + self.register_buffer( + "bandwidth", + torch.tensor(1.0 if epsilon is None else epsilon, + dtype=torch.float32)) + + def forward(self, query, support): + """Evaluate log density; gradients flow through queries only.""" + support = support.detach() + count, dimension = support.shape + if self.epsilon is None: + epsilon = (2 * count**(-2 / (dimension + 4)) * + support.var(dim=0, unbiased=False).mean()).clamp_min( + self.min_epsilon) + else: + epsilon = self.bandwidth.to(query) + _, distances = euclidean_similarity(query, query, support) + return (torch.logsumexp(distances / epsilon, dim=1, keepdim=True) - + math.log(count) - 0.5 * dimension * epsilon.log()) + + +class MLPPotential(nn.Module): + """Centered scalar potential owned by the contrastive criterion. + + Args: + latent_dim: Number of encoded coordinates. + num_hidden_units: Width of one hidden GELU layer. + """ + + def __init__(self, latent_dim: int, num_hidden_units: int = 32): + super().__init__() + self.network = nn.Sequential(nn.Linear(latent_dim, num_hidden_units), + nn.GELU(), + nn.Linear(num_hidden_units, 1, bias=False)) + + def forward(self, query, support=None): + """Evaluate and center the potential over the query batch.""" + value = self.network(query) + return value - value.mean() + + +class DYSCOInfoNCE(ContrastiveLoss): + """Full-denominator trajectory InfoNCE with candidate potential correction. + + The three comparison blocks are forward/encoded, backward/encoded and + forward/backward. Every block uses the concatenated encoded, forward and + backward negative pools. Only the first two blocks receive the potential. + The backward/encoded block deliberately uses the reference time index in + its temperature, matching the submitted DYSCO objective. + + Args: + sample_interval: Positive time between observation nodes. + temperature: Positive noise scale; squared before horizon scaling. + negative_temperature: Negative noise scale; defaults to temperature. + num_positive: Events sampled per reference window. + num_negatives: Number of sampled negative events; defaults to batch size. + candidate_mode: ``in_batch`` uses submitted row-offset sampling for + negative counts divisible by batch size, otherwise uniform rows. + ``independent`` uses separately sampled windows and times. + bidirectional: Include all three blocks; False uses forward/encoded. + potential: Optional module accepting query and detached support. + seed: Seed for checkpointed, private event sampling. + """ + + def __init__(self, + sample_interval=0.02, + temperature=1.0, + negative_temperature=None, + num_positive=1, + num_negatives=None, + candidate_mode="in_batch", + bidirectional=True, + potential=None, + seed=42): + super().__init__() + negative_temperature = temperature if negative_temperature is None else negative_temperature + for name, value in [("sample_interval", sample_interval), + ("temperature", temperature), + ("negative_temperature", negative_temperature)]: + if not math.isfinite(value) or value <= 0: + raise ValueError(name + " must be finite and positive.") + if num_positive is None: + raise ValueError("num_positive must be a positive integer.") + for name, value in [("num_positive", num_positive), + ("num_negatives", num_negatives)]: + if value is not None and (isinstance(value, bool) or + not isinstance(value, int) or value < 1): + raise ValueError(name + " must be a positive integer.") + if candidate_mode not in ("in_batch", "independent"): + raise ValueError("candidate_mode must be in_batch or independent.") + self.sample_interval = float(sample_interval) + self.temperature = float(temperature) + self.negative_temperature = float(negative_temperature) + self.num_positive = num_positive + self.num_negatives = num_negatives + self.candidate_mode = candidate_mode + self.bidirectional = bidirectional + self.potential = potential + self.register_buffer("_sampling_state", + torch.Generator().manual_seed(seed).get_state()) + + def sample_indices(self, encoded, num_candidates): + """Draw event indices without consuming the global Torch generator.""" + batch, views, nodes, _ = encoded.shape + if batch < 2 and self.candidate_mode == "in_batch": + raise ValueError( + "in_batch sampling requires at least two reference windows.") + generator = torch.Generator().set_state(self._sampling_state.cpu()) + + def draw(low, high, count): + return torch.randint(low, high, (count,), generator=generator) + + count = self.num_negatives or batch + references = torch.arange(batch).repeat_interleave(self.num_positive) + if self.candidate_mode == "in_batch": + if count % batch == 0: + offsets = draw(1, batch, count) + negative_rows = (torch.arange(count) * batch // count + + offsets) % batch + else: + negative_rows = draw(0, batch, count) + else: + negative_rows = draw(0, num_candidates, count) + view_offsets = draw(0, views, len(references)) + reference_views = draw(0, views, len(references)) + negative_views = draw(0, + views if self.candidate_mode == "in_batch" else 1, + count) + times = draw(0, nodes, len(references)) + negative_times = draw(0, nodes, count) + support = draw(0, batch * views * nodes, 2 * views * batch) + self._sampling_state.copy_(generator.get_state().to( + self._sampling_state.device)) + result = dict(reference=torch.stack( + (references, reference_views, times)), + positive=torch.stack( + (references, (reference_views + view_offsets) % views, + times)), + negative=torch.stack( + (negative_rows, negative_views, negative_times)), + support=support) + return {key: value.to(encoded.device) for key, value in result.items()} + + def forward(self, ref, pos, neg, indices=None): + """Reduce trajectory comparisons to CEBRA's standard loss/statistics tuple. + + Args: + ref: Encoded windows, shape (batch, view, time, latent). + pos: Forward and optional backward trajectories, shape + (direction, batch, view, time, latent). + neg: Candidate trajectories, shape (estimate, window, time, latent), + ordered encoded, forward, backward. In in_batch mode the window + dimension is the flattened batch/view axis of ref. + indices: Optional explicit event/support indices for numerical audits. + """ + directions = 2 if self.bidirectional else 1 + if ref.ndim != 4 or ref.shape[-2] < 2 or pos.shape != (directions, + *ref.shape): + raise ValueError( + "Expected aligned encoded and predicted trajectory tensors.") + if neg.ndim != 4 or neg.shape[0] != directions + 1 or neg.shape[ + 2:] != ref.shape[2:] or neg.shape[1] < 1: + raise ValueError( + "Candidate trajectories must match time and latent dimensions.") + if self.candidate_mode == "in_batch" and neg.shape[ + 1] != ref.shape[0] * ref.shape[1]: + raise ValueError( + "in_batch candidates must contain every reference view.") + indices = self.sample_indices( + ref, neg.shape[1]) if indices is None else indices + r, p, n = (tuple(indices[key]) + for key in ("reference", "positive", "negative")) + negative_windows = n[0] * ref.shape[1] + n[ + 1] if self.candidate_mode == "in_batch" else n[0] + encoded, forward = ref, pos[0] + references, positives = [forward[r]], [encoded[p]] + if self.bidirectional: + backward = pos[1] + references.extend([backward[r], forward[r]]) + positives.extend([encoded[p], backward[p]]) + candidates = torch.cat( + [estimate[negative_windows, n[2]] for estimate in neg], dim=0) + references, positives = torch.cat(references), torch.cat(positives) + positive_scores, negative_scores = euclidean_similarity( + references, positives, candidates) + horizon = r[2].clamp_min(1) + horizons = torch.cat( + [horizon, horizon, + torch.full_like(horizon, ref.shape[2] - + 1)]) if self.bidirectional else horizon + scale = 2 * self.sample_interval * horizons + positive_scores = positive_scores / (self.temperature**2 * scale) + negative_scores = negative_scores / (self.negative_temperature**2 * + scale[:, None]) + if self.potential is not None: + support = ref.reshape(-1, + ref.shape[-1])[indices["support"]].detach() + corrected = len(r[0]) * (2 if self.bidirectional else 1) + # Center both query sets together to preserve relative logits. + potential = self.potential(torch.cat( + (positives[:corrected], candidates)), + support=support) + positive_scores = torch.cat( + (positive_scores[:corrected] - potential[:corrected].flatten(), + positive_scores[corrected:])) + negative_scores = torch.cat( + (negative_scores[:corrected] - potential[corrected:].T, + negative_scores[corrected:])) + return infonce_full_denominator(positive_scores, negative_scores) diff --git a/cebra/solver/__init__.py b/cebra/solver/__init__.py index 8bc63a42..e774f975 100644 --- a/cebra/solver/__init__.py +++ b/cebra/solver/__init__.py @@ -36,6 +36,7 @@ # pylint: disable=wrong-import-position from cebra.solver.base import * +from cebra.solver.dysco import DYSCOSolver from cebra.solver.multi_session import * from cebra.solver.multiobjective import * from cebra.solver.regularized import * diff --git a/cebra/solver/base.py b/cebra/solver/base.py index 838d5233..c1026d4b 100644 --- a/cebra/solver/base.py +++ b/cebra/solver/base.py @@ -938,6 +938,34 @@ def step(self, batch: cebra.data.Batch) -> dict: class AuxiliaryVariableSolver(Solver): + def state_dict(self) -> dict: + """Save the solver state, including the reference model parameters.""" + state = super().state_dict() + state["reference_model"] = self.reference_model.state_dict() + return state + + def load_state_dict(self, state_dict: dict, strict: bool = True): + """Restore the solver and reference model from a checkpoint. + + Args: + state_dict: Solver checkpoint, including ``reference_model``. + strict: Require reference model parameters. If ``False``, load + available components and warn when the reference model is absent. + """ + if "reference_model" not in state_dict: + message = ( + "Checkpoint is missing reference_model parameters. " + "Legacy auxiliary solver checkpoints did not save them. " + "Use strict=False only to load available components and leave " + "unsaved reference model parameters unchanged.") + if strict: + raise KeyError(message) + warnings.warn(message, UserWarning, stacklevel=2) + else: + self.reference_model.load_state_dict(state_dict["reference_model"], + strict=strict) + super().load_state_dict(state_dict, strict=strict) + @torch.no_grad() def transform(self, inputs: torch.Tensor, diff --git a/cebra/solver/dysco.py b/cebra/solver/dysco.py new file mode 100644 index 00000000..913bd0c7 --- /dev/null +++ b/cebra/solver/dysco.py @@ -0,0 +1,104 @@ +# +# 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. +# +"""Aligned-trial dynamics learning with the common CEBRA solver lifecycle.""" + +import torch + +import cebra.data +from cebra.models.dysco import DYSCOInfoNCE +from cebra.solver import register +from cebra.solver.single_session import SingleSessionDCLSolver + + +@register("aligned-trial-dysco") +class DYSCOSolver(SingleSessionDCLSolver): + """Encode aligned windows and return trajectories to DYSCOInfoNCE. + + Optimization, logging, validation, transform, device handling, and reference + model persistence are inherited from the existing single-session solvers. + The criterion owns its potential and event-sampling state. + """ + + def _encode_windows(self, observations): + offset = len(self.model.get_offset()) + windows = observations.unfold(-2, offset, 1) + shape = windows.shape[:-2] + encoded = self.model(windows.reshape(-1, windows.shape[-2], offset)) + if encoded.ndim == 3 and encoded.shape[-1] == 1: + encoded = encoded.squeeze(-1) + if encoded.ndim != 2: + raise ValueError( + "The encoder must return one embedding per receptive window.") + return encoded.reshape(*shape, encoded.shape[-1]) + + def parameters(self, session_id=None): + """Iterate over the encoder, dynamics and criterion parameters.""" + self._check_is_session_id_valid(session_id) + yield from self.reference_model.parameters() + yield from self.criterion.parameters() + + def _trajectories(self, encoded, controls): + steps = encoded.shape[-2] - 1 + predictions = [ + self.dynamics_model.rollout(encoded[..., 0, :], + steps, + controls=controls) + ] + if self.criterion.bidirectional: + backward_controls = None if controls is None else controls.flip(-2) + backward = self.dynamics_model.rollout(encoded[..., -1, :], + steps, + controls=backward_controls, + dt=-self.dynamics_model.dt) + predictions.append(backward.flip(-2)) + return torch.stack(predictions) + + def _inference(self, batch): + if not isinstance(self.criterion, DYSCOInfoNCE): + raise ValueError("DYSCOSolver requires DYSCOInfoNCE.") + batch.to(self.device) + if self.criterion.sample_interval != self.dynamics_model.dt: + raise ValueError( + "Criterion and dynamics sampling intervals must match.") + encoded = self._encode_windows(batch.observations) + predictions = self._trajectories(encoded, batch.controls) + if self.criterion.candidate_mode == "in_batch": + candidates = torch.cat((encoded[None], predictions), + dim=0).flatten(1, 2) + else: + if batch.negative.shape[0] == 0: + raise ValueError( + "Independent candidates require negative windows.") + negative = self._encode_windows(batch.negative) + negative_predictions = self._trajectories(negative, + batch.negative_controls) + candidates = torch.cat((negative[None], negative_predictions), + dim=0) + return cebra.data.Batch(encoded, predictions, candidates) + + def _set_fitted_params(self, loader): + if loader.dataset.sample_interval != self.dynamics_model.dt: + raise ValueError( + "Dataset and dynamics sampling intervals must match.") + if loader.candidate_mode != self.criterion.candidate_mode: + raise ValueError("Loader and criterion candidate modes must match.") + super()._set_fitted_params(loader) diff --git a/docs/source/api.rst b/docs/source/api.rst index 28b65729..849663ef 100644 --- a/docs/source/api.rst +++ b/docs/source/api.rst @@ -9,8 +9,8 @@ CEBRA has two main APIs: - The low-level ``torch`` API exposes models, layers, loss functions and other components. The ``torch`` API exposes all low-level functions and classes used for training CEBRA models. For **day-to-day use of CEBRA**, it is sufficient to know the high-level ``scikit-learn`` API, which -is currently limited to a single estimator class, :py:class:`cebra.CEBRA`. CEBRA's main -functionalities are covered by this class. +is centered on :py:class:`cebra.CEBRA`. Aligned repeated-trial dynamics learning +is available through :py:class:`cebra.DYSCO`. For machine learning researchers, and everybody with **custom data analysis needs**, we expose all core functions of CEBRA via our ``torch`` API. This allows more fine-grained control over @@ -23,6 +23,7 @@ these components in other contexts and research code bases. :caption: scikit-learn API api/sklearn/cebra + api/sklearn/dysco api/sklearn/metrics api/sklearn/decoder api/sklearn/helpers diff --git a/docs/source/api/pytorch/data.rst b/docs/source/api/pytorch/data.rst index e8f319dc..67e244fa 100644 --- a/docs/source/api/pytorch/data.rst +++ b/docs/source/api/pytorch/data.rst @@ -70,3 +70,52 @@ Datatypes .. automodule:: cebra.data.datatypes :members: :show-inheritance: + + +Aligned repeated trials +----------------------- + +``AlignedTrialDataset`` represents repeated trials in a shared observation +feature space. The caller supplies alignment groups and a sample interval; +trials within each group must already be temporally aligned and have equal +lengths. Groups may have different lengths. This is separate from heterogeneous +multi-session data. + +.. code-block:: python + + import numpy as np + from cebra.data import AlignedTrialDataset, AlignedTrialLoader, Offset + + trials = [np.zeros((100, 5), dtype="float32") for _ in range(4)] + dataset = AlignedTrialDataset(trials, alignment_ids=[0, 0, 1, 1], + sample_interval=0.02) + dataset.offset = Offset(2, 3) # Or dataset.configure_for(encoder). + loader = AlignedTrialLoader(dataset, num_steps=10, batch_size=16, + batch_size_negatives=32, rollout_steps=8, + num_views=2, seed=42) + batch = next(iter(loader)) + assert batch.observations.shape == (16, 2, 13, 5) + assert batch.time.shape == (16, 2, 9) + assert batch.negative.shape == (32, 13, 5) + +A core window has ``rollout_steps + 1`` nodes. Raw observations include the +encoder's receptive context; controls and times cover the core nodes only. +Views are distinct trials from the same group at the same indices. Set +``num_views=1`` for singleton groups. Impossible view counts and windows are +rejected; no trial boundary is padded or crossed implicitly. + +Reference groups are sampled uniformly, then valid starts and distinct trials +are selected within the group. Negative windows are sampled independently from +the same group-uniform marginal; ``batch_size_negatives`` counts windows. The +returned index metadata retains trial identities and starts, including any +candidate collisions, for the contrastive objective's exclusion policy. This +loader does not define the DYSCO loss or claim submitted-objective parity. + +The private CPU random generator is independent of global Torch seeding and +advances across iterations. Its state can be captured with +``loader.generator.get_state()`` and restored with ``set_state``. Observation, +control, time and index tensors follow device transfers. + +.. automodule:: cebra.data.aligned_trials + :members: + :show-inheritance: diff --git a/docs/source/api/pytorch/dynamics.rst b/docs/source/api/pytorch/dynamics.rst index d3cd6fd2..56d4532b 100644 --- a/docs/source/api/pytorch/dynamics.rst +++ b/docs/source/api/pytorch/dynamics.rst @@ -10,7 +10,7 @@ applied to the reference samples during training and selected by name via :show-inheritance: Registration and initialization -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. autofunction:: init @@ -23,4 +23,69 @@ Models .. automodule:: cebra.dynamics.linear :members: - :show-inheritance: \ No newline at end of file + :show-inheritance: + +Polynomial vector fields and flow maps +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``polynomial-flow`` integrates a continuous-time polynomial vector field using +fixed-step RK4. Its forward method returns the state after one interval, so it +can be used by the existing DCL solver: + +.. code-block:: python + + from cebra.integrations.sklearn.cebra import DCL + + model = DCL(dynamics_model_architecture="polynomial-flow", + distance="euclidean", output_dimension=3) + +The registered defaults are degree two, an interval of 0.02 and one RK4 step +per interval. The current DCL estimator constructs registry models with only +``latent_dim``. Configure other values through the low-level API: + +.. code-block:: python + + import torch + from cebra.dynamics.polynomial import PolynomialFlow + + flow = PolynomialFlow(latent_dim=3, degree=2, dt=0.01, substeps=4) + z = torch.randn(8, 3) + derivative = flow.field(z) + next_state = flow(z) + trajectory = flow.rollout(z, num_steps=20) # (8, 21, 3) + +``dt`` is the time interval represented by one map application. In DCL it must +be interpreted together with the sampler's temporal offset. Polynomial +coefficients have the corresponding time units. A stable numerical step does +not guarantee bounded long-term dynamics; check step refinement and rollout +behavior for the learned field. + +For controlled fields, set ``control_dim`` and supply every control node to +``rollout``. Controls are linearly interpolated at intermediate RK4 stages. +The control array has shape ``(*batch, num_steps + 1, control_dim)``. Negative +``dt`` integrates backward; reverse the control-node order as well. DCL's +existing sampler does not pass control segments to the registered map. + +This component supplies polynomial dynamics for DCL and aligned-trial DYSCO +training. See :doc:`../sklearn/dysco` for the trajectory objective, candidate +potential, aligned-trial sampling and public estimator. +Polynomial coefficients are directly trainable; this component does not +perform sparsification or select a symbolic library automatically. + +Checkpoint behavior +~~~~~~~~~~~~~~~~~~~ + +Auxiliary solver checkpoints include ``reference_model``. For both minibatch +and full-batch DCL solvers, this contains the encoder and dynamics parameters. +Historical auxiliary solver checkpoints omitted the reference model and cannot +restore its unsaved parameters, including trained DCL dynamics. Strict loading +raises an explanatory error. Low-level +``solver.load_state_dict(checkpoint, strict=False)`` loads the available +components and warns that unsaved reference model parameters retain their +current values. Solvers without an auxiliary reference model are unchanged. For low-level custom +flows, reconstruct the same field/interval/substep configuration before loading +its state dictionary. + +.. automodule:: cebra.dynamics.polynomial + :members: + :show-inheritance: diff --git a/docs/source/api/sklearn/dysco.rst b/docs/source/api/sklearn/dysco.rst new file mode 100644 index 00000000..d1d7c014 --- /dev/null +++ b/docs/source/api/sklearn/dysco.rst @@ -0,0 +1,189 @@ +DYSCO: aligned-trial dynamics +============================= + +DYSCO jointly trains a CEBRA encoder and a continuous-time polynomial vector +field. Training uses aligned repeated trials in a shared observation space, +with evenly sampled time and optional observed controls. Time alignment is +supplied by the caller: giving two recordings the same label does not align +them automatically. + +Quick start +----------- + +The following example generates its own observations: + +.. code-block:: python + + import numpy as np + import cebra + + rng = np.random.default_rng(4) + time = np.arange(100) * 0.05 + signal = np.column_stack([np.cos(time), np.sin(time), np.cos(2 * time)]) + trials = [(signal + 0.02 * rng.normal(size=signal.shape)).astype("float32") + for _ in range(4)] + model = cebra.DYSCO(model_architecture="offset1-model-mse", + output_dimension=2, temperature=0.1, sample_interval=0.05, + rollout_steps=4, batch_size=16, max_iterations=100, + device="cpu") + model.fit(trials, alignment_ids=[0, 0, 0, 0]) + embedding = model.transform(trials[0]) + derivative = model.vector_field(embedding) + forecast = model.rollout(embedding[0], num_steps=10) + print(*model.equations(precision=4, threshold=0.01), sep="\n") + model.save("dysco.pt") + restored = cebra.DYSCO.load("dysco.pt", map_location="cpu") + +``trials`` contains arrays of shape ``(time, observed_feature)``. Repetitions +within each alignment group must have equal time support; different groups +can have different lengths. Set ``num_views=1`` for singleton groups. Controls, +when present, are supplied as a sequence of ``(time, control_feature)`` arrays +via ``fit(..., controls=controls)``. Field evaluation requires a control value +per state; rollout requires all control nodes including both endpoints. +Backward rollout starts at the final state, takes chronologically ordered +controls, and returns nodes in decreasing-time order. +``transform(trials)`` returns one embedding array per trial, using the same +encoder as ``transform(trials[0])``. + +Views and the shared encoder +---------------------------- + +The aligned loader retains observations as ``(batch, view, raw_time, feature)``. +Each row chooses one alignment group and one start time, then draws distinct +repetitions from that group. Every view in a row has corresponding time nodes; +views are repetitions in one observation space, with one shared encoder. + +For an encoder receptive width ``R`` and ``K`` rollout transitions, the raw +window has ``K + R`` samples. Unfolding creates ``K + 1`` receptive windows. +Only the encoder call flattens batch, view and core time into a single sample +axis: ``(B*V*(K+1), feature, R)``. Its output is immediately reshaped to +``(B, V, K+1, latent)``. The field and RK4 preserve the leading batch/view +axes; forward and backward predictions add a direction axis. Positive-event +sampling can then select corresponding times in different views explicitly. + +The shared solver loop calls a three-argument criterion through ``Batch``. +The DYSCO inference adapter places encoded trajectories in ``reference``, +predicted trajectories in ``positive``, and candidate trajectories in +``negative``. DYSCOInfoNCE constructs actual positive/negative events from these +arrays. These slots therefore carry trajectory inputs, rather than already +selected positive/negative pairs. This adapter keeps optimizer updates, +callbacks, logging and validation in the existing solver. Generic losses and +batch-inspection code cannot assume the ordinary two-dimensional embeddings. + +Training and sampling conventions +--------------------------------- + +The default bidirectional loss compares forward predictions with encoded +states, backward predictions with encoded states, and forward with backward +predictions. Every comparison sees the concatenation of encoded, forward and +backward negative candidates. CEBRA's existing squared Euclidean similarity +and stabilized full-denominator InfoNCE reduction are reused. + +``temperature`` and ``negative_temperature`` are noise scales. Their squares +are multiplied by twice the physical reference horizon before dividing the +scores. The submitted convention uses the sampled reference index for both +encoded comparison blocks, including the backward block, and the complete +window horizon for forward/backward comparison. Index zero uses one time step. +This convention is explicit to preserve numerical compatibility with the +submitted objective. ``bidirectional=False`` selects the forward-only ablation. + +``candidate_mode="in_batch"`` samples events from the encoded reference windows +and preserves the submitted row-offset sampling rule, including within-view +positives and independently sampled negative times. The negative pool is +shared across score rows. Duplicate physical windows and positive/negative +collisions are retained; there is no implicit collision mask. +``batch_size_negatives`` controls the candidate event count independently of +``batch_size``. For integer multiples of the batch size, event draws match the +submitted row-offset rule. Other counts use uniform row draws, preserving the +candidate marginal without assigning unequal sampling weights to windows. +No separate negative windows are materialized in this mode. +``candidate_mode="independent"`` instead samples additional windows through +the aligned-trial loader; this is an explicitly different sampling policy. + +Choose noise scales and horizons for the time and state units of the dataset. +The default ``offset1-model-mse`` encoder allows unconstrained Euclidean latent +coordinates. A normalized encoder constrains coordinates to a unit sphere and +changes the representational assumptions of the polynomial state model. + +The default KDE potential corrects candidate scores in the first two blocks. +Its encoded support is detached, while query and rollout gradients remain +active. ``potential="mlp"`` selects a learned centered potential; ``None`` +disables the correction. Positive and negative queries share one potential +evaluation and centering constant. This corrects the separately centered MLP +queries in the submitted implementation; the frozen uncentered-potential and +KDE parity tests remain unchanged. The criterion owns potential parameters. + +Lifecycle and scope +------------------- + +The estimator reuses CEBRA's encoder registry, model configuration, solver +training loop, callbacks, embedding transform and checkpoint envelope. Its +solver inherits reference-model persistence: the encoder and dynamics are +registered in ``reference_model``. Potential parameters and the private event +sampler state belong to ``criterion``. Checkpoints also preserve optimizer +state, window-sampler state and constructor configuration. ``partial_fit`` +continues from these states, while ``fit`` initializes a new model. The default +encoder's subsequent updates are tested to match after save/load. Stochastic +encoder layers can also depend on the external Torch random state. +Snapshots taken inside training callbacks read the live window sampler. +``to(device)`` also migrates Adam moments before continued training. +Changing construction or objective parameters with ``set_params`` requires +``fit``; ``partial_fit`` rejects such changes. Iteration count, verbosity and +transform padding may change during continuation. +Checkpoints identify the DYSCO objective/format version. Unversioned local +development checkpoints require their matching code revision; loading them +into this corrected objective is rejected explicitly. + +The vector field uses directly trainable polynomial coefficients. Numerical +loss and gradient tests use frozen fixtures from the submitted research code; +these tests do not reproduce the paper's recovery experiments. Direct +coefficient optimization is an intentional parameterization choice. Inspect +the coefficient tensor through ``model.dynamics_model_.field.coefficients`` or +print equations with ``print(*model.equations(), sep="\n")``. Equations use the +learned latent coordinates and the time units of ``sample_interval``. Custom +``variable_names`` and ``control_names`` label coordinates without transforming +them. ``threshold`` and ``precision`` affect display only; they do not fit a +sparse field or recover the physical coordinate system. +``dynamics_learning_rate`` optionally gives polynomial coefficients their own +Adam rate; encoder and potential use ``learning_rate``. This uses ordinary +optimizer parameter groups, preserving direct coefficient optimization. +The default ``None`` gives all parameters the same rate. + +This first interface supports polynomial fields, observed controls, aligned +trials and one embedding per observation node. Irregular time, heterogeneous +observation spaces, resampling encoders, latent inferred controls, symbolic +library selection and affine-gauge sparsification are outside its scope. + +An offline autonomous/controlled oscillator example with held-out diagnostics +is available in ``tests/examples/dysco_sklearn_example.py``. It reports +embedding and transported-field R-squared, short-rollout error and a persistence +comparison; these are bounded diagnostics rather than recovery guarantees. + +The Lorenz example ``tests/examples/dysco_lorenz_example.py`` generates repeated +noisy observations through a shared linear mixing map, fits a quadratic field, +prints its equations and saves a checkpoint, diagnostics and a figure. Run it +with ``--output lorenz-example``. Ground-truth states are used only for a +training-set affine evaluation map and held-out diagnostics. Repeated-trial and +unseen-initial-condition results are reported separately, including field +agreement and forecasts against persistence. This is a demonstration with +linear observations and deterministic Lorenz trajectories. + +The ordinary CEBRA ``infonce_loss`` and goodness-of-fit helpers reject this +aligned-trial objective: their data loaders and information baseline do not +apply. Raw DYSCO training loss is available through ``model.solver_.history``; +scientific validation should assess held-out embeddings, fields and rollouts. + +API reference +------------- + +.. autoclass:: cebra.DYSCO + :members: + :show-inheritance: + +.. automodule:: cebra.models.dysco + :members: + :show-inheritance: + +.. automodule:: cebra.solver.dysco + :members: + :show-inheritance: diff --git a/tests/examples/dysco_lorenz_example.py b/tests/examples/dysco_lorenz_example.py new file mode 100644 index 00000000..b46da57b --- /dev/null +++ b/tests/examples/dysco_lorenz_example.py @@ -0,0 +1,235 @@ +# +# 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. +# +"""Learn polynomial dynamics from noisy, repeated Lorenz observations. + +Run ``python tests/examples/dysco_lorenz_example.py --output lorenz-example``. +The script generates all data locally and writes equations, a checkpoint, +held-out diagnostics and a figure. True states are used only for evaluation. +This small example uses linear observation mixing and deterministic dynamics; +it does not reproduce the paper's noisy nonlinear observation experiments. +""" + +import argparse +import json +import time +from pathlib import Path + +import numpy as np + +import cebra + + +def lorenz(states): + """Evaluate the standard Lorenz field in physical state and time units.""" + x, y, z = np.moveaxis(np.asarray(states), -1, 0) + return np.stack((10 * (y - x), x * (28 - z) - y, x * y - 8 * z / 3), + axis=-1) + + +def simulate(initial, length=1200, dt=0.01, burn_in=300): + """Integrate the field with two RK4 substeps per recorded interval.""" + state = np.asarray(initial, dtype=float) + trajectory = [] + for index in range(length + burn_in): + if index >= burn_in: + trajectory.append(state.copy()) + for _ in range(2): + h = dt / 2 + k1 = lorenz(state) + k2 = lorenz(state + h * k1 / 2) + k3 = lorenz(state + h * k2 / 2) + k4 = lorenz(state + h * k3) + state = state + h * (k1 + 2 * k2 + 2 * k3 + k4) / 6 + return np.asarray(trajectory) + + +def make_trials(seed=17): + """Create four training conditions and one unseen initial condition. + + Each training condition has four aligned noisy repetitions, three for + training and one for evaluation. The same observation map is used for all + conditions. No windows from the fifth condition enter training. + """ + rng = np.random.default_rng(seed) + mixing, _ = np.linalg.qr(rng.normal(size=(12, 3))) + trials, states, groups, training, testing = [], [], [], [], [] + initials = ([1., 1., 1.], [-2., 3., 5.], [5., -3., + 12.], [-7., -4., + 20.], [2., -1., 8.]) + for group, initial in enumerate(initials): + trajectory = simulate(initial) + scaled = (trajectory - [0., 0., 25.]) / 20 + for repetition in range(4 if group < 4 else 1): + index = len(trials) + trials.append((scaled @ mixing.T + rng.normal( + scale=0.02, size=(len(scaled), 12))).astype("float32")) + states.append(trajectory) + groups.append(group) + (training + if group < 4 and repetition < 3 else testing).append(index) + return trials, states, groups, training, testing + + +def r2(prediction, target): + """Compute variance-weighted R-squared over all coordinates.""" + return float(1 - np.square(prediction - target).sum() / + np.square(target - target.mean(axis=0)).sum()) + + +def diagnose(model, trials, states, training, testing): + """Fit a training-only affine map, then score held-out states and fields.""" + encoded = [model.transform(trial) for trial in trials] + train_embedding = np.concatenate([encoded[i] for i in training]) + train_state = np.concatenate([states[i] for i in training]) + affine = np.linalg.lstsq(np.c_[train_embedding, + np.ones(len(train_embedding))], + train_state, + rcond=None)[0] + metrics = {} + for name, indices in (("held_out_repetitions", testing[:-1]), + ("unseen_initial_condition", testing[-1:])): + embedding = np.concatenate([encoded[i] for i in indices]) + target = np.concatenate([states[i] for i in indices]) + predicted = np.c_[embedding, np.ones(len(embedding))] @ affine + field = model.vector_field(embedding) @ affine[:-1] + horizons = {} + for horizon in (1, 5, 10, 20): + initial, future = [], [] + for i in indices: + starts = np.arange(0, len(encoded[i]) - horizon, 20) + initial.append(encoded[i][starts]) + future.append(states[i][starts + horizon]) + initial, future = np.concatenate(initial), np.concatenate(future) + flow = model.rollout(initial, horizon)[:, -1] + forecast = np.c_[flow, np.ones(len(flow))] @ affine + persistence = np.c_[initial, np.ones(len(initial))] @ affine + error = float(np.square(forecast - future).mean()) + baseline = float(np.square(persistence - future).mean()) + horizons[str(horizon)] = dict(mse=error, + persistence_mse=baseline, + relative_mse=error / baseline) + metrics[name] = dict( + embedding_r2=r2(predicted, target), + transported_field_r2=r2(field, lorenz(target)), + latent_standard_deviation=embedding.std(0).tolist(), + forecasts=horizons) + return metrics, encoded, affine + + +def plot_example(model, states, encoded, affine, output): + """Plot unseen trajectory geometry and a short autonomous forecast.""" + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + target = states[-1] + embedding = encoded[-1] + aligned = np.c_[embedding, np.ones(len(embedding))] @ affine + figure = plt.figure(figsize=(12, 3.8), constrained_layout=True) + for position, values, title in ((1, target, "Held-out Lorenz trajectory"), + (2, aligned, "Affine-aligned embedding")): + axis = figure.add_subplot(1, 3, position, projection="3d") + axis.plot(*values.T, linewidth=0.6, color="tab:blue") + axis.set(xlabel="x", ylabel="y", zlabel="z", title=title) + axis = figure.add_subplot(1, 3, 3) + start, horizon = 200, 50 + forecast = model.rollout(embedding[start], horizon) + forecast = np.c_[forecast, np.ones(len(forecast))] @ affine + times = np.arange(horizon + 1) * model.sample_interval + for dimension, color in enumerate(("tab:blue", "tab:orange", "tab:green")): + axis.plot(times, + target[start:start + horizon + 1, dimension], + color=color, + label="True state" if dimension == 0 else None) + axis.plot(times, + forecast[:, dimension], + "--", + color=color, + label="DYSCO rollout" if dimension == 0 else None) + axis.set(xlabel="Time from initial state", + ylabel="State", + title="Autonomous forecast") + axis.legend(frameon=False) + figure.savefig(output / "lorenz.png", dpi=180) + plt.close(figure) + + +def run(output, seed=42, iterations=3000): + """Train, inspect equations, save and evaluate one reproducible fit.""" + output = Path(output) + output.mkdir(parents=True, exist_ok=True) + trials, states, groups, training, testing = make_trials() + model = cebra.DYSCO(model_architecture="offset1-model-mse", + output_dimension=3, + num_hidden_units=32, + polynomial_degree=2, + sample_interval=0.01, + rollout_steps=8, + num_views=2, + batch_size=32, + batch_size_negatives=128, + temperature=0.1, + potential=None, + learning_rate=3e-3, + dynamics_learning_rate=0.05, + max_iterations=iterations, + random_state=seed, + device="cpu") + start = time.perf_counter() + + def report_progress(step, solver): + print(f"Update {step + 1}: loss={solver.history[-1]:.4f}", flush=True) + + model.fit([trials[i] for i in training], + alignment_ids=[groups[i] for i in training], + callback=report_progress, + callback_frequency=500) + elapsed = time.perf_counter() - start + equations = model.equations(precision=6) + print(*equations, sep="\n", flush=True) + model.save(output / "dysco.pt") + (output / "equations.txt").write_text("\n".join(equations) + "\n") + metrics, encoded, affine = diagnose(model, trials, states, training, + testing) + metrics.update(seed=seed, + iterations=iterations, + training_seconds=elapsed, + last_loss=model.solver_.history[-1], + affine_map_condition=float(np.linalg.cond(affine[:-1]))) + (output / "metrics.json").write_text(json.dumps(metrics, indent=2) + "\n") + np.savez(output / "diagnostics.npz", + true_state=states[-1], + embedding=encoded[-1], + affine=affine, + history=np.asarray(model.solver_.history)) + plot_example(model, states, encoded, affine, output) + print(json.dumps(metrics, indent=2), flush=True) + return metrics + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, default=Path("lorenz-example")) + parser.add_argument("--iterations", type=int, default=3000) + parser.add_argument("--seed", type=int, default=42) + args = parser.parse_args() + run(args.output, args.seed, args.iterations) diff --git a/tests/examples/dysco_sklearn_example.py b/tests/examples/dysco_sklearn_example.py new file mode 100644 index 00000000..62c2d7db --- /dev/null +++ b/tests/examples/dysco_sklearn_example.py @@ -0,0 +1,149 @@ +# +# 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. +# +"""Offline aligned-trial example and bounded DYSCO diagnostics. + +Run from the CEBRA checkout with ``python tests/examples/dysco_sklearn_example.py``. +The example generates its own observations and optional controls. +""" + +import argparse +import json +import time + +import numpy as np + +import cebra + + +def make_trials(controlled=False, seed=17): + """Generate repeated noisy observations of two linear oscillator trials.""" + rng = np.random.default_rng(seed) + dt = 0.05 + times = np.arange(100) * dt + mixing, _ = np.linalg.qr(rng.normal(size=(5, 2))) + trials, states, controls, groups, derivatives = [], [], [], [], [] + for group, initial in enumerate(([1., 0.], [0.2, 0.8])): + u = (0.3 * + np.sin(0.7 * times + group))[:, None] if controlled else np.zeros( + (len(times), 1)) + + def field(z, value): + return np.array([-z[1] + value, z[0]]) + + z = np.asarray(initial, dtype=float) + trajectory = [z.copy()] + for k in range(len(times) - 1): + start, end = u[k, 0], u[k + 1, 0] + middle = (start + end) / 2 + k1 = field(z, start) + k2 = field(z + dt * k1 / 2, middle) + k3 = field(z + dt * k2 / 2, middle) + k4 = field(z + dt * k3, end) + z = z + dt * (k1 + 2 * k2 + 2 * k3 + k4) / 6 + trajectory.append(z.copy()) + trajectory = np.asarray(trajectory) + derivative = np.stack( + [field(z, value) for z, value in zip(trajectory, u[:, 0])]) + for repetition in range(6): + trials.append( + (trajectory @ mixing.T + + rng.normal(scale=0.02, size=(100, 5))).astype("float32")) + states.append(trajectory) + controls.append(u.astype("float32")) + groups.append(group) + derivatives.append(derivative) + return trials, states, controls if controlled else None, groups, derivatives, dt + + +def run(seed=42, iterations=500, controlled=False): + """Fit one seed and report held-out observation and dynamics diagnostics.""" + trials, states, controls, groups, derivatives, dt = make_trials(controlled) + training = [i for i in range(len(trials)) if i % 6 < 4] + testing = [i for i in range(len(trials)) if i % 6 >= 4] + model = cebra.DYSCO(model_architecture="offset1-model-mse", + output_dimension=2, + num_hidden_units=16, + sample_interval=dt, + polynomial_degree=1, + rollout_steps=8, + integration_substeps=1, + num_views=2, + batch_size=16, + batch_size_negatives=32, + max_iterations=iterations, + learning_rate=1e-3, + temperature=0.1, + potential="kde", + random_state=seed, + device="cpu") + start = time.perf_counter() + model.fit( + [trials[i] for i in training], + alignment_ids=[groups[i] for i in training], + controls=None if controls is None else [controls[i] for i in training]) + elapsed = time.perf_counter() - start + encoded_train = np.concatenate( + [model.transform(trials[i]) for i in training]) + target_train = np.concatenate([states[i] for i in training]) + mapping = np.linalg.lstsq(np.c_[encoded_train, + np.ones(len(encoded_train))], + target_train, + rcond=None)[0] + predictions, targets, field_predictions, field_targets = [], [], [], [] + errors, persistence = [], [] + for i in testing: + encoded = model.transform(trials[i]) + predictions.append(np.c_[encoded, np.ones(len(encoded))] @ mapping) + targets.append(states[i]) + u = None if controls is None else controls[i] + field_predictions.append(model.vector_field(encoded, u) @ mapping[:-1]) + field_targets.append(derivatives[i]) + for k in range(0, len(encoded) - 4, 4): + segment = None if u is None else u[k:k + 5] + trajectory = model.rollout(encoded[k], 4, segment) + errors.append(np.square(trajectory[-1] - encoded[k + 4]).mean()) + persistence.append(np.square(encoded[k] - encoded[k + 4]).mean()) + + def score(predicted, actual): + predicted, actual = np.concatenate(predicted), np.concatenate(actual) + return float(1 - np.square(predicted - actual).sum() / + np.square(actual - actual.mean(0)).sum()) + + return dict(seed=seed, + controlled=controlled, + iterations=iterations, + seconds=elapsed, + last_loss=model.solver_.history[-1], + embedding_r2=score(predictions, targets), + transported_field_r2=score(field_predictions, field_targets), + rollout_mse=float(np.mean(errors)), + persistence_mse=float(np.mean(persistence))) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--iterations", type=int, default=500) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--controlled", action="store_true") + args = parser.parse_args() + print(json.dumps(run(args.seed, args.iterations, args.controlled), + indent=2)) diff --git a/tests/fixtures/dysco_submission.json b/tests/fixtures/dysco_submission.json new file mode 100644 index 00000000..c294bea2 --- /dev/null +++ b/tests/fixtures/dysco_submission.json @@ -0,0 +1,1387 @@ +{ + "reference": "submission_2026", + "torch": "2.12.1+cu126", + "seed": 17, + "sample_interval": 0.2, + "temperature": 0.7, + "negative_temperature": 1.1, + "num_positive": 2, + "num_negatives": 6, + "source_sha256": { + "src/model/losses.py": "9e74a8620971675915fe773cc2f24fded3950678f3ddc50df5447a06208060e6", + "src/utils/data.py": "30aeb81da65ede0bbeae053f1cf55c35127c69ef3ba4196fe464393b361c19d8", + "src/model/potential.py": "5e16b7fffc1f07a025ed4b0c222898f88493661468e77d539235ce5eb946a140", + "src/model/similarities.py": "979a5b0e6ce94b0e7ccc05bf45560aafb33c4abc7e20ebdfd65b2978eb2f7f79" + }, + "cases": [ + { + "potential": "none", + "loss": 3.699708685834235, + "encoded": [ + [ + [ + [ + 0.08351395377884983, + -0.5620843550689381 + ], + [ + 0.4382085845412596, + -0.15943439856485978 + ], + [ + -0.0840727022884253, + -0.1660477208228944 + ] + ], + [ + [ + 0.15236537554478377, + 0.16159134894374141 + ], + [ + 0.25504876557929634, + 0.6932768747420965 + ], + [ + -0.08852720366168103, + 0.04412776560341874 + ] + ] + ], + [ + [ + [ + -0.015978436948814984, + -0.21314595558577354 + ], + [ + -0.035583305475957935, + 0.35630670609861753 + ], + [ + 0.3758820409043065, + 0.1195805831732917 + ] + ], + [ + [ + 0.4333494157900676, + -0.5986052856244651 + ], + [ + -0.057658455945868936, + 0.3619935901318078 + ], + [ + 0.42353113938835396, + 0.2603054412428696 + ] + ] + ] + ], + "forward": [ + [ + [ + [ + 0.05806113841032596, + -0.6906479930994972 + ], + [ + 0.35772714729250366, + -0.1746956323605974 + ], + [ + -0.08832607495202631, + -0.26379998162465307 + ] + ], + [ + [ + 0.1764092698106727, + 0.18269403739719933 + ], + [ + 0.2445311746841635, + 0.7194201935724372 + ], + [ + -0.18001159565135347, + 0.1987632829203433 + ] + ] + ], + [ + [ + [ + -0.00851197395532762, + -0.36651529391796633 + ], + [ + -0.16495971687537697, + 0.3744013454043833 + ], + [ + 0.5699710889797233, + -0.028631342945420274 + ] + ], + [ + [ + 0.344897754272574, + -0.722482621765616 + ], + [ + 0.018888678532494818, + 0.24443629890919527 + ], + [ + 0.3091700194577017, + 0.022816984692184628 + ] + ] + ] + ], + "backward": [ + [ + [ + [ + 0.027481907210910532, + -0.7160772081001073 + ], + [ + 0.4679704837233648, + -0.3108264127272118 + ], + [ + -0.1816009415433082, + -0.09556785137989687 + ] + ], + [ + [ + 0.23966887060506142, + 0.21096607348749064 + ], + [ + 0.0883306144323033, + 0.79075894899048 + ], + [ + 0.0398083312991067, + 0.20724503420909135 + ] + ] + ], + [ + [ + [ + 0.3251271959569969, + 0.0015322039198867599 + ], + [ + 0.18251425491000062, + 0.4267685728919609 + ], + [ + 0.3400886762273796, + 0.08072670482430161 + ] + ], + [ + [ + 0.5165329472324938, + -0.6682624116161651 + ], + [ + -0.04635980498205813, + 0.33098067842383105 + ], + [ + 0.35495653698089724, + 0.10930000011753788 + ] + ] + ] + ], + "indices": { + "reference": [ + [ + 0, + 0, + 1, + 1 + ], + [ + 0, + 1, + 0, + 0 + ], + [ + 0, + 1, + 2, + 0 + ] + ], + "positive": [ + [ + 0, + 0, + 1, + 1 + ], + [ + 0, + 0, + 0, + 1 + ], + [ + 0, + 1, + 2, + 0 + ] + ], + "negative": [ + [ + 1, + 1, + 1, + 0, + 0, + 0 + ], + [ + 1, + 1, + 0, + 1, + 1, + 0 + ], + [ + 2, + 0, + 1, + 0, + 1, + 0 + ] + ], + "support": [ + 10, + 1, + 10, + 5, + 1, + 9, + 8, + 1 + ] + }, + "gradients": [ + [ + [ + [ + [ + 0.06617488715942715, + 0.23546026032838663 + ], + [ + 0.4616677294242823, + -1.553259176752286 + ], + [ + 0.0, + 0.0 + ] + ], + [ + [ + 0.010030188228607196, + -0.018424647585391002 + ], + [ + -0.004573947499226516, + -0.03109702946659039 + ], + [ + 0.0, + 0.0 + ] + ] + ], + [ + [ + [ + 0.0, + 0.0 + ], + [ + 0.03708041208561063, + -0.01872030509463385 + ], + [ + -0.0627848502516123, + 0.07413529269890752 + ] + ], + [ + [ + 0.4065240565828329, + -0.6629858181733607 + ], + [ + 0.0, + 0.0 + ], + [ + -0.028564384089892973, + -0.015534937794020195 + ] + ] + ] + ], + [ + [ + [ + [ + 0.07239149164923728, + 0.0846829446202815 + ], + [ + 0.0, + 0.0 + ], + [ + 0.0, + 0.0 + ] + ], + [ + [ + 0.0065112457215820915, + -0.01811070821158693 + ], + [ + -0.292914683980959, + 0.9754680549688114 + ], + [ + 0.0, + 0.0 + ] + ] + ], + [ + [ + [ + -0.47350902806605266, + 0.403764903568811 + ], + [ + 0.04881704476329671, + -0.017797293768173357 + ], + [ + 0.05858862063059581, + -0.08548142906470008 + ] + ], + [ + [ + -0.03697600922059125, + 0.04243957631271085 + ], + [ + 0.0, + 0.0 + ], + [ + -0.01759951757714802, + -0.013918462060746479 + ] + ] + ] + ], + [ + [ + [ + [ + 0.013956586933487183, + -0.012145697080974911 + ], + [ + 0.094472613593998, + -0.4355996711679701 + ], + [ + 0.0, + 0.0 + ] + ], + [ + [ + -0.003071160626895768, + -0.01736112363902079 + ], + [ + -0.25347226985602767, + 0.6526894773517499 + ], + [ + 0.0, + 0.0 + ] + ] + ], + [ + [ + [ + -0.12541298884333424, + 0.5271016960725807 + ], + [ + 0.00695974745867857, + -0.020074510913110674 + ], + [ + -0.12591724434700008, + 0.0280962374010293 + ] + ], + [ + [ + 0.16376606355921489, + -0.08900511910584656 + ], + [ + 0.0, + 0.0 + ], + [ + -0.022144603432110235, + -0.01432251344485663 + ] + ] + ] + ] + ] + }, + { + "potential": "quadratic", + "loss": 3.6980412388452715, + "encoded": [ + [ + [ + [ + 0.08351395377884983, + -0.5620843550689381 + ], + [ + 0.4382085845412596, + -0.15943439856485978 + ], + [ + -0.0840727022884253, + -0.1660477208228944 + ] + ], + [ + [ + 0.15236537554478377, + 0.16159134894374141 + ], + [ + 0.25504876557929634, + 0.6932768747420965 + ], + [ + -0.08852720366168103, + 0.04412776560341874 + ] + ] + ], + [ + [ + [ + -0.015978436948814984, + -0.21314595558577354 + ], + [ + -0.035583305475957935, + 0.35630670609861753 + ], + [ + 0.3758820409043065, + 0.1195805831732917 + ] + ], + [ + [ + 0.4333494157900676, + -0.5986052856244651 + ], + [ + -0.057658455945868936, + 0.3619935901318078 + ], + [ + 0.42353113938835396, + 0.2603054412428696 + ] + ] + ] + ], + "forward": [ + [ + [ + [ + 0.05806113841032596, + -0.6906479930994972 + ], + [ + 0.35772714729250366, + -0.1746956323605974 + ], + [ + -0.08832607495202631, + -0.26379998162465307 + ] + ], + [ + [ + 0.1764092698106727, + 0.18269403739719933 + ], + [ + 0.2445311746841635, + 0.7194201935724372 + ], + [ + -0.18001159565135347, + 0.1987632829203433 + ] + ] + ], + [ + [ + [ + -0.00851197395532762, + -0.36651529391796633 + ], + [ + -0.16495971687537697, + 0.3744013454043833 + ], + [ + 0.5699710889797233, + -0.028631342945420274 + ] + ], + [ + [ + 0.344897754272574, + -0.722482621765616 + ], + [ + 0.018888678532494818, + 0.24443629890919527 + ], + [ + 0.3091700194577017, + 0.022816984692184628 + ] + ] + ] + ], + "backward": [ + [ + [ + [ + 0.027481907210910532, + -0.7160772081001073 + ], + [ + 0.4679704837233648, + -0.3108264127272118 + ], + [ + -0.1816009415433082, + -0.09556785137989687 + ] + ], + [ + [ + 0.23966887060506142, + 0.21096607348749064 + ], + [ + 0.0883306144323033, + 0.79075894899048 + ], + [ + 0.0398083312991067, + 0.20724503420909135 + ] + ] + ], + [ + [ + [ + 0.3251271959569969, + 0.0015322039198867599 + ], + [ + 0.18251425491000062, + 0.4267685728919609 + ], + [ + 0.3400886762273796, + 0.08072670482430161 + ] + ], + [ + [ + 0.5165329472324938, + -0.6682624116161651 + ], + [ + -0.04635980498205813, + 0.33098067842383105 + ], + [ + 0.35495653698089724, + 0.10930000011753788 + ] + ] + ] + ], + "indices": { + "reference": [ + [ + 0, + 0, + 1, + 1 + ], + [ + 0, + 1, + 0, + 0 + ], + [ + 0, + 1, + 2, + 0 + ] + ], + "positive": [ + [ + 0, + 0, + 1, + 1 + ], + [ + 0, + 0, + 0, + 1 + ], + [ + 0, + 1, + 2, + 0 + ] + ], + "negative": [ + [ + 1, + 1, + 1, + 0, + 0, + 0 + ], + [ + 1, + 1, + 0, + 1, + 1, + 0 + ], + [ + 2, + 0, + 1, + 0, + 1, + 0 + ] + ], + "support": [ + 10, + 1, + 10, + 5, + 1, + 9, + 8, + 1 + ] + }, + "gradients": [ + [ + [ + [ + [ + 0.06854244667831931, + 0.2171568175441901 + ], + [ + 0.4835409894941878, + -1.56119259975083 + ], + [ + 0.0, + 0.0 + ] + ], + [ + [ + 0.008377461584857455, + -0.021054881526563023 + ], + [ + -0.006793844337209649, + -0.03682793458139868 + ], + [ + 0.0, + 0.0 + ] + ] + ], + [ + [ + [ + 0.0, + 0.0 + ], + [ + 0.03812971034401758, + -0.022678817880755736 + ], + [ + -0.04520657947100877, + 0.07958789758676792 + ] + ], + [ + [ + 0.42472019290464513, + -0.6877056663937268 + ], + [ + 0.0, + 0.0 + ], + [ + -0.033299464321735105, + -0.018465374779613235 + ] + ] + ] + ], + [ + [ + [ + [ + 0.07090909803532976, + 0.09473455514068876 + ], + [ + 0.0, + 0.0 + ], + [ + 0.0, + 0.0 + ] + ], + [ + [ + 0.0044684566527369435, + -0.02090814653387963 + ], + [ + -0.2951793281392195, + 0.9672573685172478 + ], + [ + 0.0, + 0.0 + ] + ] + ], + [ + [ + [ + -0.47429729600680004, + 0.40778515331379495 + ], + [ + 0.05097750861300404, + -0.021334283237278557 + ], + [ + 0.058313632898003884, + -0.08441801911641009 + ] + ], + [ + [ + -0.039277802498527165, + 0.048023860109193 + ], + [ + 0.0, + 0.0 + ], + [ + -0.021961619277081026, + -0.014863295590064754 + ] + ] + ] + ], + [ + [ + [ + [ + 0.012780309558780283, + -0.002262410800759916 + ], + [ + 0.094472613593998, + -0.4355996711679701 + ], + [ + 0.0, + 0.0 + ] + ], + [ + [ + -0.006075648535689072, + -0.02032836449576447 + ], + [ + -0.25506407832835654, + 0.6445551309165931 + ], + [ + 0.0, + 0.0 + ] + ] + ], + [ + [ + [ + -0.12587556926741703, + 0.5290751522201068 + ], + [ + 0.004972380020264842, + -0.02489127863682264 + ], + [ + -0.12607297277962232, + 0.028796999908662975 + ] + ], + [ + [ + 0.16143189265347369, + -0.0849583458313814 + ], + [ + 0.0, + 0.0 + ], + [ + -0.026818600741619583, + -0.016067659663592755 + ] + ] + ] + ], + -0.00889609644035369 + ] + }, + { + "potential": "kde", + "loss": 3.8767739332666418, + "encoded": [ + [ + [ + [ + 0.08351395377884983, + -0.5620843550689381 + ], + [ + 0.4382085845412596, + -0.15943439856485978 + ], + [ + -0.0840727022884253, + -0.1660477208228944 + ] + ], + [ + [ + 0.15236537554478377, + 0.16159134894374141 + ], + [ + 0.25504876557929634, + 0.6932768747420965 + ], + [ + -0.08852720366168103, + 0.04412776560341874 + ] + ] + ], + [ + [ + [ + -0.015978436948814984, + -0.21314595558577354 + ], + [ + -0.035583305475957935, + 0.35630670609861753 + ], + [ + 0.3758820409043065, + 0.1195805831732917 + ] + ], + [ + [ + 0.4333494157900676, + -0.5986052856244651 + ], + [ + -0.057658455945868936, + 0.3619935901318078 + ], + [ + 0.42353113938835396, + 0.2603054412428696 + ] + ] + ] + ], + "forward": [ + [ + [ + [ + 0.05806113841032596, + -0.6906479930994972 + ], + [ + 0.35772714729250366, + -0.1746956323605974 + ], + [ + -0.08832607495202631, + -0.26379998162465307 + ] + ], + [ + [ + 0.1764092698106727, + 0.18269403739719933 + ], + [ + 0.2445311746841635, + 0.7194201935724372 + ], + [ + -0.18001159565135347, + 0.1987632829203433 + ] + ] + ], + [ + [ + [ + -0.00851197395532762, + -0.36651529391796633 + ], + [ + -0.16495971687537697, + 0.3744013454043833 + ], + [ + 0.5699710889797233, + -0.028631342945420274 + ] + ], + [ + [ + 0.344897754272574, + -0.722482621765616 + ], + [ + 0.018888678532494818, + 0.24443629890919527 + ], + [ + 0.3091700194577017, + 0.022816984692184628 + ] + ] + ] + ], + "backward": [ + [ + [ + [ + 0.027481907210910532, + -0.7160772081001073 + ], + [ + 0.4679704837233648, + -0.3108264127272118 + ], + [ + -0.1816009415433082, + -0.09556785137989687 + ] + ], + [ + [ + 0.23966887060506142, + 0.21096607348749064 + ], + [ + 0.0883306144323033, + 0.79075894899048 + ], + [ + 0.0398083312991067, + 0.20724503420909135 + ] + ] + ], + [ + [ + [ + 0.3251271959569969, + 0.0015322039198867599 + ], + [ + 0.18251425491000062, + 0.4267685728919609 + ], + [ + 0.3400886762273796, + 0.08072670482430161 + ] + ], + [ + [ + 0.5165329472324938, + -0.6682624116161651 + ], + [ + -0.04635980498205813, + 0.33098067842383105 + ], + [ + 0.35495653698089724, + 0.10930000011753788 + ] + ] + ] + ], + "indices": { + "reference": [ + [ + 0, + 0, + 1, + 1 + ], + [ + 0, + 1, + 0, + 0 + ], + [ + 0, + 1, + 2, + 0 + ] + ], + "positive": [ + [ + 0, + 0, + 1, + 1 + ], + [ + 0, + 0, + 0, + 1 + ], + [ + 0, + 1, + 2, + 0 + ] + ], + "negative": [ + [ + 1, + 1, + 1, + 0, + 0, + 0 + ], + [ + 1, + 1, + 0, + 1, + 1, + 0 + ], + [ + 2, + 0, + 1, + 0, + 1, + 0 + ] + ], + "support": [ + 10, + 1, + 10, + 5, + 1, + 9, + 8, + 1 + ] + }, + "gradients": [ + [ + [ + [ + [ + 0.21999686719712352, + 0.45902695719576453 + ], + [ + 0.3727007009319854, + -1.501860484999158 + ], + [ + 0.0, + 0.0 + ] + ], + [ + [ + 0.002817745427486404, + -0.0010149755061249488 + ], + [ + 0.035758156972180544, + 0.09335277491001465 + ], + [ + 0.0, + 0.0 + ] + ] + ], + [ + [ + [ + 0.0, + 0.0 + ], + [ + 0.013477149001106713, + 0.009541721751385217 + ], + [ + -0.15578917960965405, + -0.03525609465112151 + ] + ], + [ + [ + 0.3855509365376392, + -0.40433915354228195 + ], + [ + 0.0, + 0.0 + ], + [ + 0.0027393537584265437, + 0.019326590675157483 + ] + ] + ] + ], + [ + [ + [ + [ + -0.029193152252267547, + -0.0694824742122904 + ], + [ + 0.0, + 0.0 + ], + [ + 0.0, + 0.0 + ] + ], + [ + [ + 0.003143258403699372, + 0.0015718049481822788 + ], + [ + -0.2528052826631404, + 1.1460372881452898 + ], + [ + 0.0, + 0.0 + ] + ] + ], + [ + [ + [ + -0.48128754469709223, + 0.36244264260198 + ], + [ + 0.014247444572546876, + 0.007870683044235098 + ], + [ + 0.057035918233474446, + -0.09298416520712481 + ] + ], + [ + [ + -0.05297355147915945, + -0.04628255227287126 + ], + [ + 0.0, + 0.0 + ], + [ + -0.006200515269774234, + -0.003295248730500798 + ] + ] + ] + ], + [ + [ + [ + [ + -0.10450851215085374, + -0.17996950564557918 + ], + [ + 0.094472613593998, + -0.4355996711679701 + ], + [ + 0.0, + 0.0 + ] + ], + [ + [ + 0.002961978244079939, + 0.0064666965900112075 + ], + [ + -0.22992991681759517, + 0.8330301501877684 + ], + [ + 0.0, + 0.0 + ] + ] + ], + [ + [ + [ + -0.12945925106894549, + 0.513764114592626 + ], + [ + 0.013938657699007843, + 0.027223535965303473 + ], + [ + -0.12888545047889094, + 0.024517416513529035 + ] + ], + [ + [ + 0.1820789095678444, + -0.1526713177103835 + ], + [ + 0.0, + 0.0 + ], + [ + -0.003273490567963458, + 0.0037840268999931904 + ] + ] + ] + ] + ] + } + ] +} diff --git a/tests/test_aligned_trials.py b/tests/test_aligned_trials.py new file mode 100644 index 00000000..968e60b4 --- /dev/null +++ b/tests/test_aligned_trials.py @@ -0,0 +1,189 @@ +# +# 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. +# +"""Aligned-trial sampling preserves group, trial and encoder boundaries.""" + +import numpy as np +import pytest +import torch + +from cebra.data import Offset +from cebra.data.aligned_trials import AlignedTrialDataset +from cebra.data.aligned_trials import AlignedTrialLoader +from cebra.data.aligned_trials import AlignedWindowIndex + + +def dataset(controls=True, device='cpu'): + trials = [ + torch.stack((torch.full((n,), i), torch.arange(n)), -1).float() + for i, n in enumerate((12, 12, 18, 18, 18)) + ] + control = [x[:, 1:] * 3 for x in trials] if controls else None + result = AlignedTrialDataset(trials, ['a', 'a', 'b', 'b', 'b'], + .02, + controls=control, + time_origin=-.25, + device=device) + result.offset = Offset(2, 3) + return result + + +def test_windows_align_views_and_controls_without_crossing_boundaries(): + data = dataset() + loader = AlignedTrialLoader(data, + num_steps=2, + batch_size=17, + batch_size_negatives=5, + rollout_steps=3) + batch = next(iter(loader)) + assert batch.observations.shape == (17, 2, 8, 2) + assert batch.negative.shape == (5, 8, 2) + assert batch.controls.shape == (17, 2, 4, 1) + assert batch.time.shape == (17, 2, 4) + assert batch.negative_controls.shape == (5, 4, 1) + # Feature 0 encodes trial ID; feature 1 encodes that trial's time index. + torch.testing.assert_close( + batch.observations[..., 0], + batch.index.trials[..., None].expand(-1, -1, 8).float()) + assert torch.all(batch.index.trials[:, 0] != batch.index.trials[:, 1]) + group = data.group_index[batch.index.trials] + assert torch.equal(group[:, 0], group[:, 1]) + times = batch.observations[..., 2:6, 1] + torch.testing.assert_close(batch.controls[..., 0], times * 3) + torch.testing.assert_close(batch.time, times * .02 - .25) + torch.testing.assert_close(batch.observations[:, 0, :, 1], + batch.observations[:, 1, :, 1]) + assert batch.to('cpu') is batch + assert batch.index.trials.device.type == 'cpu' + assert len(list(loader)) == 2 + + +def test_seed_is_private_reproducible_and_does_not_reset_each_iteration(): + kwargs = dict(num_steps=2, batch_size=16, rollout_steps=2, seed=7) + a = AlignedTrialLoader(dataset(), **kwargs) + b = AlignedTrialLoader(dataset(), **kwargs) + first = a.get_indices(16) + torch.manual_seed(891) + same = b.get_indices(16) + torch.testing.assert_close(first.trials, same.trials) + torch.testing.assert_close(first.starts, same.starts) + second = a.get_indices(16) + assert not (torch.equal(first.trials, second.trials) and + torch.equal(first.starts, second.starts)) + + +def test_singleton_groups_are_explicit_single_view(): + data = AlignedTrialDataset([np.zeros((8, 2)), np.ones((12, 2))], [0, 1], .1) + loader = AlignedTrialLoader(data, + num_steps=1, + batch_size=5, + num_views=1, + rollout_steps=3) + batch = next(iter(loader)) + assert batch.observations.shape == (5, 1, 4, 2) + assert batch.controls is None + with pytest.raises(ValueError, match='distinct trials'): + AlignedTrialLoader(data, + num_steps=1, + batch_size=5, + num_views=2, + rollout_steps=3) + + +def test_tensor_alignment_labels_have_value_semantics(): + trials = [np.zeros((12, 2))] * 4 + data = AlignedTrialDataset(trials, torch.tensor([0, 0, 1, 1]), .1) + assert data.groups == ((0, 1), (2, 3)) + for labels in (torch.zeros(4, 1), [0, 0, float("nan"), + float("nan")], + np.array([0, 0, np.nan, np.nan], dtype="float32")): + with pytest.raises(ValueError, match="alignment IDs"): + AlignedTrialDataset(trials, labels, .1) + + +def test_shortest_legal_window_and_invalid_context(): + data = AlignedTrialDataset([np.zeros((7, 2))] * 2, [0, 0], .1) + data.offset = Offset(2, 2) + loader = AlignedTrialLoader(data, + num_steps=1, + batch_size=9, + rollout_steps=3) + batch = next(iter(loader)) + assert torch.all(batch.index.starts == 2) + assert batch.observations.shape[-2] == 7 + with pytest.raises(ValueError, match='too short'): + AlignedTrialLoader(data, num_steps=1, batch_size=9, rollout_steps=4) + with pytest.raises(ValueError, match='boundary'): + data[torch.tensor([[0, 0]])] + with pytest.raises(ValueError, match='boundary'): + data[torch.tensor([[0, 6]])] + assert data[torch.tensor([[1, 2]])].shape == (1, 2, 4) + + +def test_manual_index_cannot_pair_groups_or_duplicate_trials(): + data = dataset() + index = AlignedWindowIndex(torch.tensor([[0, 2]]), torch.tensor([3]), + torch.tensor([1]), torch.tensor([3]), 4) + with pytest.raises(ValueError, match='same alignment group'): + data.load_batch(index) + index.trials = torch.tensor([[0, 0]]) + with pytest.raises(ValueError, match='independent views'): + data.load_batch(index) + index.trials = torch.tensor([[0, 1]]) + index.starts = torch.tensor([10]) + with pytest.raises(ValueError, match='boundary'): + data.load_batch(index) + + +@pytest.mark.parametrize('trials,labels,controls', [ + ([np.zeros((8, 2)), np.zeros((9, 2))], [0, 0], None), + ([np.zeros((8, 2))], [], None), + ([np.zeros((8, 2)), np.zeros((8, 3))], [0, 1], None), + ([np.full((8, 2), np.nan)], [0], None), + ([np.zeros((8, 2))], [0], [np.zeros((7, 1))]), + ([np.zeros((8, 2))], [[0]], None), +]) +def test_invalid_data_is_rejected(trials, labels, controls): + with pytest.raises(ValueError): + AlignedTrialDataset(trials, labels, .02, controls=controls) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason='CUDA unavailable') +def test_device_move_includes_controls_and_metadata(): + loader = AlignedTrialLoader(dataset(), + num_steps=1, + batch_size=3, + rollout_steps=2) + loader.to('cuda') + batch = next(iter(loader)) + for value in (batch.observations, batch.controls, batch.time, + batch.index.trials): + assert value.device.type == 'cuda' + loader.to('cpu') + assert next(iter(loader)).observations.device.type == 'cpu' + + +def test_readonly_input_is_copied_without_mutation(): + data = np.zeros((8, 2), dtype=np.float32) + data.setflags(write=False) + result = AlignedTrialDataset([data], [0], .02) + result.neural.fill_(3) + assert np.all(data == 0) diff --git a/tests/test_auxiliary_checkpoint.py b/tests/test_auxiliary_checkpoint.py new file mode 100644 index 00000000..836c39cc --- /dev/null +++ b/tests/test_auxiliary_checkpoint.py @@ -0,0 +1,161 @@ +# +# 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. +# +"""Auxiliary solver checkpoints preserve reference models and DCL dynamics.""" + +import copy +import itertools + +import numpy as np +import pytest +import torch + +import cebra +import cebra.models +import cebra.solver + + +def _make_auxiliary_solver(multisession): + + def make_encoder(): + return torch.nn.Sequential(torch.nn.Linear(5, 3), + torch.nn.BatchNorm1d(3)) + + if multisession: + model = torch.nn.ModuleList([make_encoder(), make_encoder()]) + reference_model = torch.nn.ModuleList([make_encoder(), make_encoder()]) + solver_class = cebra.solver.MultiSessionAuxVariableSolver + else: + model = make_encoder() + reference_model = make_encoder() + solver_class = cebra.solver.SingleSessionAuxVariableSolver + criterion = cebra.models.InfoNCE() + optimizer = torch.optim.Adam( + itertools.chain(model.parameters(), reference_model.parameters(), + criterion.parameters())) + kwargs = {} if multisession else {"reference_model": reference_model} + solver = solver_class(model=model, + criterion=criterion, + optimizer=optimizer, + tqdm_on=False, + **kwargs) + if multisession: + solver.reference_model = reference_model + return solver + + +@pytest.mark.parametrize("multisession", [False, True]) +def test_auxiliary_reference_round_trip(multisession): + torch.manual_seed(4) + solver = _make_auxiliary_solver(multisession) + restored = _make_auxiliary_solver(multisession) + inputs = torch.randn(8, 5) + models = list(solver.model) if multisession else [solver.model] + references = (list(solver.reference_model) + if multisession else [solver.reference_model]) + for reference in references: + reference(inputs) # Update the reference encoder's running statistics. + solver.model.eval() + solver.reference_model.eval() + restored.model.eval() + restored.reference_model.eval() + restored_references = (list(restored.reference_model) + if multisession else [restored.reference_model]) + for reference, other in zip(references, restored_references): + assert not torch.allclose(reference(inputs), other(inputs)) + + restored.load_state_dict(copy.deepcopy(solver.state_dict())) + restored_models = list(restored.model) if multisession else [restored.model] + for model, other in zip(models, restored_models): + torch.testing.assert_close(model(inputs), other(inputs)) + for reference, other in zip(references, restored_references): + torch.testing.assert_close(reference(inputs), other(inputs)) + for name, value in reference.named_buffers(): + torch.testing.assert_close(value, dict(other.named_buffers())[name]) + + +@pytest.mark.parametrize("multisession", [False, True]) +def test_auxiliary_legacy_checkpoint(multisession): + solver = _make_auxiliary_solver(multisession) + restored = _make_auxiliary_solver(multisession) + legacy = copy.deepcopy(solver.state_dict()) + del legacy["reference_model"] + before = copy.deepcopy(restored.reference_model.state_dict()) + with pytest.raises(KeyError, match="missing reference_model"): + restored.load_state_dict(legacy) + with pytest.warns(UserWarning, match="Legacy auxiliary"): + restored.load_state_dict(legacy, strict=False) + for name, value in before.items(): + torch.testing.assert_close(value, + restored.reference_model.state_dict()[name]) + for name, value in solver.model.state_dict().items(): + torch.testing.assert_close(value, restored.model.state_dict()[name]) + + +@pytest.mark.parametrize("strict", [False, True]) +def test_auxiliary_reference_parameter_strictness(strict): + solver = _make_auxiliary_solver(multisession=False) + checkpoint = copy.deepcopy(solver.state_dict()) + del checkpoint["reference_model"]["0.weight"] + if strict: + with pytest.raises(RuntimeError, match="Missing key.*0.weight"): + solver.load_state_dict(checkpoint) + else: + solver.load_state_dict(checkpoint, strict=False) + + +@pytest.mark.parametrize("architecture", ["linear", "orthogonal-linear"]) +@pytest.mark.parametrize("batch_size", [8, None]) +def test_existing_dcl_fit_save_load_and_resume(tmp_path, architecture, + batch_size): + from cebra.integrations.sklearn.cebra import DCL + torch.manual_seed(4) + data = np.random.default_rng(4).normal(size=(100, 5)).astype("float32") + model = DCL(device="cpu", + dynamics_model_architecture=architecture, + output_dimension=3, + batch_size=batch_size, + batch_size_negatives=11, + max_iterations=2, + distance="euclidean") + model.fit(data) + path = tmp_path / "flow.pt" + model.save(path, backend="sklearn") + loaded = cebra.CEBRA.load(path, backend="sklearn") + assert loaded.solver_.reference_model[0] is loaded.solver_.model + assert loaded.solver_.reference_model[1] is loaded.dynamics_model_ + np.testing.assert_allclose(model.transform(data), loaded.transform(data)) + state = torch.randn(7, 3) + torch.testing.assert_close(model.dynamics_model_(state), + loaded.dynamics_model_(state)) + before = loaded.dynamics_model_(state).detach().clone() + loaded.partial_fit(data) + assert torch.isfinite(loaded.dynamics_model_(state)).all() + assert not torch.equal(before, loaded.dynamics_model_(state)) + legacy = model.solver_.state_dict() + del legacy["reference_model"] + before = loaded.dynamics_model_(state).detach().clone() + with pytest.raises(KeyError, match="missing reference_model"): + loaded.solver_.load_state_dict(legacy) + with pytest.warns(UserWarning, match="Legacy auxiliary"): + loaded.solver_.load_state_dict(legacy, strict=False) + torch.testing.assert_close(loaded.dynamics_model_(state), before) + np.testing.assert_allclose(model.transform(data), loaded.transform(data)) diff --git a/tests/test_dysco.py b/tests/test_dysco.py new file mode 100644 index 00000000..9755f787 --- /dev/null +++ b/tests/test_dysco.py @@ -0,0 +1,279 @@ +# +# 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. +# +"""Numerical parity and inherited lifecycle for trajectory contrastive learning.""" + +import copy +import json +from pathlib import Path + +import pytest +import torch +from torch import nn + +import cebra.data +import cebra.models +import cebra.solver +from cebra.dynamics.polynomial import PolynomialFlow +from cebra.models.dysco import DYSCOInfoNCE +from cebra.models.dysco import KDEPotential +from cebra.models.dysco import MLPPotential + + +class QuadraticPotential(nn.Module): + + def __init__(self): + super().__init__() + self.coefficient = nn.Parameter(torch.tensor(0.15, dtype=torch.float64)) + + def forward(self, query, support=None): + return self.coefficient * query.square().sum(-1, keepdim=True) + + +@pytest.mark.parametrize("potential_name", ["none", "quadratic", "kde"]) +def test_submission_value_and_gradient_parity(potential_name): + record = json.loads( + (Path(__file__).parent / "fixtures/dysco_submission.json").read_text()) + case = next(c for c in record["cases"] if c["potential"] == potential_name) + tensors = [ + torch.tensor(case[key], dtype=torch.float64, requires_grad=True) + for key in ("encoded", "forward", "backward") + ] + potential = None if potential_name == "none" else QuadraticPotential( + ) if potential_name == "quadratic" else KDEPotential(epsilon=0.35) + criterion = DYSCOInfoNCE(sample_interval=0.2, + temperature=0.7, + negative_temperature=1.1, + num_positive=2, + num_negatives=6, + potential=potential).double() + encoded, forward, backward = tensors + predictions = torch.stack((forward, backward)) + candidates = torch.stack(tensors).flatten(1, 2) + indices = { + key: torch.tensor(value) for key, value in case["indices"].items() + } + loss, _, _ = criterion(encoded, predictions, candidates, indices=indices) + torch.testing.assert_close(loss, + torch.tensor(case["loss"], dtype=torch.float64), + rtol=1e-10, + atol=1e-10) + variables = tensors + ([potential.coefficient] + if potential_name == "quadratic" else []) + gradients = torch.autograd.grad(loss, variables) + for value, expected in zip(gradients, case["gradients"]): + torch.testing.assert_close(value, + torch.tensor(expected, dtype=torch.float64), + rtol=1e-9, + atol=1e-10) + + +def test_submission_event_sampling_matches_frozen_indices(): + record = json.loads( + (Path(__file__).parent / "fixtures/dysco_submission.json").read_text()) + case = record["cases"][0] + encoded = torch.tensor(case["encoded"]) + criterion = DYSCOInfoNCE(num_positive=2, num_negatives=6, seed=17) + state = torch.random.get_rng_state().clone() + actual = criterion.sample_indices(encoded, 4) + assert torch.equal(state, torch.random.get_rng_state()) + for key, expected in case["indices"].items(): + torch.testing.assert_close(actual[key], torch.tensor(expected)) + + +@pytest.mark.parametrize("count", [1, 2, 4]) +def test_nonmultiple_negative_counts_have_uniform_window_marginal(count): + encoded = torch.zeros(3, 2, 4, 2) + criterion = DYSCOInfoNCE(num_negatives=count) + rows = torch.cat([ + criterion.sample_indices(encoded, 6)["negative"][0] for _ in range(600) + ]) + counts = torch.bincount(rows, minlength=3) + assert torch.all((counts / len(rows) - 1 / 3).abs() < .07) + + +def test_centered_potential_uses_a_common_query_gauge(): + + class CenteredQuadratic(QuadraticPotential): + + def forward(self, query, support=None): + values = super().forward(query, support) + return values - values.mean() + + generator = torch.Generator().manual_seed(7) + encoded = torch.randn(2, + 2, + 3, + 2, + generator=generator, + dtype=torch.float64, + requires_grad=True) + predictions = torch.randn(2, + 2, + 2, + 3, + 2, + generator=generator, + dtype=torch.float64, + requires_grad=True) + candidates = torch.cat((encoded[None], predictions)).flatten(1, 2) + first = DYSCOInfoNCE(sample_interval=.2, + potential=QuadraticPotential()).double() + second = DYSCOInfoNCE(sample_interval=.2, + potential=CenteredQuadratic()).double() + indices = first.sample_indices(encoded, 4) + loss = first(encoded, predictions, candidates, indices=indices)[0] + centered = second(encoded, predictions, candidates, indices=indices)[0] + torch.testing.assert_close(loss, centered) + variables = (encoded, predictions) + gradients = torch.autograd.grad(loss, variables) + centered_gradients = torch.autograd.grad(centered, variables) + for actual, expected in zip(centered_gradients, gradients): + torch.testing.assert_close(actual, expected) + + +@pytest.mark.parametrize("bidirectional", [True, False]) +def test_criterion_finite_difference_gradients(bidirectional): + torch.manual_seed(5) + encoded = torch.randn(2, 1, 3, 2, dtype=torch.float64, requires_grad=True) + predictions = torch.randn(2 if bidirectional else 1, + 2, + 1, + 3, + 2, + dtype=torch.float64, + requires_grad=True) + candidates = torch.randn(3 if bidirectional else 2, + 2, + 3, + 2, + dtype=torch.float64, + requires_grad=True) + criterion = DYSCOInfoNCE(sample_interval=0.4, + potential=KDEPotential(0.8), + bidirectional=bidirectional).double() + indices = criterion.sample_indices(encoded, 2) + # Support is explicitly detached; finite differences hold it fixed by using + # a potential with externally frozen support during this audit. + support = encoded.detach().reshape(-1, 2)[indices["support"]].clone() + + class FrozenKDE(KDEPotential): + + def forward(self, query, support=None): + return super().forward(query, self.support) + + potential = FrozenKDE(0.8) + potential.support = support + criterion.potential = potential + assert torch.autograd.gradcheck( + lambda x, y, z: criterion(x, y, z, indices=indices)[0], + (encoded, predictions, candidates), + atol=1e-5) + + +@pytest.mark.parametrize("architecture", ["offset1-model", "offset10-model"]) +@pytest.mark.parametrize("candidate_mode", ["in_batch", "independent"]) +@pytest.mark.parametrize("controlled", [True, False]) +def test_solver_inherited_training_and_checkpoint(architecture, candidate_mode, + controlled): + torch.manual_seed(3) + dataset = cebra.data.AlignedTrialDataset( + [torch.randn(40, 5) for _ in range(4)], [0, 0, 1, 1], + 0.02, + controls=[torch.randn(40, 1) for _ in range(4)] if controlled else None) + model = cebra.models.init(architecture, + num_neurons=5, + num_units=8, + num_output=2) + dataset.configure_for(model) + loader = cebra.data.AlignedTrialLoader(dataset=dataset, + num_steps=2, + batch_size=3, + batch_size_negatives=5, + rollout_steps=3, + candidate_mode=candidate_mode) + flow = PolynomialFlow(2, control_dim=int(controlled)) + criterion = DYSCOInfoNCE(candidate_mode=candidate_mode, + num_negatives=5, + potential=MLPPotential(2, 8)) + parameters = list(model.parameters()) + list(flow.parameters()) + list( + criterion.parameters()) + solver = cebra.solver.init("aligned-trial-dysco", + model=model, + dynamics_model=flow, + criterion=criterion, + optimizer=torch.optim.Adam(parameters, lr=1e-3), + tqdm_on=False) + assert {id(p) for p in solver.parameters()} == {id(p) for p in parameters} + assert len(list(solver.parameters())) == len(parameters) + before = [ + p.detach().clone() + for p in (next(model.parameters()), flow.field.coefficients, + next(criterion.potential.parameters())) + ] + solver.fit(loader) + assert len(solver.history) == 2 + for previous, current in zip( + before, (next(model.parameters()), flow.field.coefficients, + next(criterion.potential.parameters()))): + assert torch.isfinite(current).all() + assert not torch.equal(previous, current) + restored = copy.deepcopy(solver) + checkpoint = copy.deepcopy(solver.state_dict()) + restored.load_state_dict(checkpoint) + assert restored.reference_model[0] is restored.model + assert restored.reference_model[1] is restored.dynamics_model + batch = next(iter(loader)) + torch.testing.assert_close(torch.tensor(solver.step(batch)["total"]), + torch.tensor(restored.step(batch)["total"])) + for first, second in zip(solver.reference_model.parameters(), + restored.reference_model.parameters()): + torch.testing.assert_close(first, second) + assert solver.transform(torch.randn(20, 5)).shape == (20, 2) + + +def test_controlled_bidirectional_endpoint_consistency(): + model = cebra.models.init("offset1-model", + num_neurons=2, + num_units=8, + num_output=2) + flow = PolynomialFlow(2, degree=1, control_dim=1, dt=0.1) + with torch.no_grad(): + flow.field.coefficients.zero_() + flow.field.coefficients[0, flow.field.terms.index((2,))] = 1 + flow.field.coefficients[1, flow.field.terms.index(())] = 0.2 + criterion = DYSCOInfoNCE(sample_interval=0.1) + optimizer = torch.optim.Adam( + list(model.parameters()) + list(flow.parameters())) + solver = cebra.solver.init("aligned-trial-dysco", + model=model, + dynamics_model=flow, + criterion=criterion, + optimizer=optimizer, + tqdm_on=False) + times = torch.arange(4) * 0.1 + encoded = torch.stack((0.5 * times.square(), 0.2 * times), dim=-1)[None, + None] + encoded = encoded + torch.tensor([0., 1.])[:, None, None, None] + controls = times[None, None, :, None].expand(2, 1, -1, -1) + forward, backward = solver._trajectories(encoded, controls) + torch.testing.assert_close(forward, encoded) + torch.testing.assert_close(backward, encoded) diff --git a/tests/test_dysco_estimator.py b/tests/test_dysco_estimator.py new file mode 100644 index 00000000..2885e5f2 --- /dev/null +++ b/tests/test_dysco_estimator.py @@ -0,0 +1,239 @@ +# +# 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. +# +"""Public DYSCO estimator lifecycle and standard CEBRA reconstruction.""" + +import numpy as np +import pytest +import torch +from sklearn.base import clone + +import cebra +from cebra.integrations.sklearn import metrics + + +@pytest.mark.parametrize("candidate_mode", ["in_batch", "independent"]) +@pytest.mark.parametrize("potential", [None, "kde", "mlp"]) +@pytest.mark.parametrize("controlled", [False, True]) +def test_dysco_estimator_round_trip_and_exact_resume(tmp_path, candidate_mode, + potential, controlled): + rng = np.random.default_rng(4) + trials = [rng.normal(size=(30, 5)).astype("float32") for _ in range(4)] + controls = [rng.normal(size=(30, 1)).astype("float32") for _ in trials + ] if controlled else None + model = cebra.DYSCO( + output_dimension=2, + num_hidden_units=8, + rollout_steps=3, + batch_size=3, + batch_size_negatives=5, + max_iterations=2, + potential=potential, + dynamics_learning_rate=.02 if potential == "mlp" else None, + candidate_mode=candidate_mode, + device="cpu") + torch_state = torch.random.get_rng_state().clone() + model.fit(trials, alignment_ids=[0, 0, 1, 1], controls=controls) + assert torch.equal(torch_state, torch.random.get_rng_state()) + assert clone(model).get_params() == model.get_params() + path = tmp_path / "dysco.pt" + model.save(path) + restored = cebra.CEBRA.load(path, map_location="cpu", weights_only=True) + assert isinstance(restored, cebra.DYSCO) + assert restored.get_params() == model.get_params() + assert [group["lr"] for group in model.solver_.optimizer.param_groups] == [ + model.learning_rate, model.learning_rate if model.dynamics_learning_rate + is None else model.dynamics_learning_rate + ] + assert restored.solver_.reference_model[0] is restored.model_ + assert restored.solver_.reference_model[1] is restored.dynamics_model_ + encoded = model.transform(trials[0]) + np.testing.assert_allclose(encoded, + restored.transform(trials[0]), + atol=1e-7) + u = None if controls is None else controls[0] + np.testing.assert_allclose(model.vector_field(encoded, u), + restored.vector_field(encoded, u)) + segment = None if u is None else u[:4] + np.testing.assert_allclose(model.rollout(encoded[0], 3, segment), + restored.rollout(encoded[0], 3, segment)) + model.partial_fit(trials, alignment_ids=[0, 0, 1, 1], controls=controls) + restored.partial_fit(trials, alignment_ids=[0, 0, 1, 1], controls=controls) + np.testing.assert_allclose(model.transform(trials[0]), + restored.transform(trials[0]), + atol=1e-7) + for first, second in zip(model.solver_.criterion.parameters(), + restored.solver_.criterion.parameters()): + torch.testing.assert_close(first, second) + torch.testing.assert_close(model.dynamics_model_.field.coefficients, + restored.dynamics_model_.field.coefficients) + assert model.equations() == restored.equations() + restored.to(torch.device("cpu")) + assert restored.solver_.criterion._sampling_state.device.type == "cpu" + + +def test_dysco_clone_forward_only_and_explicit_metadata(): + trials = [ + np.random.default_rng(i).normal(size=(25, 3)).astype("float32") + for i in range(2) + ] + model = cebra.DYSCO(num_views=1, + bidirectional=False, + potential=None, + max_iterations=1, + batch_size=2, + rollout_steps=2, + device="cpu") + with pytest.raises(ValueError, match="alignment_ids"): + model.fit(trials) + embeddings = model.fit_transform(trials, alignment_ids=[0, 1]) + assert [x.shape for x in embeddings] == [(25, 3), (25, 3)] + for result in (model.transform(trials), model.transform(np.stack(trials)), + model.transform(trials, batch_size=10)): + for actual, expected in zip(result, embeddings): + np.testing.assert_allclose(actual, expected, atol=2e-8, rtol=2e-6) + assert model.partial_fit(trials, alignment_ids=[0, 1]) is model + with pytest.raises(ValueError, match="dimensions"): + model.partial_fit([np.zeros((25, 4))] * 2, alignment_ids=[0, 1]) + with pytest.raises(ValueError, match="direction"): + model.rollout(np.zeros(3), 2, direction="invalid") + + +def test_callback_checkpoint_resumes_exactly_from_first_fit(tmp_path): + trials = [ + np.random.default_rng(i).normal(size=(25, 3)).astype("float32") + for i in range(4) + ] + model = cebra.DYSCO(max_iterations=2, + batch_size=3, + rollout_steps=2, + num_hidden_units=8, + device="cpu") + path = tmp_path / "callback.pt" + + def snapshot(step, solver): + model.save(path) + + model.fit(trials, + alignment_ids=[0, 0, 1, 1], + callback=snapshot, + callback_frequency=1) + restored = cebra.DYSCO.load(path, weights_only=True) + torch.testing.assert_close(model.sampling_state_, restored.sampling_state_) + model.partial_fit(trials, alignment_ids=[0, 0, 1, 1]) + restored.partial_fit(trials, alignment_ids=[0, 0, 1, 1]) + np.testing.assert_array_equal(model.transform(trials[0]), + restored.transform(trials[0])) + + +def test_partial_fit_rejects_changed_training_configuration(tmp_path): + trials = [np.zeros((20, 3), dtype="float32")] * 2 + model = cebra.DYSCO(max_iterations=1, batch_size=2, device="cpu") + model.fit(trials, alignment_ids=[0, 0]) + model.set_params(temperature=.1, num_positive=2) + with pytest.raises(ValueError, match="configuration changed"): + model.partial_fit(trials, alignment_ids=[0, 0]) + with pytest.raises(ValueError, match="configuration changed"): + model.save(tmp_path / "invalid.pt") + model.fit(trials, alignment_ids=[0, 0]) + assert model.solver_.criterion.temperature == .1 + model.set_params(max_iterations=2) + model.partial_fit(trials, alignment_ids=[0, 0]) + + +def test_checkpoint_rejects_unversioned_objective(tmp_path): + trials = [np.zeros((20, 3), dtype="float32")] * 2 + model = cebra.DYSCO(max_iterations=1, batch_size=2, device="cpu") + model.fit(trials, alignment_ids=[0, 0]) + checkpoint = model._get_state_dict() + assert checkpoint["metadata"].pop("dysco_version") == 1 + path = tmp_path / "unversioned.pt" + torch.save(checkpoint, path) + with pytest.raises(ValueError, match="checkpoint version"): + cebra.CEBRA.load(path, weights_only=True) + + +@pytest.mark.parametrize("rate", [-.01, float("nan"), float("inf")]) +def test_invalid_dynamics_learning_rate(rate): + model = cebra.DYSCO(dynamics_learning_rate=rate, device="cpu") + with pytest.raises(ValueError, match="finite and nonnegative"): + model.fit([np.zeros((20, 3))] * 2, alignment_ids=[0, 0]) + + +def test_cebra_scoring_helpers_reject_dysco_objective(): + trials = [np.zeros((20, 3), dtype="float32")] * 2 + model = cebra.DYSCO(max_iterations=1, batch_size=2, device="cpu") + model.fit(trials, alignment_ids=[0, 0]) + for evaluate in (lambda: metrics.infonce_loss(model, trials[0]), + lambda: metrics.goodness_of_fit_score(model, trials[0]), + lambda: metrics.goodness_of_fit_history(model), + lambda: metrics.infonce_to_goodness_of_fit(1., model)): + with pytest.raises(NotImplementedError, + match="aligned-trial objective"): + evaluate() + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA is unavailable") +def test_dysco_accelerator_and_cpu_checkpoint(tmp_path): + trials = [ + np.random.default_rng(i).normal(size=(30, 3)).astype("float32") + for i in range(2) + ] + model = cebra.DYSCO(device="cuda", + potential="mlp", + num_views=1, + max_iterations=1, + batch_size=2, + rollout_steps=2) + model.fit(trials, alignment_ids=[0, 1]) + path = tmp_path / "accelerator.pt" + model.save(path) + restored = cebra.DYSCO.load(path, map_location="cpu", weights_only=True) + np.testing.assert_allclose(model.transform(trials[0]), + restored.transform(trials[0]), + atol=1e-5) + model.to("cpu") + assert all( + p.device.type == "cpu" for p in model.solver_.criterion.parameters()) + for state in model.solver_.optimizer.state.values(): + assert state["exp_avg"].device.type == "cpu" + assert state["exp_avg_sq"].device.type == "cpu" + model.partial_fit(trials, alignment_ids=[0, 1]) + model.to("cuda") + model.partial_fit(trials, alignment_ids=[0, 1]) + assert model.solver_.criterion._sampling_state.device.type == "cpu" + + +def test_failed_refit_preserves_learned_dynamics(): + rng = np.random.default_rng(12) + trials = rng.normal(size=(2, 20, 4)).astype("float32") + model = cebra.DYSCO(device="cpu", + batch_size=4, + rollout_steps=2, + max_iterations=2).fit(trials, alignment_ids=[0, 0]) + before = model.transform(trials[0]) + forecast = model.rollout(before[0], 2) + model.set_params(sample_interval=0.5) + np.testing.assert_array_equal(model.rollout(before[0], 2), forecast) + with pytest.raises(ValueError, match="num_views"): + model.fit(trials, alignment_ids=[0, 1]) + np.testing.assert_array_equal(model.transform(trials[0]), before) + np.testing.assert_array_equal(model.rollout(before[0], 2), forecast) diff --git a/tests/test_polynomial_dynamics.py b/tests/test_polynomial_dynamics.py new file mode 100644 index 00000000..b1261d2f --- /dev/null +++ b/tests/test_polynomial_dynamics.py @@ -0,0 +1,269 @@ +# +# 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. +# +"""Numerical and lifecycle tests for the DYSCO dynamics foundation.""" + +import math + +import numpy as np +import pytest +import torch + +import cebra +import cebra.dynamics +from cebra.dynamics.polynomial import PolynomialField +from cebra.dynamics.polynomial import PolynomialFlow +from cebra.dynamics.polynomial import RK4Flow + + +def test_polynomial_field_recovers_lorenz(): + field = PolynomialField(3).double() + # 1, x, y, z, xx, xy, xz, yy, yz, zz + with torch.no_grad(): + field.coefficients.zero_() + field.coefficients[0, 1:3] = torch.tensor([-10., 10.]) + field.coefficients[1, [1, 2, 6]] = torch.tensor([28., -1., -1.], + dtype=torch.float64) + field.coefficients[2, [3, 5]] = torch.tensor([-8 / 3, 1.], + dtype=torch.float64) + state = torch.randn(2, 4, 7, 3, dtype=torch.float64) + x, y, z = state.unbind(-1) + expected = torch.stack((10 * (y - x), x * (28 - z) - y, x * y - 8 * z / 3), + -1) + torch.testing.assert_close(field(state), expected) + + +def test_polynomial_features_match_sklearn(): + from sklearn.preprocessing import PolynomialFeatures + state = torch.randn(12, 3, dtype=torch.float64) + control = torch.randn(12, 2, dtype=torch.float64) + field = PolynomialField(3, degree=3, control_dim=2).double() + expected = PolynomialFeatures(3).fit_transform( + torch.cat((state, control), -1).numpy()) + np.testing.assert_allclose(field.features(state, control).numpy(), expected) + + +def test_lorenz_rollout_matches_adaptive_reference_with_views(): + from scipy.integrate import solve_ivp + + field = PolynomialField(3).double() + with torch.no_grad(): + field.coefficients.zero_() + field.coefficients[0, 1:3] = torch.tensor([-10., 10.]) + field.coefficients[1, [1, 2, 6]] = torch.tensor([28., -1., -1.], + dtype=torch.float64) + field.coefficients[2, [3, 5]] = torch.tensor([-8 / 3, 1.], + dtype=torch.float64) + initial = torch.tensor([[[1., 1., 1.], [-2., 3., 5.]]], dtype=torch.float64) + flow = RK4Flow(field, dt=.01, substeps=2) + actual = flow.rollout(initial, 10).detach().numpy() + assert actual.shape == (1, 2, 11, 3) + + def reference(time, state): + x, y, z = state + return [10 * (y - x), x * (28 - z) - y, x * y - 8 * z / 3] + + for view in range(2): + expected = solve_ivp(reference, (0, .1), + initial[0, view].numpy(), + t_eval=np.linspace(0, .1, 11), + rtol=1e-11, + atol=1e-12).y.T + np.testing.assert_allclose(actual[0, view], + expected, + atol=3e-6, + rtol=1e-6) + + +def test_equations_match_controlled_polynomial_and_preserve_coefficients(): + field = PolynomialField(2, degree=3, control_dim=1).double() + state = torch.tensor([[0.3, -0.7]], dtype=torch.float64) + control = torch.tensor([[0.2]], dtype=torch.float64) + coefficients = field.coefficients.detach().clone() + equations = field.equations(precision=17, + variable_names=["x", "y"], + control_names=["forcing"]) + values = {"x": 0.3, "y": -0.7, "forcing": 0.2} + evaluated = [ + eval(equation.split(" = ")[1], {"__builtins__": {}}, values) + for equation in equations + ] + np.testing.assert_allclose(evaluated, field(state, control).detach()[0]) + assert field.equations(threshold=1.0) == ["dz0/dt = 0", "dz1/dt = 0"] + torch.testing.assert_close(coefficients, field.coefficients) + + +def test_equations_lorenz_order_signs_and_precision(): + field = PolynomialField(3).double() + with torch.no_grad(): + field.coefficients.zero_() + field.coefficients[0, 1:3] = torch.tensor([-10., 10.]) + field.coefficients[1, [1, 2, 6]] = torch.tensor([28., -1., -1.], + dtype=torch.float64) + field.coefficients[2, [3, 5]] = torch.tensor([-8 / 3, 1.], + dtype=torch.float64) + assert field.equations(precision=4, variable_names=["x", "y", "z"]) == [ + "dx/dt = -10*x + 10*y", "dy/dt = 28*x - 1*y - 1*x*z", + "dz/dt = -2.667*z + 1*x*y" + ] + + +@pytest.mark.parametrize("kwargs", [ + dict(precision=0), + dict(threshold=-1), + dict(threshold=float("nan")), + dict(variable_names="xy"), + dict(variable_names=["x"]), + dict(variable_names=["x", "x"]), + dict(variable_names=["x", "x+y"]), + dict(variable_names=["u0", "y"]), + dict(variable_names=["x", "class"]) +]) +def test_equations_reject_invalid_format_configuration(kwargs): + with pytest.raises(ValueError): + PolynomialField(2, control_dim=1).equations(**kwargs) + + +def test_rk4_fourth_order_convergence_and_backward(): + field = PolynomialField(1, degree=1, include_bias=False).double() + with torch.no_grad(): + field.coefficients.fill_(1) + initial = torch.ones(2, 1, dtype=torch.float64) + flow = RK4Flow(field, dt=0.25) + coarse = flow.rollout(initial, 4)[..., -1, :] + fine = flow.rollout(initial, 8, dt=0.125)[..., -1, :] + ratio = ((coarse - math.e).abs() / (fine - math.e).abs()).mean() + assert 13 < ratio < 18 + recovered = flow.rollout(fine, 8, dt=-0.125)[..., -1, :] + torch.testing.assert_close(recovered, initial, atol=1e-6, rtol=0) + assert flow.rollout(initial, 4).shape == (2, 5, 1) + + +def test_rotational_flow_matches_analytic_orbit(): + field = PolynomialField(2, degree=1, include_bias=False).double() + with torch.no_grad(): + field.coefficients.copy_(torch.tensor([[0., -2.], [2., 0.]])) + flow = RK4Flow(field, dt=0.05, substeps=2) + time = torch.arange(41, dtype=torch.float64) * 0.05 + expected = torch.stack((torch.cos(2 * time), torch.sin(2 * time)), -1) + actual = flow.rollout(torch.tensor([1., 0.], dtype=torch.float64), 40) + torch.testing.assert_close(actual, expected, atol=3e-7, rtol=0) + + +def test_control_interpolation_and_gradients(): + field = PolynomialField(1, degree=1, control_dim=1, + include_bias=False).double() + with torch.no_grad(): + field.coefficients.copy_(torch.tensor([[0., 1.]])) + flow = RK4Flow(field, dt=1, substeps=3) + initial = torch.zeros(2, 1, dtype=torch.float64, requires_grad=True) + controls = torch.tensor([[[0.], [1.], [2.]]], + dtype=torch.float64).repeat(2, 1, 1) + controls.requires_grad_() + actual = flow.rollout(initial, 2, controls) + torch.testing.assert_close(actual[0, :, 0], + torch.tensor([0., 0.5, 2.], dtype=torch.float64)) + actual[..., -1, :].sum().backward() + assert torch.isfinite(field.coefficients.grad).all() + assert torch.count_nonzero(controls.grad) == controls.numel() + torch.testing.assert_close(initial.grad, torch.ones_like(initial)) + recovered = flow.rollout(actual[..., -1, :], 2, controls.flip(-2), dt=-1) + torch.testing.assert_close(recovered[..., -1, :], initial) + + +def test_flow_passes_autograd_gradcheck(): + torch.manual_seed(3) + field = PolynomialField(2).double() + flow = RK4Flow(field, dt=0.1, substeps=2) + state = torch.randn(3, 2, dtype=torch.float64, requires_grad=True) + assert torch.autograd.gradcheck(flow, (state,)) + + +@pytest.mark.parametrize("kwargs", [ + dict(latent_dim=0), + dict(latent_dim=True), + dict(latent_dim=2, degree=0), + dict(latent_dim=2, control_dim=-1) +]) +def test_invalid_field_configuration(kwargs): + with pytest.raises(ValueError): + PolynomialField(**kwargs) + + +@pytest.mark.parametrize("dt", [0, -0.1, float("nan"), float("inf")]) +def test_invalid_flow_interval(dt): + with pytest.raises(ValueError): + PolynomialFlow(2, dt=dt) + + +def test_controls_and_time_nodes_are_required(): + flow = PolynomialFlow(2, control_dim=1) + state = torch.zeros(3, 2) + with pytest.raises(ValueError, match="Controls"): + flow(state) + with pytest.raises(ValueError, match="time node"): + flow.rollout(state, 3, torch.zeros(3, 3, 1)) + with pytest.raises(ValueError, match="autonomous"): + PolynomialFlow(2).rollout(state, 3, torch.zeros(3, 4, 1)) + with pytest.raises(ValueError, match="nonzero"): + flow.rollout(state, 1, dt=0) + + +def test_registry_state_dict_roundtrip(): + original = cebra.dynamics.init("polynomial-flow", latent_dim=3).double() + restored = cebra.dynamics.init("polynomial-flow", latent_dim=3).double() + restored.load_state_dict(original.state_dict()) + state = torch.randn(4, 3, dtype=torch.float64) + torch.testing.assert_close(original(state), restored(state)) + + +@pytest.mark.parametrize("architecture", ["polynomial-flow"]) +@pytest.mark.parametrize("batch_size", [8, None]) +def test_existing_dcl_fit_save_load_and_resume(tmp_path, architecture, + batch_size): + from cebra.integrations.sklearn.cebra import DCL + torch.manual_seed(4) + data = np.random.default_rng(4).normal(size=(100, 5)).astype("float32") + model = DCL(device="cpu", + dynamics_model_architecture=architecture, + output_dimension=3, + batch_size=batch_size, + batch_size_negatives=11, + max_iterations=2, + distance="euclidean") + model.fit(data) + path = tmp_path / "flow.pt" + model.save(path, backend="sklearn") + loaded = cebra.CEBRA.load(path, backend="sklearn") + np.testing.assert_allclose(model.transform(data), loaded.transform(data)) + state = torch.randn(7, 3) + torch.testing.assert_close(model.dynamics_model_(state), + loaded.dynamics_model_(state)) + before = loaded.dynamics_model_(state).detach().clone() + loaded.partial_fit(data) + assert torch.isfinite(loaded.dynamics_model_(state)).all() + assert not torch.equal(before, loaded.dynamics_model_(state)) + legacy = model.solver_.state_dict() + del legacy["reference_model"] + with pytest.raises(KeyError, match="missing reference_model"): + loaded.solver_.load_state_dict(legacy) + with pytest.warns(UserWarning, match="Legacy auxiliary"): + loaded.solver_.load_state_dict(legacy, strict=False)