Tutorial 10 · Using your model

Exporting and deploying

A trained network is only a file of numbers. In this tutorial you turn it into files that other software and hardware can run: an ONNX model that you can execute from Python or compile for an embedded accelerator, and the C arrays used by the FPGA version of the Portiloop. You will check numerically that nothing changed on the way, and see how many bits of precision the weights really need.

Time
45 minutes
Level
Intermediate
You need
02 (installed package); 05 for your own model; 08 recommended
Runs in browser
Widgets yes; exporting needs Python

In this tutorial you will

  • Understand what ONNX is and what the exported Portiloop model contains (and what it does not)
  • Export the published model or your own with the command line, from Python, or automatically during training
  • Run the exported model with ONNX Runtime, carrying the hidden state between calls, and verify it against PyTorch
  • Inspect all 25,679 weights and extract them as C arrays for the FPGA with parameter_extractor.py
  • Explore how fixed-point precision affects the detector, and where to find the device software

Five files for one network

The same trained detector exists in several formats in the Portiloop ecosystem, each for a different consumer:

FormatProduced byUsed by
PyTorch checkpoint (no extension), e.g. pareto_search_15_35_v4_0run() during training (05)Python: evaluation, notebooks, export
ONNX, .onnxonnx_export.py (this tutorial), also automatically during trainingONNX Runtime on a PC or single-board computer; the device software can run it directly; input to accelerator compilers
RDK X5 BPU binary, .bin (int8)hb_mapper makertbin, driven by compile_bpu.sh in portiloop-software (branch rdkx5)The neural accelerator (BPU) of the D-Robotics RDK X5 board
C arrays, weight.txtparameter_extractor.py (this tutorial)The FPGA implementation (Pynq) of the original Portiloop [1]
TensorFlow Lite, .tflite (quantized)Not in this repositoryThe Coral version of the Portiloop, in portiloop-software

What is ONNX?

ONNX (Open Neural Network Exchange) is an open file format that describes a trained network as a graph of standard operations (convolution, matrix product, sigmoid...) together with all their weights. Any program that implements these operations can run the file, without PyTorch and without the training code. ONNX Runtime is the reference engine to run ONNX files on CPUs and GPUs; vendors of neural accelerators provide compilers that read ONNX and produce code for their chips. Each ONNX file declares an opset, the version of the operation catalogue it uses; older compilers only accept older opsets.

For neuroscientistsONNX is to neural networks what EDF is to EEG recordings: a vendor-neutral container. Your amplifier's software and your analysis toolbox never need to know about each other as long as both speak EDF. In the same way, the training code (PyTorch) and the device (an FPGA, a Coral, an RDK X5) only need to agree on ONNX or on a format derived from it.

The single-step stateful model

During training the network processes a whole sequence of 50 windows at once. A device does not have the future: it gets one window at a time and must remember the past itself. The exporter therefore wraps the network in PortiloopSpindleOnnxStep, which performs exactly one step: one window in, the previous hidden state in; one probability out, the new hidden state out.

class PortiloopSpindleOnnxStep(nn.Module):
    """
    Single-step stateful ONNX wrapper for `PortiloopNetwork` (1-input sleep spindle detector).

    Inputs:
        x: (1, 1, 1, window_size) float32 (default window_size=54)
        h: (1, hidden_size) float32 (default hidden_size=7, or (1, nb_rnn_layers * hidden_size))
    Outputs:
        y: (1, 1) float32 probability in [0, 1]
        h_out: (1, hidden_size) float32 updated hidden state
    """
TensorShapeMeaning
x (input)(1, 1, 1, 54)The last 54 standardized samples (0.216 s at 250 Hz), oldest first. The four dimensions are batch, channels, height, width ("NCHW"): one window, one EEG channel, a "height" of 1, and 54 time points as the width.
h (input)(1, 7)The GRU hidden state returned by the previous call for this hidden-state slot (zeros at the start).
y (output)(1, 1)Probability that the window ends inside a spindle.
h_out (output)(1, 7)The new hidden state, to pass back as h next time.

