Tutorial 08 · Using your model

Real-time simulation and stimulation

A detector that scores well offline is not yet a closed-loop device. In this tutorial you stream EEG through the real Portiloop network sample by sample, see why it keeps eight hidden states instead of one, add up every millisecond between a spindle's onset and the sound reaching the sleeper, and run the repository's simulation notebook with your own trained model.

Time
45 to 60 minutes
Level
Intermediate
You need
03 and 04; 05 for your own model
Runs in browser
Widgets yes; the notebook needs the dataset of 02

In this tutorial you will

  • Follow one EEG sample from the electrode to a stimulation decision, and name every source of delay
  • Understand the eight interleaved hidden states (the "virtual parallel networks" of the paper) and why they are needed
  • Watch a live closed loop: the published network, the Portiloop filters and the stimulation rule, running in your browser
  • Read and modify simulate_Portiloop_1_input_classification.ipynb to evaluate your own trained model as a stimulation device
  • Interpret the notebook's stimulation statistics and its Captum attribution plots

From offline scores to a closed loop

In tutorial 06 the network was judged sample by sample: is this 4 ms point inside a spindle or not? A stimulation experiment asks a different question: did one sound arrive while the spindle was still going on, and only one? The Portiloop paper makes this distinction explicitly [1]:

Valenchon et al. (2022), section 6.1"The performance measured in the previous section is not entirely representative of the performance on the final task. So far, we have only measured the capability of the model to annotate each data point of the signal individually. Yet, we want the ability to send one single stimulation per sleep spindle."

Between the brain and the speaker, the signal goes through a chain of stages. Coloured edges: purple for the acquisition and output hardware, blue for signal processing, orange for the network:

  1. Electrodes and ADCone sample every 4 ms (250 Hz)
  2. FIR lowpass, 21 taps40 ms group delay
  3. 60 Hz notchIIR, one biquad
  4. Online standardizationrunning mean and variance
  5. Window of 54 samples0.216 s of signal
  6. Network forward pass20 ms on the FPGA [1]
  7. Threshold and refractory ruleone stimulus per spindle
  8. Sound4 ms with a basic sound controller [1]

The filters were covered in tutorial 03 and the network in tutorial 04. Here we focus on what happens when these pieces run continuously, against the clock.

For neuroscientistsThink of the device as a participant in a reaction-time task. The "stimulus" is the spindle onset, the "response" is the sound. Part of the reaction time is perceptual (the network must see enough cycles to be confident), part is motor (the sound hardware), and part is conduction (the filters). Just as in psychophysics, you cannot remove the perceptual part without increasing errors: a lower detection threshold answers faster but also "responds" to things that are not spindles. The paper notes that each spindle cycle is "only ~60 ms long and the entire spindle is between 0.5 and 2.5 s" [1], so every few tens of milliseconds matter.

The sample stream and the 20 ms rhythm

The Portiloop samples the EEG at 250 Hz, so a new value arrives every 4 ms. The network cannot run that often: the paper reports "We measure the execution time of this architecture to be 20 ms per forward pass on the Portiloop" [1] (FPGA version). The simulation notebook encodes this as a number of samples:

FPGA_NN_EXEC_TIME = 5  # equivalent to 20 ms
ERROR_FPGA_EXEC_TIME = 0  # to be sure there is no overlap

Five samples at 4 ms each is 20 ms. ERROR_FPGA_EXEC_TIME is a safety margin (in samples) that you can add if your hardware's inference time fluctuates; it is 0 in the notebook. So at most one window can be evaluated every 5 samples. Each window is the last 54 standardized samples (int(0.218 * 250) = 54, about 0.22 s), ending at the newest sample. Consecutive windows therefore overlap by 49 samples: the network looks at almost the same stretch of signal, shifted by 20 ms.

Why eight hidden states?

