Coverage for neuralfields/neural_fields.py: 100%

47 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-10-16 07:32 +0000

1from typing import Optional, Sequence, Tuple, Union 

2 

3import torch 

4from torch import nn 

5 

6from neuralfields.custom_layers import IndependentNonlinearitiesLayer, MirroredConv1d, init_param_ 

7from neuralfields.custom_types import ActivationFunction 

8from neuralfields.potential_based import PotentialBased 

9 

10 

11class NeuralField(PotentialBased): 

12 """A potential-based recurrent neural network according to [Amari, 1977]. 

13 

14 See Also: 

15 [Amari, 1977] S.-I. Amari, "Dynamics of Pattern Formation in Lateral-Inhibition Type Neural Fields", 

16 Biological Cybernetics, 1977. 

17 """ 

18 

19 def __init__( 

20 self, 

21 input_size: int, 

22 hidden_size: int, 

23 output_size: Optional[int] = None, 

24 input_embedding: Optional[nn.Module] = None, 

25 output_embedding: Optional[nn.Module] = None, 

26 activation_nonlin: Union[ActivationFunction, Sequence[ActivationFunction]] = torch.sigmoid, 

27 mirrored_conv_weights: bool = True, 

28 conv_kernel_size: Optional[int] = None, 

29 conv_padding_mode: str = "circular", 

30 conv_out_channels: int = 1, 

31 conv_pooling_norm: int = 1, 

32 tau_init: Union[float, int] = 10, 

33 tau_learnable: bool = True, 

34 kappa_init: Union[float, int] = 1e-5, 

35 kappa_learnable: bool = True, 

36 potentials_init: Optional[torch.Tensor] = None, 

37 init_param_kwargs: Optional[dict] = None, 

38 ): 

39 """ 

40 Args: 

41 input_size: Number of input dimensions. 

42 hidden_size: Number of neurons with potential in the (single) hidden layer. 

43 output_size: Number of output dimensions. By default, the number of outputs is equal to the number of 

44 hidden neurons. 

45 input_embedding: Optional (custom) [Module][torch.nn.Module] to extract features from the inputs. 

46 This module must transform the inputs such that the dimensionality matches the number of 

47 neurons of the neural field, i.e., `hidden_size`. By default, a [linear layer][torch.nn.Linear] 

48 without biases is used. 

49 output_embedding: Optional (custom) [Module][torch.nn.Module] to compute the outputs from the activations. 

50 This module must map the activations of shape (`hidden_size`,) to the outputs of shape (`output_size`,) 

51 By default, a [linear layer][torch.nn.Linear] without biases is used. 

52 activation_nonlin: Nonlinearity used to compute the activations from the potential levels. 

53 mirrored_conv_weights: If `True`, re-use weights for the second half of the kernel to create a 

54 symmetric convolution kernel. 

55 conv_kernel_size: Size of the kernel for the 1-dim convolution along the potential-based neurons. 

56 conv_padding_mode: Padding mode forwarded to [Conv1d][torch.nn.Conv1d], options are "circular", 

57 "reflect", or "zeros". 

58 conv_out_channels: Number of filter for the 1-dim convolution along the potential-based neurons. 

59 conv_pooling_norm: Norm type of the [torch.nn.LPPool1d][] pooling layer applied after the convolution. 

60 Unlike in typical scenarios, here the pooling is performed over the channel dimension. Thus, varying 

61 `conv_pooling_norm` only has an effect if `conv_out_channels > 1`. 

62 tau_init: Initial value for the shared time constant of the potentials. 

63 tau_learnable: Whether the time constant is a learnable parameter or fixed. 

64 kappa_init: Initial value for the cubic decay, pass 0 to disable the cubic decay. 

65 kappa_learnable: Whether the cubic decay is a learnable parameter or fixed. 

66 potentials_init: Initial for the potentials, i.e., the network's hidden state. 

67 init_param_kwargs: Additional keyword arguments for the policy parameter initialization. 

68 """ 

69 if hidden_size < 2: 

70 raise ValueError("The humber of hidden neurons hidden_size must be at least 2!") 

71 if conv_kernel_size is None: 

72 conv_kernel_size = hidden_size 

73 if conv_padding_mode not in ["circular", "reflect", "zeros"]: 

74 raise ValueError("The conv_padding_mode must be either 'circular', 'reflect', or 'zeros'!") 

75 if not callable(activation_nonlin) and not ( 

76 isinstance(activation_nonlin, Sequence) and all(callable(nonlin) for nonlin in activation_nonlin) 

77 ): 

78 raise ValueError("The activation_nonlin must be a callable or a sequence of callables!") 

79 init_param_kwargs = init_param_kwargs if init_param_kwargs is not None else dict() 

80 

81 # Create the common layers and parameters. 

82 super().__init__( 

83 input_size=input_size, 

84 hidden_size=hidden_size, 

85 output_size=output_size, 

86 activation_nonlin=activation_nonlin, 

87 tau_init=tau_init, 

88 tau_learnable=tau_learnable, 

89 kappa_init=kappa_init, 

90 kappa_learnable=kappa_learnable, 

91 potentials_init=potentials_init, 

92 input_embedding=input_embedding, 

93 output_embedding=output_embedding, 

94 ) 

95 