What the file does not contain: the FIR and notch filters, the online standardization, the 8-slot round-robin schedule of hidden states, the threshold and the stimulation rule (tutorial 08). The program that calls the model must implement all of them, exactly as during training.

Why 4D convolutions and an unrolled GRU?

The network's convolutions are one-dimensional (nn.Conv1d, kernel 7). The exporter rewrites each one as a two-dimensional convolution with a kernel of height 1 and width 7, which computes exactly the same thing on a (1, C, 1, L) tensor. The docstring gives the reason: "1D ConvPoolModule lowered to 2D Conv2d((1, k)) + ReLU + MaxPool2d((1, k)) on 4D NCHW tensors for native BPU hardware acceleration". Embedded accelerators are designed for images, so 4D tensors are their native format.

The GRU is rewritten as explicit matrix products and gate equations, "so that BPU compilers (Horizon bayes-e `hb_mapper`) do not encounter an ONNX Scan/GRU op". The arithmetic is the standard GRU (as in torch.nn.GRU), with gates in the order reset, update, candidate:

$$\begin{aligned} r &= \sigma(W_{ir}x + b_{ir} + W_{hr}h + b_{hr})\\ z &= \sigma(W_{iz}x + b_{iz} + W_{hz}h + b_{hz})\\ n &= \tanh\big(W_{in}x + b_{in} + r \odot (W_{hn}h + b_{hn})\big)\\ h' &= (1-z)\odot n + z \odot h \end{aligned}$$
    def forward(self, x: torch.Tensor, h: torch.Tensor) -> torch.Tensor:
        gi = self.ih(x)
        gh = self.hh(h)
        i_r, i_z, i_n = torch.split(gi, self.hidden_size, dim=-1)
        h_r, h_z, h_n = torch.split(gh, self.hidden_size, dim=-1)
        r = torch.sigmoid(i_r + h_r)
        z = torch.sigmoid(i_z + h_z)
        n = torch.tanh(i_n + r * h_n)
        return (1.0 - z) * n + z * h

We opened the exported file with the onnx package: it declares opset 11 and contains only 3 Conv, 3 Relu, 3 MaxPool, 3 Gemm (matrix products), 3 Sigmoid, 1 Tanh, 2 Split, 4 Add, 3 Mul, 1 Sub, 1 Reshape and 2 Constant nodes, with 25,679 weights in total. Opset 11 is the default because, in the words of the command-line help, it is the "default: 11 for Horizon BPU"; the D-Robotics documentation asks for "caffe1.0 or opset=10/11 onnx models" [4].

Step through the exported model

The same interface as the ONNX file (window x and state h in, y and h_out out), computed by the published network in your browser. Each step moves the window by 42 samples (168 ms), i.e. you follow one of the eight hidden-state slots of tutorial 08. What to try: step through the two spindles (green bands) and watch the output and the hidden units change; tick "reset h before every step", press Reset and Run again, and compare the outputs between spindles.

Loading model…

Exporting a model

From the command line

  1. Install the ONNX package. onnx is listed in setup.py, so pip install -e . (tutorial 02) installs it; if your environment predates this, run:
    pip install onnx onnxruntime
    Without onnx, PyTorch stops the export with OnnxExporterError: Module onnx is not installed!. onnxruntime is only needed to run and check the exported file.
  2. Export the published model. From the repository root:
    python -m portiloop_software.portiloop_python.ANN.onnx_export --output-dir onnx_models
    Expected output (PyTorch may also print a DeprecationWarning about the "legacy TorchScript-based ONNX export"; it is harmless):
    Exported Sleep Spindle ONNX model to: onnx_models/portiloop_spindle.onnx
  3. Options.
    • --output-dir DIR: where to write the files (default onnx_models, created if needed).
    • --spindle-checkpoint PATH: export another checkpoint instead of pareto_search_15_35_v4_0. The architecture is taken from get_final_model_config_dict(), so this works only for checkpoints with the published architecture (31 channels, hidden size 7, window 0.218 s...). For a different architecture, use the Python function below.
    • --opset N: ONNX opset version (default 11).
    • --tinysleepnet-tflite PATH and --nanosleepnet-npz PATH: also export two sleep-staging networks (next section).