The network ends with a GRU, a recurrent layer whose 7-number hidden state carries a memory of previous windows (tutorial 04). During training, the GRU was not fed overlapping windows 20 ms apart. It was fed sequences of 50 windows spaced by seq_stride_s = 0.17 s, that is int(0.17 * 250) = 42 samples or 168 ms. The paper calls this spacing time dilation: "the time-dilation (set to 168 ms by PMBO)" [1]. A sequence of 50 such windows covers about 8.4 s of EEG, which is what lets the network use context well beyond one window (the config entry 'time_in_past': 8.5).

The hidden state has therefore learned dynamics that assume 168 ms between updates. If we fed it a window every 20 ms, its memory would evolve about eight times too fast, a regime it never saw. The solution is to keep several independent copies of the hidden state and use them in turn (round robin):

$$n_\text{parallel} = \left\lfloor \frac{\text{seq\_stride}}{\text{FPGA\_NN\_EXEC\_TIME} + \text{ERROR\_FPGA\_EXEC\_TIME}} \right\rfloor = \left\lfloor \frac{42}{5} \right\rfloor = 8$$
    nb_parallel_runs = seq_stride // (FPGA_NN_EXEC_TIME + ERROR_FPGA_EXEC_TIME)
    print(f"seq_stride: {seq_stride}")
    print(f"FPGA_NN_EXEC_TIME + ERROR_FPGA_EXEC_TIME: {FPGA_NN_EXEC_TIME + ERROR_FPGA_EXEC_TIME}")
    print(f"nb_parallel_runs: {nb_parallel_runs}")
    stride_between_runs = seq_stride // nb_parallel_runs

Hidden state 1 sees windows ending at samples 53, 95, 137, ... (42 apart); state 2 sees the windows 5 samples later; and so on. Each state lives in the 168 ms world it was trained in, yet together they produce a fresh output about every 20 ms. The paper calls these "decoupled virtual parallel networks" [1] and shows they matter: when the time dilation is shrunk to 20 ms so that a single state must be used, "the highly deteriorated results illustrate the importance of time-dilation" [1].

For neuroscientistsPicture eight observers watching the same EEG monitor, each glancing at it once every 168 ms, with their glances staggered by 20 ms. Each observer keeps their own running impression of the last few seconds. Any single observer is slow, but at every moment one of them has just looked. Nothing is shared between observers, which is why the paper calls them "decoupled".

Three ways to fit 8 windows into 42 samples

Eight windows 5 samples apart span 40 samples, not 42, so the two extra samples must go somewhere. The code in the Portiloop ecosystem does this in three slightly different ways; all keep 8 hidden states:

WhereGaps between consecutive windows (samples)Spacing seen by each hidden state
Simulation notebook (ValidationSampler with network_stride = stride_between_runs = 5)5, 5, 5, 5, 5, 5, 5, 7exactly 42
Device software, portiloop-software (stride_counters)5, 5, 5, 6, 5, 5, 5, 6exactly 42
This website, PL.PortiloopModel.prototype.runStream5, 5, 5, 5, 5, 5, 5, 540 (an approximation)

The device code computes its gaps from the same two numbers:

        num_models_parallel = 8
        window_size = 54
        seq_stride = 42
...
        self.stride_counters = [np.floor((self.seq_stride / self.num_models_parallel) * (i + 1)) for i in range(self.num_models_parallel)]
        for idx in reversed(range(1, len(self.stride_counters))):
            self.stride_counters[idx] -= self.stride_counters[idx-1]
        assert sum(self.stride_counters) == self.seq_stride, f"{self.stride_counters} does not sum to {self.seq_stride}"

In the notebook, the extra 2 samples appear as the adder = 2 applied every 8th output (if (i+1)%nb_samp ==0) when outputs are mapped back to sample indices. The live oscilloscope below lets you switch between the three schedules.

Interleaved hidden states

Each coloured bar is one 54-sample window; its row is the hidden state that processes it. The vertical line is "now", in slow motion (about 25 times slower than real time). The arcs show the spacing seen by the most recent state. What to try: set the network stride to 7 (6 states, every schedule agrees); set it to 4 (10 states, but 16 ms is shorter than the 20 ms forward pass); set the sequence stride to 5 to reproduce the paper's "no time dilation" ablation (a single state).

