Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions cebra/attribution/_jacobian.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,8 @@ def _prepare_model_and_inputs():
prepared_inputs = tensors_to_cpu_and_double(input_vars)
else:
prepared_model = model.to(cuda_device).float()
prepared_inputs = tensors_to_cuda(input_vars, cuda_device=cuda_device)
prepared_inputs = tensors_to_cuda(input_vars,
cuda_device=cuda_device)
return prepared_model, prepared_inputs

def _forward_outputs(prepared_model, prepared_inputs):
Expand All @@ -135,28 +136,28 @@ def _forward_outputs(prepared_model, prepared_inputs):
output_vars = _forward_outputs(prepared_model, prepared_inputs)
n_outputs = int(output_vars.shape[1])
effective_output_batch_size = (
n_outputs
if output_batch_size is None or any(
module.training for module in prepared_model.modules())
else min(int(output_batch_size), n_outputs)
)
n_outputs if output_batch_size is None or any(
module.training for module in prepared_model.modules()) else
min(int(output_batch_size), n_outputs))

jacob_chunks = []
for output_start in range(0, n_outputs, effective_output_batch_size):
output_end = min(output_start + effective_output_batch_size, n_outputs)
output_end = min(output_start + effective_output_batch_size,
n_outputs)
if output_start > 0:
output_vars = _forward_outputs(prepared_model, prepared_inputs)

chunk_rows = []
for local_idx, output_idx in enumerate(range(output_start, output_end)):
for local_idx, output_idx in enumerate(
range(output_start, output_end)):
is_last_in_chunk = local_idx == (output_end - output_start - 1)
grads = torch.autograd.grad(
output_vars[:, output_idx : output_idx + 1],
output_vars[:, output_idx:output_idx + 1],
prepared_inputs,
retain_graph=not is_last_in_chunk,
create_graph=False,
grad_outputs=torch.ones(
output_vars[:, output_idx : output_idx + 1].shape,
output_vars[:, output_idx:output_idx + 1].shape,
device=output_vars.device,
),
)
Expand Down
22 changes: 10 additions & 12 deletions cebra/attribution/attribution_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
import cebra.attribution._jacobian
from cebra.attribution import register


_VALID_ATTRIBUTION_RESULT_KEYS = {
"jf",
"jf-convabs",
Expand All @@ -56,8 +55,7 @@ def _normalize_selected_result_keys(selected_keys):
if key_str not in _VALID_ATTRIBUTION_RESULT_KEYS:
raise ValueError(
f"Unknown attribution result key {key!r}. "
f"Valid keys: {sorted(_VALID_ATTRIBUTION_RESULT_KEYS)}"
)
f"Valid keys: {sorted(_VALID_ATTRIBUTION_RESULT_KEYS)}")
normalized.append(key_str)
return set(normalized)

Expand Down Expand Up @@ -376,9 +374,9 @@ def compute_attribution_map(self, selected_keys=None):
if selected_keys is not None and inv_key not in selected_keys:
continue
print(f"Computing inverse for {key} with method {method}")
result[inv_key], result[f'time_inversion_{method}'] = self._inverse(
value, method=method
)
result[inv_key], result[
f'time_inversion_{method}'] = self._inverse(value,
method=method)
# result[f"{key}-inv-{method}-conditions"] = self.check_moores_penrose_conditions(value, result[f"{key}-inv-{method}"])

return result
Expand Down Expand Up @@ -417,9 +415,9 @@ def compute_attribution_map(self, batch_size=1024, selected_keys=None):
inv_key = f"{key}-inv-{method}"
if selected_keys is not None and inv_key not in selected_keys:
continue
result[inv_key], result[f'time_inversion_{method}'] = self._inverse(
value, method=method
)
result[inv_key], result[
f'time_inversion_{method}'] = self._inverse(value,
method=method)

return result

Expand Down Expand Up @@ -457,7 +455,8 @@ def compute_attribution_map(
)

