Inside the network
Open the Portiloop spindle detector and look at every layer: what it computes, why it is there, how big it is, and which line of the configuration controls it. The widgets run the real pre-trained network in your browser, so you can watch it listen to EEG.
In this tutorial you will
- Follow one 0.216 s window of EEG through the five stages of
PortiloopNetwork: convolution, rectification, pooling, recurrent memory and output. - Understand 1D convolutions as a bank of learned FIR filters, and see what the 31 learned first-layer filters of the published model actually respond to.
- Understand how the GRU (a gated recurrent unit) carries about 8.5 s of context across windows.
- Read every key of the configuration dictionary and know what it changes.
- Compute tensor shapes and the exact number of parameters of any architecture, and check them with PyTorch.
The network at a glance
The Portiloop paper describes the design in one paragraph [1]:
Valenchon et al. (2022), section 4“In essence, a sliding window over a few last data points is fed to a Convolutional Neural Network (CNN) whose purpose is to extract relevant features (e.g., frequencies) in this signal fragment. Then, these extracted features are fed to a Recurrent Neural Network (RNN) whose purpose is to keep track of the features extracted in past forward passes (where a “forward pass” is the action of computing an output from the ANN).”
In the code, this is the class PortiloopNetwork in portiloop_software/portiloop_python/ANN/portiloop_detector_training.py. For the published model (configuration returned by get_final_model_config_dict(), checkpoint pareto_search_15_35_v4_0), the data flow is:
Stage 1: the input window
The network never sees a whole recording. Every time it runs, it receives the last window_size samples of the preprocessed signal (low-pass filtered, notch filtered and standardized on line, see tutorial 03). The length is set in seconds by window_size_s and converted to samples with Python's int(), which truncates toward zero:
window_size = int(window_size_s * fe)
nb_out = window_size
With window_size_s = 0.218 and fe = 250: \(0.218 \times 250 = 54.5\), truncated to 54 samples, that is 0.216 s. This is why the paper's supplementary table lists a window of 0.216 s while the configuration says 0.218. At 13 Hz, 0.216 s holds about 2.8 spindle cycles: enough to see an oscillation, far too little to see a whole spindle (0.5 to 2 s). The memory stage (below) solves that.
window_size_s give the same window (0.216, 0.218 and 0.219 all give 54 samples). The Pareto search compares windows in samples for exactly that reason (same_config_dict() in Utils/utils.py uses int(config["window_size_s"] * config["fe"])).Stage 2: convolution, a bank of learned FIR filters
Each convolutional block is a ConvPoolModule. Here is the whole class:
class ConvPoolModule(nn.Module):
def __init__(self,
in_channels,
out_channel,
kernel_conv,
stride_conv,
conv_padding,
dilation_conv,
kernel_pool,
stride_pool,
pool_padding,
dilation_pool,
dropout_p):
super(ConvPoolModule, self).__init__()
self.conv = nn.Conv1d(in_channels=in_channels,
out_channels=out_channel,
kernel_size=kernel_conv,
stride=stride_conv,
padding=conv_padding,
dilation=dilation_conv)
self.pool = nn.MaxPool1d(kernel_size=kernel_pool,
stride=stride_pool,
padding=pool_padding,
dilation=dilation_pool)
self.dropout = nn.Dropout(dropout_p)
def forward(self, input_f):
x, max_value = input_f
x = F.relu(self.conv(x))
x = self.pool(x)
max_temp = torch.max(abs(x))
if max_temp > max_value:
logging.debug(f"max_value = {max_temp}")
max_value = max_temp
return self.dropout(x), max_value
(The max_value bookkeeping only records the largest activation, which the authors used to check that the FPGA's fixed-point number format had enough range. It does not change the output.)
What nn.Conv1d computes
A Conv1d layer with \(C_\text{in}\) input channels, \(C_\text{out}\) output channels and kernel size \(K\) holds \(C_\text{out}\) filters of \(C_\text{in} \times K\) coefficients plus one bias per output channel. With stride \(s\) and dilation \(d\), output channel \(c\) at position \(t\) is
With one input channel this is exactly an FIR filter applied to the EEG (PyTorch slides the kernel without flipping it, which mathematicians call cross-correlation; the magnitude of the frequency response is the same). The first layer of the published model is therefore 31 FIR filters of 7 taps each, learned from data instead of designed by hand. The deeper layers combine the 31 channels of the previous layer (\(31 \times 7 = 217\) coefficients per filter).
How the length shrinks: the out_dim formula
The code uses no padding (conv_padding = 0, pool_padding = 0), so every convolution and every pooling eats \(d(K-1)\) samples. The length after each layer is computed with the standard PyTorch formula, implemented in Utils/utils.py:
def out_dim(window_size, padding, dilation, kernel, stride):
return floor((window_size + 2 * padding - dilation * (kernel - 1) - 1) / stride + 1)
$$L_\text{out} = \left\lfloor \frac{L_\text{in} + 2p - d\,(K-1) - 1}{s} + 1 \right\rfloor$$
PortiloopNetwork.__init__ applies it twice per block (convolution, then pooling):
for _ in range(nb_conv_layers):
nb_out = out_dim(nb_out, conv_padding, dilation_conv, kernel_conv, stride_conv)
nb_out = out_dim(nb_out, pool_padding, dilation_pool, kernel_pool, stride_pool)
output_cnn_size = int(nb_channel * nb_out)
For the published model (\(K = 7\), stride 1, dilation 1) each layer removes 6 samples: 54 → 48 → 42 → 36 → 30 → 24 → 18. So nb_out = 18 and the flattened feature vector has \(31 \times 18 = 558\) numbers. If you ask for too many layers or too large kernels for the window, a length reaches zero or below and PyTorch cannot build the network: the calculator below flags this.
What does the first layer listen to?
Since each first-layer channel is a 7-tap FIR filter, we can compute its frequency response exactly, \(|H(f)| = \left|\sum_{k=0}^{6} w_k\, e^{-i 2\pi f k / f_s}\right|\) with \(f_s = 250\) Hz, from the weights stored in the model file (key first_layer_input1.conv.weight, shape [31, 1, 7]).
Three honest observations, which you can check in the widget:
- No first-layer filter is a sigma band-pass. With 7 taps at 250 Hz a filter spans 28 ms, and its frequency resolution is roughly \(f_s / K = 250 / 7 \approx 36\) Hz. A 7-tap filter physically cannot pass 11 to 16 Hz while rejecting 8 or 20 Hz. The dashed curve shows what a textbook design (Hamming-windowed sinc) produces when asked for an 11 to 16 Hz band-pass with 7 taps: the requested band is so much narrower than the resolution that the result degenerates into a broad low-pass, with its maximum at 0 Hz.
- Most filters are high-pass or “derivative-like”. Their DC gain (sum of coefficients) is close to zero and, for 22 of the 31 channels, the gain at 13.5 Hz is larger than the gain at 1 Hz. In plain terms, the first layer suppresses slow waves and emphasizes faster activity, a sensible first step before looking for 11 to 16 Hz bursts riding on large slow oscillations.
- The raw peak frequencies (33 to 125 Hz) are mostly above the 30 Hz preprocessing low-pass. The network never sees much energy there. With the low-pass included, the effective peaks fall between roughly 16 and 37 Hz, at the top of the passband (two channels end up low-pass). Frequency selectivity for spindles is not built by any single filter: it emerges across the three convolutional blocks and, above all, across time in the GRU.
Stage 3: flatten
After the last block the activity is a 31 × 18 array. torch.flatten(x1, start_dim=1, end_dim=-1) lays it out as one vector of 558 numbers, channel after channel (all 18 samples of channel 0, then channel 1, and so on). Nothing is computed here; the GRU simply needs a vector.
Stage 4: the GRU, a memory across windows
A single window contains under three spindle cycles, yet spindles are defined by a waxing and waning burst lasting half a second or more. The network therefore needs memory. A recurrent layer keeps an internal state vector \(h\) (7 numbers here, hidden_size = 7) and updates it each time a new window arrives. The type used is the Gated Recurrent Unit (GRU) introduced by Cho et al. [2], built with nn.GRU:
if RNN:
self.gru_input1 = nn.GRU(input_size=output_cnn_size,
hidden_size=hidden_size,
num_layers=nb_rnn_layers,
dropout=0,
batch_first=True)
PyTorch documents the update for one time step as follows [3] (\(x_t\) is the 558-number feature vector of the current window, \(h_{t-1}\) the state after the previous window, \(\sigma\) the logistic sigmoid and \(\odot\) element-wise multiplication):
Read the last line as a leaky integrator, like a membrane potential relaxing toward its input. The update gate \(z_t\) (between 0 and 1, one value per unit) sets how much of the old state is kept: \(z \approx 1\) means a long time constant (hold the memory), \(z \approx 0\) means a short one (overwrite with the new evidence \(n_t\)). Unlike a fixed RC circuit, the time constant is recomputed at every step from the current window and the current state, so the unit can, for example, hold “a spindle has been building up” during a burst and reset quickly when the burst ends.
The reset gate \(r_t\) decides how much the past state is allowed to shape the candidate \(n_t\): with \(r \approx 0\) the candidate is computed from the current window alone, as if starting fresh.
The weights are stored stacked: weight_ih_l0 has shape \(3H \times \text{input}\) = 21 × 558 (the three blocks \(W_{ir}, W_{iz}, W_{in}\)), weight_hh_l0 has shape 21 × 7, and each bias vector has 21 entries. Hence the parameter count of GRU layer \(\ell\) with input size \(I_\ell\):
For the published model: \(21 \times (558 + 7) + 42 = 11{,}907\) parameters, almost half of the network, and 11,718 of them are in weight_ih_l0, the matrix that reads the flattened features.
How far back does it remember? seq_len and seq_stride_s
During training, each example is not one window but a sequence of seq_len = 50 windows, consecutive windows starting seq_stride = int(0.17 × 250) = 42 samples (0.168 s) apart. The GRU starts from a zero state, reads the 50 windows in order, and only the output after the last window is compared with the label at the end of that window:
x1 = torch.flatten(x1, start_dim=1, end_dim=-1)
hn1 = None
if self.RNN:
x1 = x1.view(batch_size, sequence_len, -1)
x1, hn1 = self.gru_input1(x1, h1)
...
x1 = x1[:, -1, :]
The configuration records time_in_past = seq_len × seq_stride_s = 50 × 0.17 = 8.5 s (computed in sample_config_dict()). The signal actually covered by one training sequence is \((49 \times 42 + 54)/250 = 8.45\) s. So during training the network learns to use roughly the last 8.5 s of EEG, sampled as 50 snapshots spaced 168 ms apart.
Why spaced 168 ms apart rather than every sample? The paper calls this time dilation: “Our approach enables shallow recurrent neural networks to look further back in time by skipping the redundant information that is inherent to the use of a sliding window as input, while still acting as fast as possible” [1]. On the device, a forward pass takes 20 ms (5 samples) [1], so to produce an output every 20 ms while each memory still sees windows 42 samples apart, the Portiloop keeps several independent hidden states and uses them in turn (“virtual parallelization”, \(\lfloor 42/5 \rfloor = 8\) states in the simulation notebook). This is covered in tutorial 08; the widget below uses a single chain of windows 42 samples apart, which is what one of those 8 virtual networks sees.
Stage 5: from 7 numbers to a probability
The final layer is nn.Linear(7, 1): a weighted sum of the 7 GRU units plus a bias (8 parameters), called the logit. The sigmoid \(\sigma(v) = 1/(1+e^{-v})\) squashes it into the interval 0 to 1, read as the probability that the current window belongs to a spindle. A threshold turns it into a decision; choosing it is the subject of tutorial 06.
Things worth noticing (the numbers below are averages computed for this tutorial over 20 synthetic recordings like this one, ignoring the first 5 s; they describe this didactic signal, not real EEG):
- Feature maps. The mean activation of block 1 is about 1.5 times higher inside spindles (0.13) than outside (0.09). Blocks 2 and 3 are much sparser: only a few channels are active at any time.
- GRU units. Four of the seven units carry most of the spindle information. Unit 4 rises from −0.21 on average outside spindles to +0.53 inside; unit 0 falls from +0.67 to +0.01; unit 3 from −0.10 to −0.57; unit 6 from +0.86 to +0.29. Use the “Highlight” menu to follow one unit at a time.
- Lag and start-up. The output rises a few hundred milliseconds after the spindle onset, because evidence must accumulate over several windows (quantified in tutorial 08). The first two seconds of every recording look abnormal because the online standardization is still converging (tutorial 03).
Optional inputs and the ABLATION flag
PortiloopNetwork can do more than the published model uses. Its forward method takes three inputs and two hidden states:
def forward(self, x1, x2, x3, h1, h2, max_value=np.inf):
# x1 : input 1 : cleaned signal
# x2 : input 2 : envelope
# x3 : power features ratio
# h1 : gru 1 hidden size
# h2 : gru 2 hidden size
# max_value (optional) : print the maximal value reach during inference (used to verify if the FPGA implementation precision is enough)
(batch_size, sequence_len, features) = x1.shape
if ABLATION == 1:
x1 = copy.deepcopy(x2)
elif ABLATION == 2:
x2 = copy.deepcopy(x1)
envelope_input = Truebuilds a second, identical branch (first_layer_input2,seq_input2,gru_input2) that processes the signal envelope. The two branch outputs are concatenated before the final Linear layer, which then has \(2H\) inputs. The envelope is column 2 of the training dataset file; the old MATLAB generation script (matlab/old_matlab/my_full_dataset_generation.m) squares a band-passed, standardized signal and smooths it with an exponential moving average. This doubles the convolutional and recurrent parameters.power_features_input = Trueappends one extra number to the final Linear layer: column 3 of the dataset file, a spectral ratio computed bymatlab/old_matlab/compute_ratio.mas the mean FFT amplitude in 9 to 16 Hz divided by the mean in 2 to 8 Hz, over the last 125 samples (0.5 s). It adds a single weight.ABLATIONis a module-level variable, set from the command line with--ablationwhen the training script is run directly (0 by default, and always 0 when the module is imported). With 1, the signal branch receives a copy of the envelope; with 2, the envelope branch receives a copy of the signal. The architecture (and so the model capacity) stays the same; only the information changes.
The paper used exactly this ablation to drop the envelope [1]: “to keep the same architecture (and thus the same model capacity), we replace one of the two inputs by a copy of the other. [...] We find that the envelope input can be removed: the model in which we replace the envelope with a copy of the cleaned signal (5) has the same performance as the original model (3), and even performs marginally better on phase 2.” The 2-input model of the paper (supplementary Appendix G: 4 blocks of 26 channels, pooling kernel 9, two stacked GRU layers of 7 units per branch) is one of the presets of the calculator below.
Finally, RNN = False replaces each GRU with fully connected layers (FcModule: Linear, ReLU, dropout), nb_rnn_layers of them, and the network then has no memory at all. In that case the training sequences must have length 1 (the Pareto search sets seq_len = 1 when RNN is off), otherwise the number of outputs no longer matches the number of labels.
Design your own: the architecture calculator
Every quantity in this tutorial follows from a handful of configuration keys. The calculator applies the same formulas as PortiloopNetwork.__init__ (including Python's truncation of window_size_s × fe) and counts parameters layer by layer:
- Conv1d: \(C_\text{out} \cdot C_\text{in} \cdot K + C_\text{out}\) (weights plus one bias per output channel); MaxPool, ReLU, flatten and dropout have no parameters.
- GRU layer \(\ell\): \(3H(I_\ell + H) + 6H\). Fully connected alternative (
RNNoff): \(I \cdot H + H\) for the firstFcModule, \(H^2 + H\) for each additional one. - Final Linear: \((H \cdot n_\text{branches} + [\text{power features}]) + 1\).
- Everything in the convolutional and recurrent part is duplicated when
envelope_inputis on.
PortiloopNetwork from the repository and summing p.numel() over its parameters, for five configurations: the published model (25,679 parameters, nb_out 18); the paper's 2-input model (32,213, nb_out 2); RNN off with 2 fully connected layers of 12, 16 channels, kernels 5 and 3, 2 blocks (9,637, nb_out 42); strides 2, conv dilation 2, 0.4 s window, 11 channels, 2 GRU layers of 20 (6,523, nb_out 3); and the published model with both optional inputs and hidden_size 10 (61,750). All match.Count parameters yourself in Python
- Open a terminal at the repository root with the environment from tutorial 02 activated, and save this as
count_params.py:from portiloop_software.portiloop_python.ANN.portiloop_detector_training import PortiloopNetwork, get_final_model_config_dict cfg = get_final_model_config_dict() net = PortiloopNetwork(cfg) for name, p in net.named_parameters(): print(f"{name:32s} {str(tuple(p.shape)):10s} {p.numel():6d}") print("total", sum(p.numel() for p in net.parameters())) cfg.update(nb_channel=16, hidden_size=12) # try your own architecture print("smaller variant:", sum(p.numel() for p in PortiloopNetwork(cfg).parameters())) - Run it:
Expected output:python3 count_params.py
The names are the keys of the checkpoint'sfirst_layer_input1.conv.weight (31, 1, 7) 217 first_layer_input1.conv.bias (31,) 31 seq_input1.0.conv.weight (31, 31, 7) 6727 seq_input1.0.conv.bias (31,) 31 seq_input1.1.conv.weight (31, 31, 7) 6727 seq_input1.1.conv.bias (31,) 31 gru_input1.weight_ih_l0 (21, 558) 11718 gru_input1.weight_hh_l0 (21, 7) 147 gru_input1.bias_ih_l0 (21,) 21 gru_input1.bias_hh_l0 (21,) 21 fc.weight (1, 7) 7 fc.bias (1,) 1 total 25679 smaller variant: 14629model_state_dict, and the same keys you will find in exported model files (tutorial 10). Set the calculator to 16 channels and hidden size 12 to see the same 14,629.
ModuleNotFoundError: No module named 'sklearn'or'wandb': the training module imports both at the top, even to build a network. Install the requirements (pip install -e ., tutorial 02).RuntimeErrormentioning a size that is zero or negative, when building or running a custom network: a length in the convolutional stack dropped below 1. Check it in the calculator.Error(s) in loading state_dict ... size mismatch for gru_input1.weight_ih_l0when loading a checkpoint: your configuration does not match the one the checkpoint was trained with (oftenwindow_size_s,kernel_poolornb_conv_layers, which changenb_outand thus the GRU input size).
Every configuration key
A model is fully described by a Python dictionary. The table lists every key of get_final_model_config_dict(), which keys PortiloopNetwork and run() read, and what changing them does. “Published” is the value for the pre-trained model. How to train with your own values is explained in tutorial 05.
max_duration, estimator_size_memory, the W&B restore step, the default experiment_name) were fixed in November 2026: if your clone is older, run git pull.| Key | Type | Published | Read by | Meaning and effect |
|---|---|---|---|---|
Architecture (read by PortiloopNetwork) | ||||
fe | int | 250 | network, run | Sampling frequency in Hz. Converts all _s durations to samples. The Portiloop samples at 250 Hz; data at other rates must be resampled (tutorial 09). |
window_ | float | 0.218 | network, run | Input window in seconds; int(window_size_s * fe) = 54 samples. Longer windows see more cycles but add delay before a spindle fills the window, and increase nb_out, hence the GRU input size and the parameter count. |
nb_ | int | 3 | network | Number of ConvPoolModule blocks. Each one removes samples and adds \(C^2K + C\) parameters (the first adds \(CK + C\)). |
nb_ | int | 31 | network | Filters per convolutional layer (same for all layers). Parameters grow roughly with its square. |
kernel_ | int | 7 | network | Taps per filter (28 ms at 250 Hz). Longer kernels give finer frequency resolution but shorten the output. |
kernel_ | int | 7 | network | Max-pooling width. No parameters, but it shortens the signal by kernel_pool − 1 samples per block (stride 1). The paper's supplementary Table II lists 1 for this hyperparameter; the published checkpoint can only be loaded with 7 (its GRU expects 31 × 18 = 558 inputs), so the table entry appears to be a typo. |
stride_, stride_ | int | 1, 1 | network | Step between successive filter positions. A stride of 2 halves the output length (downsampling). Fixed to 1 in the Pareto search. |
dilation_, dilation_ | int | 1, 1 | network | Spacing between taps: dilation 2 makes a 7-tap kernel span 13 samples. Fixed to 1 in the Pareto search. |
RNN | bool | True | network, run | GRU memory (True) or memory-less fully connected layers (False). |
hidden_ | int | 7 | network, run | Number of GRU units \(H\) (or width of the FC layers). Size of the state carried between windows. |
nb_ | int | 1 | network, run | Stacked GRU layers (or FC layers). Each extra GRU layer adds \(6H^2 + 6H\) parameters. |
envelope_ | bool | False | network, run | Adds the second branch fed with the envelope (see above). Doubles the convolutional and recurrent parameters. |
power_ | bool | False | network, run | Appends the 9 to 16 Hz / 2 to 8 Hz power ratio to the last layer (+1 parameter). |
dropout | float | 0.5 | network | Probability of zeroing each activation during training only (a regularizer, see tutorial 05). Applied after blocks 2 and later and inside FcModule; the GRU is built with dropout=0. |
first_ | bool | False | network | Whether dropout is also applied after block 1. |
classification | bool | True | network, run | True: binary labels and binary cross-entropy loss. False: regression of the label value with mean squared error. Stored by the network but only used by run(). |
Sequences (read by run) | ||||
seq_ | int | 50 | run | Windows per training sequence (steps of back-propagation through time). |
seq_ | float | 0.170 | run | Time between consecutive windows of a sequence, int(0.17 * 250) = 42 samples (the paper's “time dilation” of 168 ms). Also sets how many interleaved hidden states are used in real time. |
Optimization (read by run; tutorial 05) | ||||
lr_ | float | 0.0005 | run | Learning rate of the AdamW optimizer. |
adam_ | float | 0.01 | run | AdamW weight decay (pulls weights toward zero). |
batch_ | int | 256 | run | Sequences per gradient step. |
nb_ | int | 1000 | run | Batches drawn per epoch (sampling is random with replacement, so an “epoch” is a fixed number of batches, not a pass through the data). |
nb_ | int | 150 | run | Maximum number of epochs. |
nb_ | int | 100 | run | Early-stopping patience: stop after this many epochs without improvement of the smoothed validation loss. |
early_ | float | 0.1 | run | Exponential moving average factor applied to the validation loss before the early-stopping test. |
max_ | int (s) | 257400 | run | Wall-clock limit for the whole run (71.5 h): training stops at the end of the epoch during which it is exceeded. (In clones older than November 2026 the timer was restarted every epoch, so the limit never triggered; git pull to get the fix.) |
distribution_ | int | 0 | run | 0: training windows are drawn 50 % spindle, 50 % non-spindle (class balancing by oversampling). 1: drawn with the natural proportions (required for regression). |
reg_ | str | 'none' | run | Regression only: 'lds' (label distribution smoothing) or 'sr' (surprise reweighting) reweight rare label values. |
split_ | int | 0 | run | Random seed (random_state) of the subject-wise train/validation/test split. |
validation_ | int | 1 | run | During validation, evaluate every k-th window offset (1 = all). Larger values speed up validation. |
device_, device_ | str | 'cuda' | run | PyTorch devices. If either starts with cuda, run() asserts that a GPU is available. |
| Bookkeeping | ||||
experiment_ | str | 'sanity_ | run, loaders | Name of the W&B run and of the checkpoint file. get_final_model_config_dict(index) returns sanity_check_final_model_<index>, and get_trained_model() falls back to the shipped checkpoint pareto_search_15_35_v4_<index> when that file is missing. From the command line, --experiment_name overrides it. |
device_ | str | 'cpu' | loaders | Device used by get_trained_model() and run_offline_unlabelled(). |
nb_ | int | 18 | nobody | Informational copy of the length after the last block; the network recomputes it. |
time_ | float (s) | 8.5 | nobody | Informational: seq_len * seq_stride_s. |
estimator_ | int | 188006400 (stale) | written by run | Rough memory estimate logged to W&B: number of parameters × window × seq_len × batch_size × branches, recomputed at every run (17,749,324,800 for the published model). The value stored in the dictionary was computed by an older version of run() that summed the first dimension of each tensor instead of the number of parameters. |
Exercises
Where do the parameters live?
Using only the formulas on this page (no calculator), compute how many parameters the published network has in its convolutional part, its GRU and its output layer. Which single tensor is the largest, and why does reducing window_size_s shrink it?
Answer
Convolutions: \(31 \cdot 1 \cdot 7 + 31 = 248\), then twice \(31 \cdot 31 \cdot 7 + 31 = 6{,}758\), total 13,764. GRU: \(21 \cdot (558 + 7) + 42 = 11{,}907\). Output: \(7 + 1 = 8\). Total 25,679. The largest tensor is gru_input1.weight_ih_l0 (21 × 558 = 11,718): its width is nb_channel × nb_out, and nb_out is the window length minus 36 samples. A 0.18 s window (45 samples) gives nb_out 9, so this tensor halves to 5,859.
The smallest window that still works
Keeping 3 blocks with kernel 7 for both convolution and pooling, what is the shortest window_size_s that produces a valid network? What happens with 5 blocks and a 0.218 s window?
Answer
Each block removes 12 samples, so 3 blocks remove 36 and the window needs at least 37 samples for nb_out ≥ 1: int(window_size_s × 250) ≥ 37, that is window_size_s ≥ 0.148. With 5 blocks, 60 samples are removed from 54: the fifth block would need a negative length, so PyTorch cannot build the GRU (the calculator turns red; the Pareto search would discard and resample this configuration).
Read a GRU unit
In “Look inside the real network”, highlight unit 4, then unit 0. Click a moment inside a spindle and a moment outside. Using the bar chart of contributions, decide whether each unit votes for or against “spindle” in each case. Why can the same unit vote in different directions at different times?
Answer
Each bar is \(w_j h_j\), the unit's value times its output weight. The output weights of the published model are all negative except unit 4 (fc.weight ≈ [−1.13, −1.06, −1.09, −1.17, +1.08, −1.13, −1.12], units numbered from 0). Unit 4 becomes positive inside spindles, so its bar becomes positive and pushes the logit up. Unit 0 has a negative weight and is strongly positive outside spindles, so its bar is negative there (a vote against); inside spindles it falls toward zero and stops voting against. Because \(h_j\) can change sign (tanh range −1 to +1), the same unit argues for or against a spindle depending on its state; the decision is the sum of the seven bars plus the bias (−0.30), passed through the sigmoid.
References
- Valenchon N, Bouteiller Y, Jourde HR, L'Heureux X, Sobral M, Coffey EBJ, Beltrame G (2022). The Portiloop: A deep learning-based open science tool for closed-loop brain stimulation. PLOS ONE 17(8): e0270696. doi:10.1371/journal.pone.0270696. Quotes from sections 4 and 6 and from S1 File (Appendix G, Appendix K).
- Cho K, van Merriënboer B, Gulcehre C, Bahdanau D, Bougares F, Schwenk H, Bengio Y (2014). Learning Phrase Representations using RNN Encoder-Decoder for Statistical Machine Translation. Proceedings of EMNLP 2014, 1724 to 1734. doi:10.3115/v1/D14-1179 (introduces the gated recurrent unit).
- PyTorch documentation,
torch.nn.GRU(equations and weight layout),torch.nn.Conv1dandtorch.nn.MaxPool1d(output length formula). - Chang S, Zhang Y, Han W, Yu M, Guo X, Tan W, Cui X, Witbrock M, Hasegawa-Johnson M, Huang TS (2017). Dilated recurrent neural networks. arXiv:1710.02224 (the time-dilation idea cited by the Portiloop paper).