Tutorial 04 · Understanding the pipeline

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.

Time
45 to 60 minutes
Level
Intermediate, no ML background assumed
You need
Tutorial 03 (what the input looks like)
Runs in browser
Yes; the Python snippets need Tutorial 02

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:

Data flow of the published Portiloop network, from a 54-sample window to a spindle probability EEG window 1 × 54 Block 1 Conv1d k=7 → ReLU → MaxPool k=7 31 × 48 → 31 × 42 Block 2 same, 31 → 31 31 × 36 → 31 × 30 Block 3 same, 31 → 31 31 × 24 → 31 × 18 Flatten 558 GRU 558 → 7 memory h state kept for the next window Linear + sigmoid 7 → 1, P(spindle) feature extraction (what is in this window?) integration over time and decision
The published architecture. Shapes are “channels × samples” (PyTorch's channel-first convention, batch dimension omitted). The paper's Fig 5 shows the same architecture in PyTorch nomenclature.
For neuroscientists: what is a “parameter”?A parameter (or weight) is one number that training adjusts, like one coefficient of a filter. The published network has 25,679 of them. For comparison, a 21-tap FIR filter like the Portiloop's preprocessing low-pass (tutorial 03) has 21. Training (tutorial 05) is the procedure that tunes all 25,679 numbers at once so that the output matches expert spindle annotations.

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.

TipBecause of truncation, several values of 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

$$y_c[t] \;=\; b_c \;+\; \sum_{c'=1}^{C_\text{in}} \sum_{k=0}^{K-1} w_{c,c',k}\; x_{c'}[\,s\,t + d\,k\,].$$

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).

For neuroscientists: a familiar pipeline, learned end to endA classical spindle detector band-passes the EEG in the sigma band (11 to 16 Hz), rectifies or squares it, smooths it into an envelope and applies a threshold. Each block of the network has the same three ingredients: filter (Conv1d), rectify (ReLU, \(\max(0,x)\), which is half-wave rectification), smooth/peak-pick (MaxPool1d keeps the largest value in each run of 7 samples, a crude envelope follower). The difference is that nothing is fixed in advance: training chooses the filters, and stacking three blocks lets later filters combine the outputs of earlier ones.

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]).

The 31 learned first-layer filters

Each card shows one filter: its 7 coefficients (stems) and its magnitude response from 0 to 125 Hz (curve), with the sigma band (11 to 16 Hz) shaded. Cards are sorted by the frequency of maximal gain. What to try: click a card to see its response in detail and what it does to a synthetic EEG segment with a spindle; tick “include the preprocessing low-pass” to see the response the network effectively has after the Portiloop's 21-tap FIR filter.

Selected channel
…
Peak gain at
…
Gain 13.5 Hz ÷ 1 Hz
…
DC gain (sum of taps)
…
Loading model…

Three honest observations, which you can check in the widget:

  1. 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.
  2. 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.
  3. 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.
Do not over-interpret single filtersMany different sets of weights can give the same overall behaviour, and a network trained again from scratch (tutorial 05) will learn different first-layer filters. Read these plots as “what kind of operations are being done”, not as a discovery about spindle physiology.

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):

$$\begin{aligned} r_t &= \sigma\!\left(W_{ir} x_t + b_{ir} + W_{hr} h_{t-1} + b_{hr}\right) &&\text{reset gate}\\ z_t &= \sigma\!\left(W_{iz} x_t + b_{iz} + W_{hz} h_{t-1} + b_{hz}\right) &&\text{update gate}\\ n_t &= \tanh\!\left(W_{in} x_t + b_{in} + r_t \odot \left(W_{hn} h_{t-1} + b_{hn}\right)\right) &&\text{candidate state}\\ h_t &= (1 - z_t) \odot n_t + z_t \odot h_{t-1} &&\text{new state} \end{aligned}$$
For neuroscientists: gates as adjustable time constants

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\):

$$N_\text{GRU}(\ell) = 3H\,(I_\ell + H) + 6H, \qquad I_0 = C \cdot L_\text{out},\quad I_{\ell>0} = H.$$

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.

NoteIn training the memory never spans more than 50 steps, but on the device the hidden state is carried forward indefinitely. The authors write that they “believe that the main role currently played by the RNN is to accumulate information regarding whether the last few windows were spindles or not, rather than actually predicting the future” [1].

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.

Look inside the real network

A 30 s synthetic NREM recording is preprocessed exactly as on the Portiloop and fed to the pre-trained network, one window every 42 samples. What to try: click anywhere on the top trace (or press Play) to choose a moment; watch the 54-sample input window, the three stacks of feature maps (brighter means larger activation), the 7 GRU units over time, and how each unit pushes the output up or down. Compare a moment inside a green spindle with one during a slow wave.

Time
…
Logit
…
P(spindle)
…
Ground truth
…
Loading model…

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):

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)

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:

Architecture calculator