input_data_batches = torch.split(self.input_data, batch_size)
keys = sorted(_VALID_ATTRIBUTION_RESULT_KEYS if selected_keys is None else selected_keys)
keys = sorted(_VALID_ATTRIBUTION_RESULT_KEYS if selected_keys is
None else selected_keys)

if return_full:
per_key_chunks = {key: [] for key in keys}
Expand All @@ -472,8 +471,7 @@ def compute_attribution_map(

for input_data_batch in input_data_batches:
jacobian_batch = self._compute_jacobian(
input_data_batch, output_batch_size=latent_batch_size
)
input_data_batch, output_batch_size=latent_batch_size)
reduced_batch = self._reduce_attribution_map({'jf': jacobian_batch})
batch_samples = next(iter(reduced_batch.values())).shape[0]

Expand Down
6 changes: 3 additions & 3 deletions cebra/attribution/feature_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,8 @@ def _num_valid_rows(model, n_samples: int) -> int:
n_valid = int(n_samples) - (left + right) + 1
if n_valid < 1:
raise ValueError(
f"{n_samples} input samples are too few for the model window ({left + right}).")
f"{n_samples} input samples are too few for the model window ({left + right})."
)
return n_valid


Expand Down Expand Up @@ -519,8 +520,7 @@ def feature_attribution_map(

if labels is not None or session_id is not None or random_ties:
raise ValueError(
"labels, session_id and random_ties are only for unified solvers."
)
"labels, session_id and random_ties are only for unified solvers.")
if isinstance(inputs, (list, tuple)):
raise ValueError(
"A single-session model needs inputs of shape (T, N), not a list.")
Expand Down
20 changes: 10 additions & 10 deletions cebra/data/datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,10 +143,10 @@ def __len__(self):

def to(self, device: str) -> "TensorDataset":
"""Move dataset to the specified device.

Args:
device: Target device

Returns:
Self for chaining
"""
Expand Down Expand Up @@ -558,10 +558,10 @@ def __getitem__(self, args) -> List[Batch]:

class UnifiedxCEBRADataset(UnifiedDataset):
"""Multi-session unified dataset with per-objective labels for multiobjective learning.

Extends UnifiedDataset to support flexible, per-objective label selection and
concatenation across sessions. Designed to work with UnifiedContrastiveMultiObjectiveLoader.

Example:
>>> import cebra.data
>>> import torch
Expand All @@ -573,10 +573,10 @@ class UnifiedxCEBRADataset(UnifiedDataset):
>>> label1_obj2 = torch.randn((100,))
>>> label2_obj1 = torch.randn((100,))
>>> label2_obj2 = torch.randn((100,))
>>>
>>>
>>> dataset1 = cebra.data.TensorDataset(session1, continuous=index1)
>>> dataset2 = cebra.data.TensorDataset(session2, continuous=index2)
>>>
>>>
>>> # Create unified dataset with per-session labels
>>> unified_dataset = cebra.data.UnifiedxCEBRADataset(dataset1, dataset2)
>>> # Add per-objective labels (stored per session)
Expand All @@ -590,7 +590,7 @@ def __init__(self, *datasets: cebra_data.SingleSessionDataset):

def add_labels(self, label_name: str, label_list: List[torch.Tensor]):
"""Add a set of per-objective labels, one per session.

Args:
label_name: Name of the label/objective (e.g., "position", "velocity")
label_list: List of label tensors, one per session, each of shape (session_length,)
Expand All @@ -616,15 +616,15 @@ def _to_tensor(data: Union[torch.Tensor, np.ndarray]) -> torch.Tensor:

def load_batch_contrastive(self, index: BatchIndex) -> Batch:
"""Load a batch for contrastive learning with per-objective positives.

Returns a single Batch with shared ref/neg and a list of positives (one per objective).

Args:
index: BatchIndex with:
- reference: (num_sessions, num_samples) tensor (shared across objectives)
- negative: (num_sessions, num_samples) tensor (shared across objectives)
- positive: list of (num_sessions, num_samples) tensors, one per objective

Returns:
A :py:class:`~cebra.data.datatypes.Batch` whose ``reference`` and ``negative`` are
concatenated across sessions and whose ``positive`` is a list of tensors, one per
Expand Down
26 changes: 12 additions & 14 deletions cebra/data/multiobjective.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
#

import literate_dataclasses as dataclasses
import numpy as np
import torch

import cebra.data as cebra_data
Expand Down Expand Up @@ -178,7 +177,7 @@ def __iter__(self):
@dataclasses.dataclass
class UnifiedContrastiveMultiObjectiveLoader(cebra_data.Loader):
"""Unified Contrastive Multiobjective data Loader for multi-session training.

Uses a single shared model across sessions with per-objective time_delta distributions.
Reference and negative samples are shared across all objectives and sampled uniformly
across sessions via UnifiedSampler. Positive samples are drawn per-objective using
Expand All @@ -192,7 +191,8 @@ class UnifiedContrastiveMultiObjectiveLoader(cebra_data.Loader):

sampling_mode_contrastive: str = dataclasses.field(
default="refneg_shared",
doc="""Type of sampling performed, re whether reference and negative samples
doc=
"""Type of sampling performed, re whether reference and negative samples
are shared. Only 'refneg_shared' is supported for unified multiobjective."""
)

Expand All @@ -211,18 +211,16 @@ def add_config(self, config):
``continuous_index``.
"""
kwargs_distribution = config['kwargs']

if config['distribution'] != "unified_time_delta":
raise NotImplementedError(
f"Only 'unified_time_delta' distribution is supported for unified multiobjective, "
f"got '{config['distribution']}'."
)

f"got '{config['distribution']}'.")

if not hasattr(self.dataset, 'continuous_index'):
raise ValueError(
"UnifiedDataset must have 'continuous_index' attribute."
)

"UnifiedDataset must have 'continuous_index' attribute.")

