Coverage for neuralfields/potential_based.py: 100%
104 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-16 07:32 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-16 07:32 +0000
1from abc import ABC, abstractmethod
2from typing import Callable, Optional, Sequence, Tuple, Union
4import torch
5import torch.utils.data
6from torch import nn
7from torch.nn.utils import convert_parameters
9from neuralfields.custom_types import ActivationFunction
12class PotentialBased(nn.Module, ABC):
13 """Base class for all potential-based recurrent neutral networks."""
15 _tau_opt: Union[torch.Tensor, nn.Parameter]
16 """Optimizable parameter for the time constant."""
17 _kappa_opt: Union[torch.Tensor, nn.Parameter]
18 """Optimizable parameter for the cubic decay."""
20 _stimuli_external: torch.Tensor
21 """Buffer to store the external stimuli to the network."""
22 _stimuli_internal: torch.Tensor
23 """Buffer to store the internal stimuli in the network."""
24 _potentials_init: torch.Tensor
25 """Buffer to store the initial potentials of the network."""
27 _tau_min: Union[float, int] = 1e-5
28 r"""Minimum value for the time constant $\tau$ to avoid numerical instabilities."""
29 _potentials_max: Union[float, int] = 100
30 """Threshold to clip the potentials symmetrically (at a very large value) for numerical stability."""
32 transform_to_opt_space: Callable[[torch.Tensor], torch.Tensor] = torch.log
33 """Function to map parameters to the optimization space."""
34 transform_to_img_space: Callable[[torch.Tensor], torch.Tensor] = torch.exp
35 """Function to map parameters to the image space of the original problem."""
37 def __init__(
38 self,
39 input_size: int,
40 hidden_size: int,
41 activation_nonlin: Union[ActivationFunction, Sequence[ActivationFunction]],
42 tau_init: Union[float, int],
43 tau_learnable: bool,
44 kappa_init: Union[float, int],
45 kappa_learnable: bool,
46 potentials_init: Optional[torch.Tensor] = None,
47 output_size: Optional[int] = None,
48 input_embedding: Optional[nn.Module] = None,
49 output_embedding: Optional[nn.Module] = None,
50 ):
51 """
52 Args:
53 input_size: Number of input dimensions.
54 hidden_size: Number of neurons with potential per hidden layer. For all use cases conceived at this point,
55 we only use one recurrent layer. However, there is the possibility to extend the networks to multiple
56 potential-based layers.
57 activation_nonlin: Nonlinearity used to compute the activations from the potential levels.
58 tau_init: Initial value for the shared time constant of the potentials.
59 tau_learnable: Whether the time constant is a learnable parameter or fixed.
60 kappa_init: Initial value for the cubic decay, pass 0 to disable the cubic decay.
61 kappa_learnable: Whether the cubic decay is a learnable parameter or fixed.
62 potentials_init: Initial for the potentials, i.e., the network's hidden state.
63 output_size: Number of output dimensions. By default, the number of outputs is equal to the number of
64 hidden neurons.
65 input_embedding: Optional (custom) [Module][torch.nn.Module] to extract features from the inputs.
66 This module must transform the inputs such that the dimensionality matches the number of
67 neurons of the neural field, i.e., `hidden_size`. By default, a [linear layer][torch.nn.Linear]
68 without biases is used.
69 output_embedding: Optional (custom) [Module][torch.nn.Module] to compute the outputs from the activations.
70 This module must map the activations of shape (`hidden_size`,) to the outputs of shape (`output_size`,)
71 By default, a [linear layer][torch.nn.Linear] without biases is used.
72 """
73 # Call torch.nn.Module's constructor.
74 super().__init__()
76 # For all use cases conceived at this point, we only use one recurrent layer. However, this variable still
77 # exists in case somebody in the future wants to try multiple potential-based layers. It will require more
78 # changes than increasing this number.
79 self.num_recurrent_layers = 1
81 self.input_size = input_size
82 self._hidden_size = hidden_size // self.num_recurrent_layers # hidden size per layer
83 self.output_size = self._hidden_size if output_size is None else output_size
84 # Create the common layers.
85 self.input_embedding = (
86 input_embedding
87 if input_embedding is not None
88 else nn.Linear(self.input_size, self._hidden_size, bias=False)
89 )
90 self.output_embedding = (
91 output_embedding
92 if output_embedding is not None
93 else nn.Linear(self._hidden_size, self.output_size, bias=False)
94 )
96 # Initialize the external and internal stimuli buffers.
97 self.register_buffer("_stimuli_external", torch.zeros(self.hidden_size), persistent=False)
98 self.register_buffer("_stimuli_internal", torch.zeros(self.hidden_size), persistent=False)
100 # Initialize the values of the potentials.
101 if potentials_init is not None:
102 potentials_init = potentials_init.detach().clone()
103 else:
104 if activation_nonlin is torch.sigmoid:
105 potentials_init = -7 * torch.ones(1, self.hidden_size)
106 else:
107 potentials_init = torch.zeros(1, self.hidden_size)
108 self.register_buffer("_potentials_init", potentials_init, persistent=False)
110 # Initialize the potentials' resting level, i.e., the asymptotic level without stimuli.
111 self.resting_level = nn.Parameter(torch.randn(self.hidden_size))
113 # Initialize the potential dynamics' time constant.
114 self.tau_learnable = tau_learnable
115 if tau_init <= PotentialBased._tau_min:
116 raise ValueError(f"The time constant tau must be initialized greater than {PotentialBased._tau_min}.")
117 tau_opt_init = PotentialBased.transform_to_opt_space(
118 torch.as_tensor(tau_init - PotentialBased._tau_min, dtype=torch.get_default_dtype())
119 )
120 self._tau_opt = nn.Parameter(tau_opt_init.reshape(-1), requires_grad=self.tau_learnable)
122 # Initialize the potential dynamics' cubic decay.
123 self.kappa_learnable = kappa_learnable
124 if kappa_init < 0:
125 raise ValueError("The cubic decay kappa must be initialized non-negative.")
126 kappa_opt_init = PotentialBased.transform_to_opt_space(
127 torch.as_tensor(kappa_init, dtype=torch.get_default_dtype()).reshape(-1)
128 )
129 self._kappa_opt = nn.Parameter(kappa_opt_init, requires_grad=self.kappa_learnable)
131 def extra_repr(self) -> str:
132 return f"tau_learnable={self.tau_learnable}, kappa_learnable={self.kappa_learnable}"
134 @property
135 def param_values(self) -> torch.Tensor:
136 """Get the module's parameters as a 1-dimensional array.
137 The values are copied, thus modifying the return value does not propagate back to the module parameters.
138 """
139 return convert_parameters.parameters_to_vector(self.parameters())
141 @param_values.setter
142 def param_values(self, param: torch.Tensor):
143 """Set the module's parameters from a 1-dimensional array."""
144 convert_parameters.vector_to_parameters(param, self.parameters())
146 @property
147 def hidden_size(self) -> int:
148 """Get the number of neurons in the neural field layer, i.e., the ones with the in-/exhibition dynamics."""
149 return self.num_recurrent_layers * self._hidden_size
151 @property
152 def stimuli_external(self) -> torch.Tensor:
153 """Get the neurons' external stimuli, resulting from the current inputs.
154 This property is useful for recording during a simulation / rollout.
155 """
156 return self._stimuli_external
158 @property
159 def stimuli_internal(self) -> torch.Tensor:
160 """Get the neurons' internal stimuli, resulting from the previous activations of the neurons.
161 This property is useful for recording during a simulation / rollout.
162 """
163 return self._stimuli_internal
165 @property
166 def tau(self) -> Union[torch.Tensor, nn.Parameter]:
167 r"""Get the timescale parameter, called $\tau$ in the original paper [Amari_77]."""
168 return PotentialBased.transform_to_img_space(self._tau_opt) + PotentialBased._tau_min
170 @property
171 def kappa(self) -> Union[torch.Tensor, nn.Parameter]:
172 r"""Get the cubic decay parameter $\kappa$."""
173 return PotentialBased.transform_to_img_space(self._kappa_opt)
175 @abstractmethod
176 def potentials_dot(self, potentials: torch.Tensor, stimuli: torch.Tensor) -> torch.Tensor:
177 """Compute the derivative of the neurons' potentials w.r.t. time.
179 Args:
180 potentials: Potential values at the current point in time, of shape `(hidden_size,)`.
181 stimuli: Sum of external and internal stimuli at the current point in time, of shape `(hidden_size,)`.
183 Returns:
184 Time derivative of the potentials $\frac{dp}{dt}$, of shape `(hidden_size,)`.
185 """
187 def init_hidden(
188 self, batch_size: Optional[int] = None, potentials_init: Optional[torch.Tensor] = None
189 ) -> Union[torch.Tensor, torch.nn.Parameter]:
190 """Provide initial values for the hidden parameters. This usually is a zero tensor.
192 Args:
193 batch_size: Number of batches, i.e., states to track in parallel.
194 potentials_init: Initial values for the potentials to override the networks default values with. Must be
195 on the model's device when provided.
197 Returns:
198 Tensor of shape `(hidden_size,)` if `hidden` was not batched, else of shape `(batch_size, hidden_size)`.
199 """
200 if potentials_init is None:
201 if batch_size is None:
202 return self._potentials_init.view(-1)
203 return self._potentials_init.repeat(batch_size, 1)
205 return potentials_init
207 @staticmethod
208 def _infer_batch_size(inputs: torch.Tensor) -> int:
209 """Get the number of batch dimensions from the inputs to the model.
210 The batch dimension is assumed to be located at the first axis of the input [tensor][torch.Tensor].
212 Args:
213 inputs: Inputs to the forward pass, could be of shape `(input_size,)` or `(batch_size, input_size)`.
215 Returns:
216 The number of batch dimensions a.k.a. the batch size.
217 """
218 if inputs.dim() == 1:
219 return 1
220 return inputs.size(0)
222 @abstractmethod
223 def forward_one_step(
224 self, inputs: torch.Tensor, hidden: Optional[torch.Tensor] = None
225 ) -> Tuple[torch.Tensor, torch.Tensor]:
226 """Compute the external and internal stimuli, advance the potential dynamics for one time step, and return
227 the model's output.
229 Args:
230 inputs: Inputs of the current time step, of shape `(input_size,)`, or `(batch_size, input_size)`, on the
231 model's device.
232 hidden: Hidden state which are for the model in this package the potentials, of shape `(hidden_size,)`, or
233 `(batch_size, input_size)`. Pass `None` to leave the initialization to the network which uses
234 [init_hidden][neuralfields.PotentialBased.init_hidden] is called. Must be on the model's device when
235 provided.
237 Returns:
238 The outputs, i.e., the (linearly combined) activations, and the most recent potential values, both of shape
239 `(batch_size, input_size)`.
240 """
242 def forward(self, inputs: torch.Tensor, hidden: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
243 """Compute the external and internal stimuli, advance the potential dynamics for one time step, and return
244 the model's output for several time steps in a row.
246 This method essentially calls [forward_one_step][neuralfields.PotentialBased.forward_one_step] several times
247 in a row.
249 Args:
250 inputs: Inputs of shape `(batch_size, num_steps, dim_input)` to evaluate the network on, on the model's
251 device.
252 hidden: Initial values of the hidden states, i.e., the potentials. By default, the network initialized
253 the hidden state to be all zeros. However, via this argument one can set a specific initial value
254 for the potentials. Depending on the shape of `inputs`, `hidden` is of shape `(hidden_size,)` if
255 the input was not batched, else of shape `(batch_size, hidden_size)`. Must be on the model's device
256 when provided.
258 Returns:
259 The outputs, i.e., the (linearly combined) activations, and all intermediate potential values, both of
260 shape `(batch_size, num_steps, dim_output)`.
261 """
262 # Bring the sequence of inputs into the shape (batch_size, num_steps, dim_input).
263 batch_size = PotentialBased._infer_batch_size(inputs)
264 inputs = inputs.reshape(batch_size, -1, self.input_size)
266 # If given use the hidden tensor, i.e., the potentials of the last step, else initialize them.
267 hidden = self.init_hidden(batch_size, hidden)
269 # Iterate over the time dimension. Do this in parallel for all batched which are still along the 1st dimension.
270 inputs = inputs.permute(1, 0, 2) # move time to first dimension for easy iterating
271 outputs_all = []
272 hidden_all = []
273 for inp in inputs:
274 outputs, hidden_next = self.forward_one_step(inp, hidden)
275 hidden = hidden_next
276 outputs_all.append(outputs)
277 hidden_all.append(hidden_next)
279 # Return the outputs and hidden states, both stacked along the time dimension.
280 return torch.stack(outputs_all, dim=1), torch.stack(hidden_all, dim=1)