What to try: start from the published model (25,679 parameters, nb_out 18), then add a fourth convolutional block, or double hidden_size, and see which part of the parameter budget grows. Push kernel_conv and nb_conv_layers up until the window is “used up”. Turn on envelope_input to see the 2-input model double in size. The shaded badge tells you whether the Pareto search of tutorial 07 would keep this architecture (1,000 to 80,000 parameters).

Input
Convolutional blocks
Strides and dilations
Memory and output
Window
…
nb_out
…
Parameters
…
Multiply-adds / pass
…
time_in_past
…

“Multiply-adds per pass” counts the products in Conv1d, GRU and Linear layers for one window (it ignores ReLU, pooling and sigmoids). It is a rough proxy for compute time; note how the convolutions dominate compute while the GRU dominates the parameter count. “time_in_past” is the code's seq_len × seq_stride_s; the span in brackets is the signal actually covered by one training sequence.

Verified against PyTorchThe counts above were cross-checked by instantiating 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

  1. 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()))
  2. Run it:
    python3 count_params.py
    Expected output:
    first_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: 14629
    The names are the keys of the checkpoint's model_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.
Troubleshooting
  • 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).
  • RuntimeError mentioning 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_l0 when loading a checkpoint: your configuration does not match the one the checkpoint was trained with (often window_size_s, kernel_pool or nb_conv_layers, which change nb_out and 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.

NoteThe descriptions below match the current code in the repository. Several training-loop details (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.
KeyTypePublishedRead byMeaning and effect
Architecture (read by PortiloopNetwork)
feint250network, runSampling 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_size_sfloat0.218network, runInput 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_conv_layersint3networkNumber of ConvPoolModule blocks. Each one removes samples and adds \(C^2K + C\) parameters (the first adds \(CK + C\)).
nb_channelint31networkFilters per convolutional layer (same for all layers). Parameters grow roughly with its square.
kernel_convint7networkTaps per filter (28 ms at 250 Hz). Longer kernels give finer frequency resolution but shorten the output.
kernel_poolint7networkMax-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_conv, stride_poolint1, 1networkStep between successive filter positions. A stride of 2 halves the output length (downsampling). Fixed to 1 in the Pareto search.
dilation_conv, dilation_poolint1, 1networkSpacing between taps: dilation 2 makes a 7-tap kernel span 13 samples. Fixed to 1 in the Pareto search.
RNNboolTruenetwork, runGRU memory (True) or memory-less fully connected layers (False).
hidden_sizeint7network, runNumber of GRU units \(H\) (or width of the FC layers). Size of the state carried between windows.
nb_rnn_layersint1network, runStacked GRU layers (or FC layers). Each extra GRU layer adds \(6H^2 + 6H\) parameters.
envelope_inputboolFalsenetwork, runAdds the second branch fed with the envelope (see above). Doubles the convolutional and recurrent parameters.
power_features_inputboolFalsenetwork, runAppends the 9 to 16 Hz / 2 to 8 Hz power ratio to the last layer (+1 parameter).
dropoutfloat0.5networkProbability 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_layer_dropoutboolFalsenetworkWhether dropout is also applied after block 1.
classificationboolTruenetwork, runTrue: 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_lenint50runWindows per training sequence (steps of back-propagation through time).
seq_stride_sfloat0.170runTime 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_adamfloat0.0005runLearning rate of the AdamW optimizer.
adam_wfloat0.01runAdamW weight decay (pulls weights toward zero).
batch_sizeint256runSequences per gradient step.
nb_batch_per_epochint1000runBatches drawn per epoch (sampling is random with replacement, so an “epoch” is a fixed number of batches, not a pass through the data).
nb_epoch_maxint150runMaximum number of epochs.
nb_epoch_early_stopping_stopint100runEarly-stopping patience: stop after this many epochs without improvement of the smoothed validation loss.
early_stopping_smoothing_factorfloat0.1runExponential moving average factor applied to the validation loss before the early-stopping test.
max_durationint (s)257400runWall-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_modeint0run0: training windows are drawn 50 % spindle, 50 % non-spindle (class balancing by oversampling). 1: drawn with the natural proportions (required for regression).
reg_balancingstr'none'runRegression only: 'lds' (label distribution smoothing) or 'sr' (surprise reweighting) reweight rare label values.
split_idxint0runRandom seed (random_state) of the subject-wise train/validation/test split.
validation_network_strideint1runDuring validation, evaluate every k-th window offset (1 = all). Larger values speed up validation.
device_train, device_valstr'cuda'runPyTorch devices. If either starts with cuda, run() asserts that a GPU is available.
Bookkeeping
experiment_namestr'sanity_check_final_model_0' (for index 0)run, loadersName 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_inferencestr'cpu'loadersDevice used by get_trained_model() and run_offline_unlabelled().
nb_outint18nobodyInformational copy of the length after the last block; the network recomputes it.
time_in_pastfloat (s)8.5nobodyInformational: seq_len * seq_stride_s.
estimator_size_memoryint188006400 (stale)written by runRough 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

  1. 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).
  2. 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).
  3. PyTorch documentation, torch.nn.GRU (equations and weight layout), torch.nn.Conv1d and torch.nn.MaxPool1d (output length formula).
  4. 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).