On the hard driveReads portiloop_software/experiments/pareto_search_15_35_v4_0 (or your --spindle-checkpoint). Writes onnx_models/portiloop_spindle.onnx relative to the folder you run the command from; in our test the file is 106,701 bytes (about 104 KiB). It is self-contained: weights and graph in one file.

Optional: sleep-staging models

The same module can export two sleep-staging networks, if you have their weight files (they are not in this repository; they are in portiloop-software, branch rdkx5, under portiloop/models/tinysleepnet/ and portiloop/models/nanosleepnet/): TinySleepNet, "Single-step stateful TinySleepNet (CNN + peephole LSTM) using 4D NCHW convolutions", initialized from tinysleepnet_float.tflite (reading it needs the tflite Python package); and NanoSleepNet-TCN, "Single-step causal NanoSleepNet-TCN with BatchNorm fused into 4D NCHW Conv2d layers", loaded from nanosleepnet.npz. Both take one 30 s epoch at 100 Hz (x of shape (1, 1, 1, 3000)) and output five stage logits "(W, N1, N2, N3, REM)"; TinySleepNet carries an LSTM state (c, h of shape (1, 128)), NanoSleepNet carries the "tokens of the previous 9 epochs" (past_tokens, shape (1, 64, 1, 9)). We have not tested these two exports.

From Python (any architecture)

To export a model with your own hyperparameters, build the network with your configuration dictionary and call export_spindle_model_to_onnx. The example uses the published model:

from pathlib import Path
import portiloop_software
from portiloop_software import get_final_model_config_dict, get_trained_model, export_spindle_model_to_onnx

cfg = get_final_model_config_dict()                       # architecture of the published model
experiments = Path(portiloop_software.__file__).parent / "experiments"
net = get_trained_model(cfg, experiments)                 # loads pareto_search_15_35_v4_0
window_size = int(cfg["window_size_s"] * cfg["fe"])       # 54
out = export_spindle_model_to_onnx(net, "onnx_models/my_spindle_model.onnx", window_size=window_size)
print("written:", out)

For your own model, replace cfg by the configuration you trained with (same keys as in tutorial 05) and point get_trained_model to the folder holding your checkpoint; it loads <folder>/<cfg["experiment_name"]>. Only 1-input recurrent models (RNN=True, envelope_input=False, power_features_input=False) can be exported. In our test this script and the command line produced byte-identical files.

Automatically during training

Each time run() saves a new best checkpoint, it also exports it, for 1-input recurrent models:

                if config_dict["RNN"] and not config_dict["envelope_input"] and not config_dict["power_features_input"]:
                    from portiloop_software.portiloop_python.ANN.onnx_export import export_spindle_model_to_onnx
                    export_spindle_model_to_onnx(best_model, path_dataset / f"{experiment_name}.onnx", window_size=window_size)
On the hard driveNext to the checkpoints in portiloop_software/dataset/: <experiment_name>.onnx (best validation F1, saved with the checkpoint <experiment_name>) and <experiment_name>_on_loss.onnx (lowest validation loss, saved with <experiment_name>_on_loss). Both are overwritten whenever a better model is found, so at the end of training they match the final checkpoints.
If your clone is olderAn earlier version of this check referred to variables that do not exist inside run(), so training stopped with an error at the first export. Update your copy (git pull) if you see a NameError there.