Hidden states
8
Gaps (samples)
…
Spacing per state
…
Outputs per second
…

Latency: where the milliseconds go

The paper measured each delay on the FPGA version of the Portiloop and summarized them in its Table 2 (reproduced here; "~" marks the variable part):

Table 2 of Valenchon et al. (2022) [1], "Delays measured in the Portiloop (sleep spindle configuration)".
ComponentHardware delaySoftware delay
Electrodes + ADC--
Filters-40 ms
ANN20 ms~250 (± 100) ms
Stimulus4 ms-
Total: ~314 ms24 ms290 (± 100) ms

The constant part is exactly the notebook's constant_delay_s:

seq_stride = int(config_dict["seq_stride_s"]*config_dict["fe"])
network_stride = 5
nb_samp = 8
window_size = int(config_dict["window_size_s"]*config_dict["fe"])
max_time_stimulate_s = 0.25
constant_delay_s = 0.064

print(f"seq_stride: {seq_stride}")

constant_delay_s = 0.064 is 40 + 20 + 4 ms. It is added in the notebook because the notebook's dataset was filtered offline with the FIR delay already compensated (tutorial 03), so the filter delay has to be put back by hand. max_time_stimulate_s = 0.25 is the tolerance used to call a stimulation "accurate" (see below). nb_samp = 8 repeats the number of hidden states for the bookkeeping loops.

Latency budget calculator