distribution = cebra.distributions.UnifiedSampler(
self.dataset,
kwargs_distribution.get('time_delta', self.time_offset),
Expand All @@ -232,14 +230,14 @@ def add_config(self, config):

def get_indices(self, num_samples: int):
"""Sample and return the specified number of indices for unified multiobjective.

Reference and negative indices are shared across all objectives and sampled
uniformly across sessions. Positive indices are drawn per-objective using
time_delta distributions with random shifts.

Args:
num_samples: Batch size (number of samples per objective).

Returns:
A BatchIndex with:
- reference: shape (num_sessions, num_samples) tensor shared across objectives
Expand All @@ -250,7 +248,7 @@ def get_indices(self, num_samples: int):
raise ValueError(
f"Sampling mode {self.sampling_mode_contrastive} is not implemented yet."
)

# Sample shared reference and negative using the first distribution
# These come back as numpy arrays from UnifiedSampler
ref_idx_np = self.distributions[0].sample_prior(self.batch_size)
Expand Down
2 changes: 1 addition & 1 deletion cebra/distributions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,5 +64,5 @@
"DeltaNormalDistribution",
"MultivariateDiscrete",
"MultisessionSampler",
"UnifiedSampler"
"UnifiedSampler",
]
5 changes: 4 additions & 1 deletion cebra/models/jacobian_regularizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,10 @@ def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
R = (1 / 2) * J2
return R

def _random_vector(self, C: int, B: int, device: torch.device = None) -> torch.Tensor:
def _random_vector(self,
C: int,
B: int,
device: torch.device = None) -> torch.Tensor:
"""Creates a random vector of dimension C with a norm of C^(1/2).

This is needed for the projection formula to work.
Expand Down
38 changes: 22 additions & 16 deletions tests/test_attribution.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,15 +226,14 @@ def _optimized_and_reference(model, input_data, batch_size, **kwargs):
model=model,
input_data=input_data,
output_dimension=3)
return (optimized.compute_attribution_map(batch_size=batch_size,
**kwargs),
return (optimized.compute_attribution_map(batch_size=batch_size, **kwargs),
reference.compute_attribution_map(batch_size=batch_size))


@pytest.mark.parametrize("conv", [False, True])
def test_jacobian_batched_optimized_matches_batched(conv):
keys = ("jf", "jf-convabs", "jf-inv-lsq", "jf-inv-svd", "jf-convabs-inv-lsq",
"jf-convabs-inv-svd")
keys = ("jf", "jf-convabs", "jf-inv-lsq", "jf-inv-svd",
"jf-convabs-inv-lsq", "jf-convabs-inv-svd")
torch.manual_seed(0)
if conv:
model = cebra.models.init("offset10-model",
Expand All @@ -248,7 +247,10 @@ def test_jacobian_batched_optimized_matches_batched(conv):
# batch_size does not divide the number of samples: the last batch is smaller.
full, reference = _optimized_and_reference(model, input_data, batch_size=32)
for key in keys:
np.testing.assert_allclose(full[key], reference[key], rtol=1e-5, atol=1e-6)
np.testing.assert_allclose(full[key],
reference[key],
rtol=1e-5,
atol=1e-6)

mean, _ = _optimized_and_reference(model,
input_data,
Expand All @@ -267,15 +269,21 @@ def test_jacobian_batched_optimized_selected_keys_and_latent_batching():
model = torch.nn.Sequential(torch.nn.Linear(6, 8), torch.nn.Tanh(),
torch.nn.Linear(8, 3))
input_data = torch.randn(40, 6, requires_grad=True)
full, reference = _optimized_and_reference(model,
input_data,
batch_size=16,
selected_keys=["jf", "jf_inv_svd"],
latent_batch_size=1)
full, reference = _optimized_and_reference(
model,
input_data,
batch_size=16,
selected_keys=["jf", "jf_inv_svd"],
latent_batch_size=1)
# "_" is read as "-"; only the selected maps and the timings are returned.
assert set(full) == {"jf", "jf-inv-svd", "time_inversion_lsq", "time_inversion_svd"}
assert set(full) == {
"jf", "jf-inv-svd", "time_inversion_lsq", "time_inversion_svd"
}
assert full["time_inversion_lsq"] == 0.0
np.testing.assert_allclose(full["jf"], reference["jf"], rtol=1e-5, atol=1e-6)
np.testing.assert_allclose(full["jf"],
reference["jf"],
rtol=1e-5,
atol=1e-6)
np.testing.assert_allclose(full["jf-inv-svd"],
reference["jf-inv-svd"],
rtol=1e-5,
Expand Down Expand Up @@ -314,8 +322,7 @@ def test_compute_jacobian_output_batching(output_batch_size):
@pytest.mark.parametrize("mixed_mode", [False, True])
def test_compute_jacobian_output_batching_with_dropout(mixed_mode):
torch.manual_seed(0)
model = torch.nn.Sequential(torch.nn.Linear(6, 8),
torch.nn.Dropout(0.5),
model = torch.nn.Sequential(torch.nn.Linear(6, 8), torch.nn.Dropout(0.5),
torch.nn.Linear(8, 5))
if mixed_mode:
model.eval()
Expand All @@ -338,8 +345,7 @@ def test_compute_jacobian_output_batching_with_dropout(mixed_mode):

@pytest.mark.parametrize("training", [False, True])
def test_compute_jacobian_output_batching_forward_count(training):
model = torch.nn.Sequential(torch.nn.BatchNorm1d(6),
torch.nn.Linear(6, 5))
model = torch.nn.Sequential(torch.nn.BatchNorm1d(6), torch.nn.Linear(6, 5))
model.train(training)
forwards = []
handle = model.register_forward_hook(
Expand Down
Loading