Running the ONNX model with ONNX Runtime

  1. One step. The minimal call: create a session, feed a window and a hidden state, get the output and the new state.
    import numpy as np
    import onnxruntime as ort
    
    sess = ort.InferenceSession("onnx_models/portiloop_spindle.onnx", providers=["CPUExecutionProvider"])
    for i in sess.get_inputs():
        print("input ", i.name, i.shape, i.type)
    for o in sess.get_outputs():
        print("output", o.name, o.shape, o.type)
    
    x = np.zeros((1, 1, 1, 54), dtype=np.float32)   # one window: 54 standardized samples (N, C, H, W)
    h = np.zeros((1, 7), dtype=np.float32)          # hidden state, all zeros at the start
    y, h = sess.run(["y", "h_out"], {"x": x, "h": h})
    print("y =", y, "h_out =", h.round(4))
    Expected output:
    input  x [1, 1, 1, 54] tensor(float)
    input  h [1, 7] tensor(float)
    output y [1, 1] tensor(float)
    output h_out [1, 7] tensor(float)
    y = [[0.03100541]] h_out = [[ 0.6783  0.0151  0.085   0.3758 -0.4393  0.5943  0.6186]]
    Inputs must be float32: a float64 NumPy array raises INVALID_ARGUMENT : Unexpected input data type. Actual: (tensor(double)) , expected: (tensor(float)), and a window of the wrong shape raises Invalid rank for input: x.
  2. A stream, as the device does it. Carry eight hidden states and use them in turn (tutorial 08). The input must already be filtered and standardized like the training data.
    import numpy as np
    import onnxruntime as ort
    
    sess = ort.InferenceSession("onnx_models/portiloop_spindle.onnx", providers=["CPUExecutionProvider"])
    for i in sess.get_inputs():
        print("input ", i.name, i.shape, i.type)
    for o in sess.get_outputs():
        print("output", o.name, o.shape, o.type)
    
    WINDOW = 54            # samples per window (0.218 s at 250 Hz)
    NETWORK_STRIDE = 5     # one new window every 5 samples (20 ms)
    N_STATES = 42 // NETWORK_STRIDE   # 8 interleaved hidden states (seq_stride = 42)
    
    def run_stream(standardized):
        """Feed a standardized 250 Hz signal to the ONNX model the way the Portiloop does online."""
        states = [np.zeros((1, 7), dtype=np.float32) for _ in range(N_STATES)]
        ends, outputs = [], []
        k = 0
        for end in range(WINDOW - 1, len(standardized), NETWORK_STRIDE):
            x = standardized[end - WINDOW + 1:end + 1].astype(np.float32).reshape(1, 1, 1, WINDOW)
            y, states[k] = sess.run(["y", "h_out"], {"x": x, "h": states[k]})
            ends.append(end)
            outputs.append(float(y[0, 0]))
            k = (k + 1) % N_STATES
        return np.array(ends), np.array(outputs)
    run_stream returns, for every window, the index of its last sample and the output. This uses the uniform schedule of runStream on this website (a window every 5 samples); to reproduce the notebook or the device exactly, use their gap patterns (tutorial 08). To compare with labels, remember the 10-sample FIR delay.
  3. Check against PyTorch. Always verify an exported model before using it in an experiment:
    from pathlib import Path
    import numpy as np
    import torch
    import onnxruntime as ort
    import portiloop_software
    from portiloop_software import get_final_model_config_dict, get_trained_model
    
    cfg = get_final_model_config_dict()
    net = get_trained_model(cfg, Path(portiloop_software.__file__).parent / "experiments").eval()
    sess = ort.InferenceSession("onnx_models/portiloop_spindle.onnx", providers=["CPUExecutionProvider"])
    
    rng = np.random.default_rng(0)
    h_onnx = np.zeros((1, 7), dtype=np.float32)    # ONNX: (1, num_layers * hidden_size)
    h_torch = torch.zeros(1, 1, 7)                 # PyTorch: (num_layers, batch, hidden_size)
    worst_y, worst_h = 0.0, 0.0
    for step in range(20):
        x = rng.normal(size=(1, 1, 1, 54)).astype(np.float32)
        y_onnx, h_onnx = sess.run(["y", "h_out"], {"x": x, "h": h_onnx})
        with torch.no_grad():
            y_torch, h_torch, _, _ = net(torch.from_numpy(x).view(1, 1, 54), None, None, h_torch, None)
        worst_y = max(worst_y, abs(float(y_onnx[0, 0]) - float(y_torch)))
        worst_h = max(worst_h, float(np.abs(h_onnx - h_torch.numpy().reshape(1, -1)).max()))
    print(f"largest difference over 20 steps: output {worst_y:.1e}, hidden state {worst_h:.1e}")
    Expected output (tiny differences are normal float32 rounding):
    largest difference over 20 steps: output 1.2e-07, hidden state 7.9e-07