A calculator with values you choose. The defaults are the measurements of Table 2 above. The bar shows when the stimulus arrives relative to a spindle that starts at time 0. What to try: shorten the spindle to 0.5 s (the shortest spindles in the paper's description); then reduce the detection delay and see how much of the spindle you gain.

Delays
Spindle
Total delay
…
Spindle left
…
Fraction left
…
Cycles left
…

The decision rule: threshold and refractory period

The network outputs a number between 0 and 1 every ~20 ms. Turning it into stimuli needs two choices.

A threshold. An output above the threshold means "spindle". The notebook uses THRESHOLD = 0.5 (from threshold_list = {'p1': 0.2, 'p2': 0.35, 'full': 0.5} with PHASE = 'full'). The device software uses a default of 0.75 ("threshold": 0.75 in DEFAULT_CONFIG_DICT, adjustable in its interface) and counts an output equal to the threshold as a detection (>=, where the notebook uses >). The paper found that, counting stimulations rather than samples, "the best such trade-off is attained at a threshold of 0.84 with our model, yielding a precision and a recall of 0.71 both", at the price of "slightly shifting the stimulation delay distribution to the right" [1].

A refractory rule. The output often flickers around the threshold at the beginning and end of a spindle, and the eight hidden states do not agree perfectly. Without a rule, one spindle would trigger a burst of sounds. The paper describes the rule [1]:

Valenchon et al. (2022), section 5"A stimulus is sent upon initial spindle detection. To avoid multiple stimuli of the same spindle, the subsequent stimulation may only occur 400 ms following the end of the spindle. If a spindle is detected again within this duration the timer is reset, and we consider it as being part of the previous spindle."

In the notebook it is implemented with two counters in samples (100 samples = 400 ms):

        for i in range(len(output_test)):
            adder = 0
            label = output_test[i]
            if (i+1)%nb_samp ==0:
                adder = 2
            if label > THRESHOLD and wait_stim == 0 and not in_spindle:
                spindle_list_stimulate.append(cur_idx)
                wait_stim = 100
                in_spindle = True
            if in_spindle and label > THRESHOLD:
                wait_in_spindle = 100#42
            if label <= THRESHOLD and wait_in_spindle <= 0:
                in_spindle = False
            cur_idx += network_stride+adder
            wait_stim -=network_stride+adder
            wait_in_spindle -=network_stride+adder

Read it as a small state machine: a stimulation is sent when the output crosses the threshold while we are not "in a spindle"; we stay "in the spindle" as long as above-threshold outputs keep coming less than 400 ms apart. The device software implements the same idea with a wall clock (self.wait_t = 0.4 # 400 ms and if ts - self.last_detected_ts > self.wait_t: in SleepSpindleRealTimeStimulator). The 400 ms value is a design choice, not a property of the network: you can change it for your experiment, for example to avoid stimulating spindle trains.

For neuroscientistsThis is a refractory period with a twist: it is measured from the last time the detector said "spindle", not from the last stimulus. A long spindle therefore receives one sound, however long it lasts, and the detector re-arms only after 400 ms of "no spindle". It plays the same role as the dead time of a spike detector that prevents one action potential from being counted twice.

A live closed loop in your browser

The widget below is a complete software Portiloop. A synthetic NREM recording (tutorial 01, ground-truth spindles known) is played sample by sample through the exact Portiloop filters (21-tap FIR, 60 Hz notch, online standardization with αμ = 0.1 and ασ = 0.001), a 54-sample window is sent to the real published network (pareto_search_15_35_v4_0, 25,679 parameters) at the chosen schedule with 8 hidden states, and the notebook's stimulation rule decides when to "play a sound".

Live closed-loop oscilloscope

Top: the standardized EEG as the network sees it (already 40 ms late because of the FIR). Bottom: the network output. Green bands: ground-truth spindles. Pink vertical lines: stimulations, drawn at the time the sound would start (decision time + 20 ms forward pass + 4 ms sound hardware). Statistics restart whenever you change a setting. What to try: press Play; set the refractory period to 0 and watch the false stimulations pile up; raise the threshold to 0.84 (the paper's best value) and watch the median delay grow; switch to the uniform schedule.

Stream time
0:00
Spindles (ended)
0
Stimulated
0
False stimuli
0
Median delay
-
Within 250 ms
-
Loading model…

How the statistics are computed (paper definitions, section 6.1 [1]): a spindle is stimulated (true positive) if a stimulation falls inside its labelled duration, all delays included, and the delay is measured from the spindle onset to the first such stimulation; every other stimulation is false. "Within 250 ms" counts stimulated spindles whose delay is at most max_time_stimulate_s = 0.25, the notebook's tolerance. The first 5 s of each recording are not used for stimulation (see the note below).

Note on start-upThe online standardizer starts with no knowledge of the signal's variance; with ασ = 0.001 its estimate needs on the order of 1000 samples (4 s) to settle, and in that period the network sees badly scaled input and tends to fire. The widget therefore ignores the first 5 s. This warm-up is a choice of this widget, not something we found in the notebook; on a device, start stimulating only after the signal has been streaming for a few seconds.
Synthetic dataThe recording is a didactic signal with smooth, waxing spindles. Its numbers (on the order of 0.4 s median delay at threshold 0.5 in our tests) are not those of real EEG. For real performance figures, run the notebook (next section) on real annotated data converted to the dataset format, or use the values of the paper (Table 2 above; precision and recall of 0.71 at threshold 0.84).
Under the hoodThe JavaScript in this page uses PL.filters.FIR, PL.filters.Biquad with PL.filters.PORTILOOP_NOTCH, PL.OnlineStandardizer and model.step(window, h) from the site library. We checked offline that, with the uniform schedule, its outputs equal PL.preprocess followed by model.runStream on the same data (largest difference 3e-8, float rounding). Each model.step takes a few milliseconds in JavaScript; if your computer cannot keep up at 5x, the widget slows down rather than skipping samples and says so in the status line.

Running the simulation notebook

The notebook notebooks/simulate_Portiloop_1_input_classification.ipynb does the same thing on the annotated dataset files (the synthetic practice dataset, or your own real data in the same format), offline but with every real-time constraint. It (1) runs the network on the test subjects with the interleaved schedule, (2) applies the stimulation rule, (3) measures stimulation delays, (4) shows an interactive plot and (5) explains individual decisions with Captum.

  1. Prepare the data and environment. Complete tutorial 02: the package installed with pip install -e . and the dataset files in portiloop_software/dataset/. The notebook additionally imports ipywidgets (interactive plot) and installs captum itself in cell 15 (with %pip, which installs into the notebook's own environment; you can also install it beforehand, as below).
    pip install jupyter ipywidgets captum
    jupyter notebook notebooks/simulate_Portiloop_1_input_classification.ipynb
  2. Cells 1 to 5: paths and definitions. Cell 1 prints the dataset, plots and experiments folders. Cell 5 is a copy of the training code (dataset, samplers, PortiloopNetwork, run_inference, get_metrics, generate_dataloader) plus get_config_dict, which returns the configuration of the published architecture.
  3. Cell 6: simulate(c_dict, split_idx). Builds the test set for split split_idx, loads portiloop_software/experiments/<experiment_name>, and runs inference with 8 parallel hidden states (the batch dimension holds one hidden state per (segment, offset) pair, so each state sees windows 42 samples apart). It re-interleaves the outputs in time order and returns f1_test, precision_test, recall_test, state, labels_portiloop, output_portiloop, test_loader, net. state codes every output as 1 = true positive, 2 = false positive, 3 = true negative, 4 = false negative.
  4. Cell 8: choose phase, threshold and models. This is the cell you edit (see below). As shipped it evaluates the first pre-trained model only: the loop over the 10 splits ends with break. Expected printout:
    seq_stride: 42
    FPGA_NN_EXEC_TIME + ERROR_FPGA_EXEC_TIME: 5
    nb_parallel_runs: 8
    output_segments.shape: (9, 5472)
    with many DEBUG lines (dataset sizes, subjects, f1_test, precision_test, recall_test). These sample-level scores are those of tutorial 06, computed on the interleaved stream.
  5. Cells 10 to 12: stimulation analysis. stimulation_analysis(THRESHOLD) walks through the outputs with the rule shown above, records each stimulation's sample index, finds spindle onsets and ends in the labels, and for each spindle keeps the stimulation closest to its onset:
                for s in spindle_list_stimulate:
                    delay = s - b
                    if abs(delay) < abs(best):
                        best = delay
                spindle_list_stimulate_delay_best.append(best)
            spindle_list_stimulate_delay_best = np.array(spindle_list_stimulate_delay_best)
            corrected_stimulation_delay = np.append(corrected_stimulation_delay, spindle_list_stimulate_delay_best/fe + constant_delay_s)
    It then reports, for a margin of 0.25 s and 0.5 s (i*max_time_stimulate_s with i = 1, 2), how many spindles were stimulated between 0 and the margin after their onset. Printout with the default synthetic dataset and the pre-trained model (split 0, 9 test segments):
    Split idx: 0
    mean spindle length: 0.8278636363636364
    For margin = 0.25 s
    accurate stimulation: 19
    spindle not stimulated: 69
    total stimulation: 113
    ratio: 16.8141592920354
    percentage stimulated spindles: 21.59090909090909
    For margin = 0.5 s
    accurate stimulation: 74
    spindle not stimulated: 14
    total stimulation: 113
    ratio: 65.48672566371681
    percentage stimulated spindles: 84.0909090909091
    ratio is the percentage of all stimulations that were accurate (a precision); percentage stimulated spindles is the percentage of spindles that received an accurate stimulation (a recall). Note that a stimulation that comes before the labelled onset (negative delay) counts as "not stimulated". In this example most stimulations arrive between 0.25 and 0.5 s after the labelled onset: 84% of the spindles are stimulated within 0.5 s, only 22% within 0.25 s. These are synthetic spindles; for real EEG, see the paper's figures above.
  6. Cell 13: interactive plot. Two sliders (start time and width, in seconds) and a Print button. Colours of the EEG trace: green = true positive, red = false positive, blue = true negative, black = false negative; magenta = network output (drawn 5 units below the EEG, right axis); dotted cyan = labelled spindle onsets; dotted grey = stimulations; dashed grey = threshold. It is the notebook equivalent of the oscilloscope above.
On the hard drive

Reads: portiloop_software/dataset/dataset_classification_full_big_250_matlab_standardized_envelope_pf.txt (signal, envelope, power ratio and label columns), subject_sequence_full_big.txt, subject_sequence_p1_big.txt, subject_sequence_p2_big.txt (which 115 s segments belong to which subject), and the checkpoints portiloop_software/experiments/pareto_search_15_35_v4_*.

Writes: portiloop_software/plots/stimulation_plot.pdf when you press Print in cell 13, and portiloop_software/plots/grad_explainer.pdf in cell 24. Nothing else is saved; results live in the notebook variables res, corrected_stimulation_delay, total_stim, spindle_list_stimulate.

Using your own trained model

After tutorial 05 you have a checkpoint named after your experiment. Change these things, all in the notebook:

WhatWhereWhy
Copy the checkpoint into portiloop_software/experiments/file systemrun() saves to portiloop_software/dataset/<experiment_name>, but simulate() loads path_experiments / experiment_name.
exp_namecell 8List of checkpoint file names, one per split. Put your experiment name(s) here.
split_idx pairingcell 8Model exp_name[split_idx] is tested on the test subjects of split split_idx. Use the split your model was trained with (config_dict["split_idx"] in training), or you will test on training subjects.
get_config_dict valuescell 5Must match the architecture you trained (nb_channel, hidden_size, window_size_s, seq_stride_s, nb_conv_layers, kernels...). A mismatch raises size mismatch in load_state_dict.
FPGA_NN_EXEC_TIME, ERROR_FPGA_EXEC_TIMEcell 8Your hardware's inference time, in samples. This sets the number of hidden states.
network_stride, nb_sampcells 10 and 13Must equal stride_between_runs and nb_parallel_runs printed by simulate(). Cell 13 also hard-codes seq_stride = 42.
THRESHOLD and the 100-sample counterscells 8 and 11Detection threshold and refractory period of your protocol.
constant_delay_scell 10Filter delay + forward pass + stimulus hardware of your setup.
The break at the end of the loopcell 8Remove it to evaluate all splits; stimulation_analysis loops over every entry of res.
Warningstimulation_analysis contains assert segment_state_size == 5472, which is 8 states × (28,750 // 42) cycles per 115 s segment. If you change the sequence stride, the network stride or LEN_SEGMENT, recompute this number (or replace the assertion) or the cell stops with an AssertionError.

Which part of the signal drives a decision? (Captum)

The last section of the notebook ("Interpretation of the results with Captum") asks which samples of the input pushed the output up. It uses Integrated Gradients [3] from the Captum library [2]: the input is morphed gradually from a baseline (here, a sequence of windows taken elsewhere in the test set) to the real input, and the gradient of the output with respect to each input sample is accumulated along the way. Cell 19 rebuilds a sequence of seq_len = 20 consecutive windows of one hidden state (idx_batch selects the segment and offset, i_min = 98 the starting window; the comment suggests spindles at 97, 200, 281), cell 21 wraps the network so that it takes only the signal and starts from a zero hidden state, and cell 23 computes:

ig = IntegratedGradients(net_captum)
attributions, delta = ig.attribute(input, baselines=bl, return_convergence_delta=True)

Cell 24 draws the 20 windows in a grid, each coloured by the absolute attribution (red = strong influence), the last panel titled with the network's score, and saves grad_explainer.pdf. The convergence delta printed by cell 23 should be small compared with the output; if it is not, the attribution is not reliable (more integration steps are needed).

For neuroscientistsIntegrated Gradients is a "virtual lesion" study: instead of removing a brain region and measuring the deficit, it asks how much the output would change if each input sample were replaced by its baseline value, integrating over all intermediate levels. Like lesion studies, the answer depends on the control condition: a different baseline gives different maps.
Known issueCell 24 starts with #FIXME: x axis is not correct here: the time axis of each small panel is approximate, so read the panels by their order, not their x values.

Interpreting the results

Troubleshooting

SymptomCause and fix
FileNotFoundError on dataset_classification_full_big_250_...txt or subject_sequence_...txtThe dataset is not in portiloop_software/dataset/; see tutorial 02.
ModuleNotFoundError: sklearn or ipywidgetspip install -e . from the repository root installs scikit-learn; install ipywidgets separately.
RuntimeError: Error(s) in loading state_dict ... size mismatchget_config_dict in cell 5 does not match the checkpoint's architecture.
AssertionError in stimulation_analysisSee the warning about segment_state_size == 5472 above.
TypeError or FutureWarning about delim_whitespaceOlder copies of the notebook pass delim_whitespace=True to read_csv, which recent pandas versions reject. The current notebook uses sep=r"\s+"; update your clone (git pull) or make the same replacement in generate_dataloader.
The oscilloscope runs slower than the selected speedYour browser cannot run enough forward passes per second; the status line shows the effective speed. 1x always needs only 50 forward passes per second.

Exercises

Why do we need a refractory rule?

In the oscilloscope, note the number of false stimuli after about one minute at the default settings. Restart, set the refractory period to 0 ms and run for the same time. What happens and why?

Answer

With 0 ms, the detector re-arms as soon as one output falls below the threshold, so every flicker of the output inside a spindle (and the disagreement between the eight hidden states) triggers a new sound. In our offline run of the widget's code on 3 minutes of recording 4 (the default) at threshold 0.5, 17 of 17 spindles were stimulated in both cases, but false stimuli went from 0 (400 ms) to 29 (0 ms): the extra sounds land on spindles that were already stimulated, or just after them, so they add no hits, only errors.

How much of a short spindle is left?

With the paper's values in the latency calculator, what fraction of a 0.5 s spindle remains when the sound starts? And of a 2 s spindle?

Answer

The total delay is 40 + 250 + 20 + 4 = 314 ms. For 0.5 s, 186 ms remain (37 %), about 2.4 cycles at 13 Hz; for 2 s, 1686 ms remain (84 %). Short spindles are the hard case for closed-loop stimulation, and the detection delay (not the hardware) is the main term to reduce.

Faster hardware, more hidden states

Suppose your hardware runs the network in 12 ms. With seq_stride unchanged, how many hidden states would simulate() use, and what do you change in the notebook?

Answer

12 ms is 3 samples, so set FPGA_NN_EXEC_TIME = 3: nb_parallel_runs = 42 // 3 = 14 and stride_between_runs = 42 // 14 = 3. Then set network_stride = 3 and nb_samp = 14 in cells 10 and 13, recompute the segment_state_size assertion (14 × 684 = 9576) and the adder (here 14 × 3 = 42, so adder must be 0). Also update constant_delay_s to 0.040 + 0.012 + your stimulus delay. You can check the schedule in the interleaved-states widget with a network stride of 3.

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 (preprint arXiv:2107.13473). Quotes are from the PLOS ONE version.
  2. Kokhlikyan N, Miglani V, Martin M, Wang E, Alsallakh B, Reynolds J, Melnikov A, Kliushkina N, Araya C, Yan S, Reblitz-Richardson O (2020). Captum: a unified and generic model interpretability library for PyTorch. arXiv:2009.07896. Library: captum.ai.
  3. Sundararajan M, Taly A, Yan Q (2017). Axiomatic attribution for deep networks. Proceedings of the 34th International Conference on Machine Learning, PMLR 70: 3319 to 3328. proceedings.mlr.press/v70/sundararajan17a.
  4. Portiloop device software: github.com/Portiloop/portiloop-software, files portiloop/src/custom/custom_detectors.py and portiloop/src/custom/custom_stimulators.py (RDK X5 version on the rdkx5 branch).