96 # Create the custom convolution layer that models the interconnection of neurons, i.e., their potentials. 

97 self.mirrored_conv_weights = mirrored_conv_weights 

98 conv1d_class = MirroredConv1d if self.mirrored_conv_weights else nn.Conv1d 

99 self.conv_layer = conv1d_class( 

100 in_channels=1, # treat potentials as a time series of values (convolutions is over the "time" axis) 

101 out_channels=conv_out_channels, 

102 kernel_size=conv_kernel_size, 

103 padding_mode=conv_padding_mode, 

104 padding="same", # to preserve the length od the output sequence 

105 bias=False, 

106 stride=1, 

107 dilation=1, 

108 groups=1, 

109 ) 

110 init_param_(self.conv_layer, **init_param_kwargs) 

111 

112 # Create a pooling layer that reduced all output channels to one. 

113 self.conv_pooling_layer = torch.nn.LPPool1d( 

114 conv_pooling_norm, kernel_size=conv_out_channels, stride=conv_out_channels 

115 ) 

116 

117 # Create the layer that converts the activations of the previous time step into potentials. 

118 self.potentials_to_activations = IndependentNonlinearitiesLayer( 

119 self._hidden_size, activation_nonlin, bias=True, weight=True 

120 ) 

121 

122 def potentials_dot(self, potentials: torch.Tensor, stimuli: torch.Tensor) -> torch.Tensor: 

123 r"""Compute the derivative of the neurons' potentials w.r.t. time. 

124 

125 $/tau /dot{u} = s + h - u + /kappa (h - u)^3, 

126 /quad /text{with} s = s_{int} + s_{ext} = W*o + /int{w(u, v) f(u) dv}$ 

127 with the potentials $u$, the combined stimuli $s$, the resting level $h$, and the cubic decay $\kappa$. 

128 

129 Args: 

130 potentials: Potential values at the current point in time, of shape `(hidden_size,)`. 

131 stimuli: Sum of external and internal stimuli at the current point in time, of shape `(hidden_size,)`. 

132 

133 Returns: 

134 Time derivative of the potentials $\frac{dp}{dt}$, of shape `(hidden_size,)`. 

135 """ 

136 rhs = stimuli + self.resting_level - potentials + self.kappa * torch.pow(self.resting_level - potentials, 3) 

137 return rhs / self.tau 

138 

139 # pylint: disable=duplicate-code 

140 def forward_one_step( 

141 self, inputs: torch.Tensor, hidden: Optional[torch.Tensor] = None 

142 ) -> Tuple[torch.Tensor, torch.Tensor]: 

143 # Get the batch size, and prepare the inputs accordingly. 

144 batch_size = PotentialBased._infer_batch_size(inputs) 

145 inputs = inputs.view(batch_size, self.input_size) 

146 

147 # If given use the hidden tensor, i.e., the potentials of the last step, else initialize them. 

148 potentials = self.init_hidden(batch_size, hidden) 

149 

150 # Don't track the gradient through the hidden state but though the initial potentials. 

151 if hidden is not None: 

152 potentials = potentials.detach() 

153 

154 # Compute the activations: scale the potentials, subtract a bias, and pass them through a nonlinearity. 

155 activations_prev = self.potentials_to_activations(potentials) 

156 

157 # Combine the current inputs to the external simuli. 

158 self._stimuli_external = self.input_embedding(inputs) 

159 

160 # Reshape and convolve the previous activations to the internal stimuli. There is only 1 input channel. 

161 self._stimuli_internal = self.conv_layer(activations_prev.view(batch_size, 1, self._hidden_size)) 

162 

163 if self._stimuli_internal.size(1) > 1: 

164 # In PyTorch, 1-dim pooling is done over the last, i.e., here the potentials' dimension. Instead, we want to 

165 # pool over the channel dimension, and then squeeze it since this has been reduced to 1 by the pooling. 

166 self._stimuli_internal = self.conv_pooling_layer(self._stimuli_internal.permute(0, 2, 1)) 

167 self._stimuli_internal = self._stimuli_internal.squeeze(2) 

168 else: 

169 # No pooling necessary since there was only one output channel for the convolution. 

170 self._stimuli_internal = self._stimuli_internal.squeeze(1) 

171 

172 # Eagerly check the shapes before adding the resting level since the broadcasting could mask errors from 

173 # the later convolution operation. 

174 if self._stimuli_external.shape != self._stimuli_internal.shape: 

175 raise RuntimeError( 

176 f"The shape of the internal and external stimuli do not match! They are {self._stimuli_internal.shape} " 

177 f"and {self._stimuli_external.shape}." 

178 ) 

179 

180 # Potential dynamics forward integration (dt = 1). 

181 potentials = potentials + self.potentials_dot(potentials, self._stimuli_external + self._stimuli_internal) 

182 

183 # Clip the potentials for numerical stabilization. 

184 potentials = potentials.clamp(min=-self._potentials_max, max=self._potentials_max) 

185 

186 # Compute the activations: scale the potentials, subtract a bias, and pass them through a nonlinearity. 

187 activations = self.potentials_to_activations(potentials) 

188 

189 # Compute the outputs from the activations. If there is no output embedding, they are the same thing. 

190 outputs = self.output_embedding(activations) 

191 

192 return outputs, potentials # the current potentials are the hidden state