What we verifiedWith onnx 1.23.2, onnxruntime 1.32.0 and PyTorch 2.9.1: the exported published model passes onnx.checker; on the 12-window reference sequence stored with this website's model (docs/assets/models/portiloop_spindle_v4_0.json) it matches PyTorch to 1.2e-7 (output) and 7.8e-7 (hidden state), and so does the portiloop_spindle.onnx shipped in portiloop-software (branch rdkx5), which is byte-identical to our export; the JavaScript model used in these pages matches the same reference to 2.2e-7; and over a 30 s synthetic stream with 8 interleaved states, ONNX Runtime and the JavaScript model agree to 1.4e-6. All three implementations compute the same function.

The weights, one tensor at a time

Before shrinking a model for hardware it helps to know what is inside. The table lists every tensor of the published network, with its PyTorch name, its name in the ONNX file, and the C array that parameter_extractor.py writes for the FPGA. Their sizes add up to 25,679, the "25.6k parameters" of the paper [1].

Weight inspector

Click a row to see the distribution of that tensor. What to try: compare the range of the convolution kernels with that of the GRU input weights (weight_ih_l0, almost half of all parameters); find the largest absolute weight in the network. Is any weight larger than 3 in magnitude (the value that parameter_extractor.py checks for)?

PyTorch name
ONNX initializer / C array
ShapeCountMinMaxDistribution
Loading model…

Fixed point and the FPGA: parameter_extractor.py

The first Portiloop ran the network on an FPGA, a chip whose circuits are configured for one computation [1]. FPGAs compute far more efficiently with fixed-point numbers (integers with an implicit binary point, e.g. 8 bits where 5 are after the point) than with floating point. The script's docstring states its purpose: "This script extracts the weights of a trained ANN in pytorch so as to implement the ANN in FPGA." It writes every tensor as a C array declaration of type parameter_fixed_type:

const parameter_fixed_type conv1_input1_kernel[CHANNEL_SIZE][1][CONV_K_SIZE] = {{{-0.071890644729137420654296875, 0.095020823180675506591796875, ...
const parameter_fixed_type conv1_input1_bias[CHANNEL_SIZE] = {0.02464049123227596282958984375, -0.1756165325641632080078125, ...

The values are written in full (format(f, '.60g')), not rounded: the conversion to fixed point happens when the FPGA code is compiled, according to how parameter_fixed_type and the size macros (CHANNEL_SIZE, CONV_K_SIZE, GRU_WI_SIZE...) are defined there. That FPGA code is not in this repository, and we could not find it in the public repositories of the Portiloop organization. The script ends by printing every weight larger than 3 in magnitude, presumably to check that all weights fit the integer range of that type (for the published model it prints nothing; the largest weight is 2.33):

for i in net.parameters():
    for j in i.view(-1):
        if abs(j) > 3:
            print(j)

The training code also keeps track of the largest activation, for the same reason. In PortiloopNetwork.forward:

        # max_value (optional) : print the maximal value reach during inference (used to verify if the FPGA implementation precision is enough)

Each convolution block, the GRU output and the final linear layer compare their largest absolute value with max_value and log it (logging.debug(f"max_value = {max_temp}")) when it grows; the simulation notebook calls run_inference(..., max_value=0) so that every new maximum is reported.

  1. Run the extractor. The script imports the training module as a top-level module and reads the checkpoint from the dataset folder, so copy the checkpoint there and run it from its own folder:
    cp portiloop_software/experiments/pareto_search_15_35_v4_0 portiloop_software/dataset/
    cd portiloop_software/portiloop_python/ANN
    python parameter_extractor.py
  2. Check the output. portiloop_software/dataset/weight.txt has 12 lines (one per tensor, in the order conv1, GRU, conv2, conv3, fc) and about 0.8 MB; the numbers of values per line add up to 25,679.
  3. Your own model. Edit experiment_name and the configuration (portiloop.get_config_dict(29, 0)) at the top of the script to match your training run.
If your clone is olderThe published checkpoints were saved from a GPU. The current script loads them with map_location='cpu'; older copies stop on a computer without CUDA with RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. Update your clone (git pull) or add map_location='cpu' to the torch.load call. (We ran the current script unchanged, with its output redirected to a scratch folder, to produce the numbers above.)
On the hard driveReads portiloop_software/dataset/<experiment_name> (note: dataset, not experiments). Writes portiloop_software/dataset/weight.txt, overwriting any previous one.
How many bits do you need?

All 25,679 weights are rounded to N-bit signed fixed point, then the network is re-run on a 30 s synthetic recording (8 interleaved states, one window every 5 samples) and compared with the full-precision network. Activations stay in floating point here; a real FPGA design must also choose their format (see the largest activation below). What to try: with per-tensor scaling, lower the bits until the output visibly departs from the float curve; then switch to one global format and see why 2 integer bits plus sign are needed for weights up to 2.33; run the sweep.

Format
…
Max |Δ output|
…
Mean |Δ output|
…
Decisions flipped
…
F1 float / quantized
…
Weights saturated
…
Loading model…
For neuroscientistsFixed point is like reading a voltage on an amplifier with a fixed input range and a fixed number of ADC bits. The integer bits set the range (values beyond it saturate, like a clipped EEG), the fractional bits set the resolution (the smallest step, like the µV per bit of your ADC). Per-tensor scaling is like choosing a separate gain for every channel.

"Decisions flipped" counts outputs that land on the other side of the 0.5 threshold; F1 is the sample-level score of tutorial 06 against the synthetic labels (with the 10-sample FIR delay). On this recording, per-tensor 8-bit weights change the output by a few hundredths at most and flip about one decision in 1,490, while a single global 8-bit format with 5 fractional bits is clearly worse. These are results for one synthetic recording and weights only; they are a guide, not a guarantee for real hardware, where the activation format and the rounding of every multiply-accumulate also matter.

Hardware targets and device software

Three hardware platforms appear in the paper and in the code. For each: what runs the network, which file it needs, and what we could verify.

Getting a model onto the RDK X5

The device software keeps the RDK X5 work on a separate branch, rdkx5 (not on main at the time of writing). Its portiloop/bpu/README.md describes the path from a checkpoint to the board. The steps below summarize it; we read these files but did not run the toolchain.

  1. Export to ONNX, straight into the device repository. The README's command (paths assume both repositories under ~/Projects):
    cd ~/Projects/portiloop-training
    python3 -m portiloop_software.portiloop_python.ANN.onnx_export \
        --output-dir ~/Projects/portiloop-software/portiloop/models \
        --tinysleepnet-tflite ~/Projects/portiloop-software/portiloop/models/tinysleepnet/tinysleepnet_float.tflite \
        --nanosleepnet-npz ~/Projects/portiloop-software/portiloop/models/nanosleepnet/nanosleepnet.npz
    This is where the two sleep-staging weight files live (tinysleepnet_float.tflite, nanosleepnet.npz). We checked that the portiloop/models/portiloop_spindle.onnx stored in that branch is byte-identical to the file we exported from pareto_search_15_35_v4_0, and that it reproduces the PyTorch reference outputs to 1.2e-7.
  2. Compile with compile_bpu.sh on an x86_64 computer with the D-Robotics OpenExplorer X5 toolchain (hb_mapper installed, or its Docker image). The script (1) runs prepare_calibration_data.py with ONNX Runtime to produce calibration inputs for both x and the hidden state h (the README: "so that both input EEG windows/epochs and recurrent hidden states (`h`, `c`, `past_tokens`) are calibrated on realistic activation distributions"); (2) runs hb_mapper makertbin with configs/spindle_bpu.yaml (march: 'bayes-e', inputs 'x;h', norm_type: 'no_preprocess;no_preprocess', optimize_level: 'O3'); (3) copies the result to portiloop/models/portiloop_model_bpu.bin. Intermediate files (original, optimized, calibrated and quantized ONNX graphs) go to portiloop/bpu/build_spindle/ and calibration data to portiloop/bpu/cal_data/; both are ignored by git.
  3. Copy the repository to the board. The detector looks for fixed file names in portiloop/models/, the folder of its default model portiloop_model_quant.tflite: it uses portiloop_model_bpu.bin if that file exists and the BPU runtime is installed; portiloop_spindle.onnx only if no TensorFlow Lite runtime is available (or if you select it); otherwise the .tflite file. A specific file can be chosen with the configuration key spindle_model_path.

For the general use of the toolchain, the vendor's quick start [4] describes hb_mapper checker, which makes sure a floating-point model "meets the support constraints of the computing platform", and hb_mapper makertbin, which performs "parsing, graph optimization, calibration, quantization, and compilation"; the architecture option for the X5 is "bayes-e (default value)".

Calibration dataQuantizing to int8 needs examples of typical inputs. In the current prepare_calibration_data.py, the spindle model is calibrated on 64 windows of synthetic sleep-like EEG divided by 20 (_synthetic_sleep_eeg(54, 250.0, rng) / 20.0), each drawn independently, with the hidden state reset every 16 windows. These are not windows that went through the Portiloop filters and online standardization, which is what the network receives on the device. If you deploy your own model, consider calibrating with standardized windows from real recordings, fed with the 8-state schedule, and compare the .bin outputs with the float model on held-out data.

How the board runs the model (SleepSpindleRealTimeDetector and portiloop/src/core/bpu.py): the BPU binary is used whenever portiloop_model_bpu.bin is present and the D-Robotics runtime (hbm_runtime or hobot_dnn) is installed; otherwise ONNX Runtime or TensorFlow Lite. Whatever the backend, the detector keeps a buffer of the last 54 filtered and standardized samples, eight hidden states (np.zeros((1, 7), dtype=h_dtype), float32 for the BPU and ONNX, int8 for TensorFlow Lite) used in turn with the gaps stride_counters = 5, 5, 5, 6, 5, 5, 5, 6 (each state sees windows exactly 42 samples apart, tutorial 08), and calls the model as self.session.run({"x": x_4d, "h": input_h}), storing out["h_out"] for that state. An output counts as a detection when result >= self.threshold; the default threshold in DEFAULT_CONFIG_DICT is 0.75. The filters on the device (SpindleFilter in custom_processors.py) use the same 21-tap FIR, the same 60 Hz notch coefficients and the same standardization constants (polyak_mean 0.1, polyak_std 0.001) as training, plus an epsilon of 1e-6 in the denominator.

Deploying is more than the modelWhatever the target, the device program must reproduce the training preprocessing exactly (21-tap FIR, 60 Hz notch, online standardization with αμ = 0.1 and ασ = 0.001; tutorial 03), the window length (54 samples), the interleaved hidden states (tutorial 08) and the stimulation rule. After deployment, record a session with the device and re-run the same data offline through the PyTorch model: the outputs should agree.

Troubleshooting

SymptomCause and fix
OnnxExporterError: Module onnx is not installed!pip install onnx (or reinstall the package with pip install -e .).
ModuleNotFoundError: No module named 'sklearn' or 'wandb' when exportingThe exporter imports the training module, which needs the training dependencies: pip install -e . from the repository root.
size mismatch when using --spindle-checkpointYour checkpoint has a different architecture; export it from Python with your own configuration (above).
[ONNXRuntimeError] : 2 : INVALID_ARGUMENT on sess.runWrong dtype or shape: x must be float32 of shape (1, 1, 1, 54) and h float32 of shape (1, 7).
The outputs are always near 0 or always near 1The input was not standardized (raw microvolts instead of the online-standardized signal), or the same hidden state was used for every window instead of 8 interleaved ones.
RuntimeError: Attempting to deserialize object on a CUDA device in parameter_extractor.pyYour copy predates the fix: git pull, or add map_location='cpu' to its torch.load call.
ModuleNotFoundError: No module named 'portiloop_detector_training' in parameter_extractor.pyRun it from its own folder, portiloop_software/portiloop_python/ANN (it imports the training module by its file name).
The accelerator compiler rejects the modelCheck the opset (--opset), then use the vendor's checker tool on the file; report unsupported operators to the vendor.

Exercises

Does the network need its memory?

In the "Step through the exported model" widget, press Run until the end of the recording with "reset h before every step" unticked, and note the outputs inside the spindles. Reset, tick the box and run again. What changes, and what does it tell you about what a device must store between calls?

Answer

Without the hidden state, every window is judged in isolation, as if the recording had just started. On this recording the spindles are still recognized, but the output between spindles is higher and noisier (we measured a mean of 0.34 outside spindles without memory against 0.23 with it, and slightly lower values inside spindles), so a fixed threshold produces more false detections. The network was trained to integrate several seconds of context; its single-window judgement is weaker. The device must keep h_out of every call and feed it back as h to the next call of the same slot; with 8 slots, that is 8 × 7 = 56 numbers of state.

Find the smallest safe weight format

In "How many bits do you need?", find the smallest number of bits for which no decision flips, first with per-tensor scaling and then with one global format (choose the best integer-bit setting). Why does the global format need more bits?

Answer

On our run, per-tensor scaling flips no decision from 10 bits on (and only about one at 8 bits); the global format with 3 integer bits needs about 12 bits. A global format must cover the largest weight of the whole network (2.33, in the GRU input weights) with the same step for every tensor, so the small convolution weights (all below 0.8 in magnitude) waste their top bits. Per-tensor scaling gives each tensor its own range. Use the sweep button to see the full curves; your exact numbers depend on the recording.

Verify your own export

Export a model you trained in tutorial 05 with export_spindle_model_to_onnx, then adapt compare_torch.py to it. What should you change besides the file name?

Answer

Build net from your own configuration (and checkpoint folder), and use your window length and hidden size for the shapes: x of shape (1, 1, 1, int(window_size_s * fe)), h_onnx of shape (1, nb_rnn_layers * hidden_size) and h_torch of shape (nb_rnn_layers, 1, hidden_size). Differences around 1e-7 to 1e-6 are float rounding; anything above about 1e-4 means something is wrong.

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).
  2. ONNX, Open Neural Network Exchange: onnx.ai. ONNX Runtime documentation, Python quick start: onnxruntime.ai/docs/get-started/with-python.html.
  3. Portiloop organization on GitHub: portiloop-hardware (plans of the Coral-based device), portiloop-software (device software and GUI; RDK X5 support and BPU pipeline on the rdkx5 branch).
  4. D-Robotics, RDK X5 algorithm toolchain, "Algorithm Model PTQ + On-board Deployment Quick Start": developer.d-robotics.cc/oe_x5_doc/en/oe_mapper/source/faststart/quickstart.html.