36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226 | class BaseCoreReadout(LightningModule):
def __init__(
self,
core: Core,
readout: nn.Module,
learning_rate: float,
loss: nn.Module | None = None,
correlation_loss: nn.Module | None = None,
data_info: dict[str, Any] | None = None,
):
super().__init__()
self.core = core
self.readout = readout
self.learning_rate = learning_rate
self.loss = loss if loss is not None else PoissonLoss3d()
self.correlation_loss = correlation_loss if correlation_loss is not None else CorrelationLoss3d(avg=True)
if data_info is None:
data_info = {}
self.data_info = data_info
def on_train_epoch_end(self):
# Compute the 2-norm for each layer at the end of the epoch
core_norms = grad_norm(self.core, norm_type=2)
self.log_dict(core_norms, on_step=False, on_epoch=True)
readout_norms = grad_norm(self.readout, norm_type=2)
self.log_dict(readout_norms, on_step=False, on_epoch=True)
def forward(self, x: Float[torch.Tensor, "batch channels t h w"], data_key: str | None = None) -> torch.Tensor:
output_core = self.core(x)
output_readout = self.readout(output_core, data_key=data_key)
return output_readout
def training_step(self, batch: tuple[str, DataPoint], batch_idx: int) -> torch.Tensor:
session_id, data_point = batch
model_output = self.forward(data_point.inputs, session_id)
loss = self.loss.forward(model_output, data_point.targets)
regularization_loss_core = self.core.regularizer()
regularization_loss_readout = self.readout.regularizer(session_id) # type: ignore
total_loss = loss + regularization_loss_core + regularization_loss_readout
correlation = -self.correlation_loss.forward(model_output, data_point.targets)
self.log("regularization_loss_core", regularization_loss_core, on_step=False, on_epoch=True)
self.log("regularization_loss_readout", regularization_loss_readout, on_step=False, on_epoch=True)
self.log("train_total_loss", total_loss, on_step=False, on_epoch=True)
self.log("train_loss", loss, on_step=False, on_epoch=True)
self.log("train_correlation", correlation, on_step=False, on_epoch=True, prog_bar=True)
return total_loss
def validation_step(self, batch: tuple[str, DataPoint], batch_idx: int) -> torch.Tensor:
session_id, data_point = batch
model_output = self.forward(data_point.inputs, session_id)
loss = self.loss.forward(model_output, data_point.targets) / sum(model_output.shape)
regularization_loss_core = self.core.regularizer()
regularization_loss_readout = self.readout.regularizer(session_id) # type: ignore
total_loss = loss + regularization_loss_core + regularization_loss_readout
correlation = -self.correlation_loss.forward(model_output, data_point.targets)
self.log("val_loss", loss, logger=True, prog_bar=True)
self.log("val_regularization_loss_core", regularization_loss_core, logger=True)
self.log("val_regularization_loss_readout", regularization_loss_readout, logger=True)
self.log("val_total_loss", total_loss, logger=True)
self.log("val_correlation", correlation, logger=True, prog_bar=True)
return loss
def test_step(self, batch: tuple[str, DataPoint], batch_idx: int, dataloader_idx: int = 0) -> torch.Tensor:
session_id, data_point = batch
model_output = self.forward(data_point.inputs, session_id)
loss = self.loss.forward(model_output, data_point.targets) / sum(model_output.shape)
avg_correlation = -self.correlation_loss.forward(model_output, data_point.targets)
per_neuron_correlation = self.correlation_loss._per_neuron_correlations
# Add metric and performances to data_info for downstream tasks
if "pretrained_performance_metric" not in self.data_info:
self.data_info["pretrained_performance_metric"] = "test " + type(self.correlation_loss).__name__
if "pretrained_performance" not in self.data_info:
self.data_info["pretrained_performance"] = {}
# Also add cut frames if not present
if "model_cut_frames" not in self.data_info:
self.data_info["model_cut_frames"] = data_point.targets.size(1) - model_output.size(1)
self.data_info["pretrained_performance"][session_id] = per_neuron_correlation
self.log_dict(
{
"test_loss": loss,
"test_correlation": avg_correlation,
}
)
return loss
def on_test_end(self):
# Update internal lightning hyperparameters to save the updated data_info after testing.
self.hparams["data_info"] = self.data_info
# Save using checkpointer callback (should always exist with our default configs)
if self.trainer and self.trainer.checkpoint_callback:
best_model_path = self.trainer.checkpoint_callback.best_model_path
if best_model_path:
final_path = best_model_path.replace(".ckpt", "_final.ckpt")
self.trainer.save_checkpoint(final_path)
def configure_optimizers(self):
optimizer = torch.optim.AdamW(self.parameters(), lr=self.learning_rate)
lr_decay_factor = 0.3
patience = 5
tolerance = 0.0005
min_lr = self.learning_rate * (lr_decay_factor**3)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
optimizer,
mode="max",
factor=lr_decay_factor,
patience=patience,
threshold=tolerance,
threshold_mode="abs",
min_lr=min_lr,
)
return {
"optimizer": optimizer,
"lr_scheduler": {
"scheduler": scheduler,
"monitor": "val_correlation",
"frequency": 1,
},
}
def save_weight_visualizations(self, folder_path: str, file_format: str = "jpg", state_suffix: str = "") -> None:
"""Save weight visualizations for core and readout modules.
Args:
folder_path: Base directory to save visualizations
file_format: Image format for saved files
state_suffix: Optional suffix for state identification
"""
# Helper function to call save_weight_visualizations with dynamic parameter support
def _call_save_viz(module: Any, subfolder: str) -> None:
full_path = os.path.join(folder_path, subfolder)
# Check if the method supports state_suffix parameter
if "state_suffix" in inspect.signature(module.save_weight_visualizations).parameters:
kwargs = {"state_suffix": state_suffix}
else:
kwargs = {}
module.save_weight_visualizations(full_path, file_format, **kwargs)
_call_save_viz(self.core, "weights_core")
_call_save_viz(self.readout, "weights_readout")
def compute_readout_input_shape(
self, core_in_shape: tuple[int, int, int, int], core: Core
) -> tuple[int, int, int, int]:
# Use the same device as the core's parameters to avoid potential errors at init.
device = next(core.parameters()).device
with torch.no_grad():
stimulus = torch.zeros((1,) + tuple(core_in_shape), device=device)
core_test_output = core.forward(stimulus)
return core_test_output.shape[1:] # type: ignore
def stimulus_shape(self, time_steps: int, num_batches: int = 1) -> tuple[int, int, int, int, int]:
channels, width, height = self.data_info["input_shape"] # type: ignore
return num_batches, channels, time_steps, width, height
def update_model_data_info(self, data_info: dict[str, Any]) -> None:
"""To update relevant model attributes when loading a (trained) model and training it with new data only."""
# update model.data_info and n_neurons_dict with the new data info
for key in data_info.keys():
if key == "input_shape":
assert all(self.data_info[key][dim] == data_info[key][dim] for dim in range(len(data_info[key]))), (
f"Input shapes don't match: model has {self.data_info[key]}, new data has {data_info[key]}"
)
else:
self.data_info[key].update(data_info[key])
# update saved hyperparameters (so that the model can be loaded from checkpoint correctly)
if hasattr(self, "hparams"):
self.hparams["n_neurons_dict"] = self.data_info["n_neurons_dict"]
self.hparams["data_info"] = self.data_info
@property
def pretrained_cfg(self) -> dict[str, Any]:
"""Alias for data_info, following `timm` (Pytorch Image Models) conventions."""
return self.data_info
|