Tutorial 07 · Training

Hyperparameter search

How many filters, how long a window, how much memory? Instead of guessing, the Portiloop authors let an algorithm (PMBO) train hundreds of candidate networks and keep those that offer the best compromise between detection quality and size. This tutorial explains the idea, what the code does line by line, how to run it, and what to edit first.

Time
45 minutes to read; a real search takes days of GPU time
Level
Advanced
You need
Tutorial 04 and Tutorial 05
Runs in browser
Widgets yes; the search needs GPUs and the dataset

In this tutorial you will

  • Understand why the size of a network matters for a closed-loop device, and what a Pareto front is.
  • Follow one iteration of Parallel Model-Based Optimization (PMBO): sampling, filtering by size, prediction by a surrogate model, selection, training.
  • See, on a toy problem, why a surrogate can reach good architectures with fewer trainings than random search, and when it cannot.
  • Know every hard-coded constant you must check, rehearse the search loop on a laptop in two minutes, then run it locally or on several GPU machines.
  • Read the result files and pick a model to retrain.

Why architecture matters on an embedded device

A detector for closed-loop stimulation is judged on two very different axes. It must detect spindles well, and it must fit and run in real time on small hardware. The paper states the constraint plainly [1]:

Valenchon et al. (2022), section 4“The Portiloop has a limited amount of available memory, so as to ensure its portability and low price. Therefore, large ANN architectures such as SpindleNet [29] are orders of magnitude too large to be implemented in our device. To produce networks that are suitable to our device, we rely on an automated optimization algorithm named “Parallel Model-Based Optimization” (PMBO) that allows us to trade-off accuracy and use of resources on our device”.

Bigger is usually better for accuracy, but every extra parameter costs memory, and every extra multiplication costs time. Time matters twice in closed loop: the forward pass of the published model takes 20 ms on the Portiloop, against 40 ms for the earlier 2-input model [1], and the stimulus can only be sent after the forward pass. The search space is large: tutorial 04 listed about fifteen architecture and training choices, many with dozens of possible values. Training one candidate on the MODA data takes hours on a GPU, so trying everything is impossible.

For neuroscientists: a trade-off you already knowChoosing an fMRI voxel size is the same kind of problem: smaller voxels give better spatial resolution but lower signal-to-noise and longer acquisitions. Nobody asks for “the best voxel size”; one asks for the best resolution for a given scan time, or the shortest scan for a given resolution. The set of protocols that cannot be improved on one axis without losing on the other is exactly what an engineer calls a Pareto front.

Two costs and the Pareto front

PMBO minimizes two costs. In the words of the supplementary material (S1 File, Appendix J) [1]:

Between two trained candidates \(E\) and \(E'\), the paper defines (Definition 1): “We say that \(E\) Pareto-dominates \(E'\) [...] when \(L_s < L'_s \wedge L_h < L'_h\)”, that is, \(E\) is both more accurate and smaller. The Pareto front is the set of candidates that no other candidate dominates; in the paper's words, “all points that are not on the Pareto front have at least one corresponding configuration that is better in terms of both software and hardware cost, and should therefore not be considered.”

Pareto front explorer

Each dot is a (synthetic, made-up) trained network: its size and its validation F1. The highlighted staircase is the Pareto front. What to try: click any dot to see which networks dominate it and which ones it dominates, and the score PMBO would give it as a candidate. Move the hardware budget to see how the “best model” changes with the device you target. Switch the vertical axis to the software cost \(1 - F_1\) used in the code and in the paper's Fig 4.

Networks
…
On the front
…
Best F1 within budget
…
Its size
…
Click a dot.

Two lessons from the widget. First, most of what a search produces is dominated: in the paper's Fig 4 most of the explored architectures are black (non-Pareto-optimal) dots. Second, the front itself does not choose for you; the hardware budget does. Moving the budget shows that “the best model” is a different network for a 10,000-parameter device and for an 80,000-parameter one.

Strict or weak domination?The paper's definition requires both costs to be strictly lower. The code is slightly different in one place: update_pareto() refuses a new experiment if an existing front member is lower or equal on both costs (<=), and removes front members that are strictly worse on both. pareto_efficiency() uses strict comparisons, as the paper. The difference only matters for ties, which are rare with real F1 values.

How PMBO searches

The supplementary material introduces the algorithm as follows [1]: “PMBO is essentially a parallelized and evolved version of “Probabilistic SMBO” [2]. PMBO is a guided-search approach that finds a suitable set of hyperparameters rapidly. For this matter, it uses one machine (or process) to train a meta network whose role is to predict non-trivially available costs for any given set of hyperparameters.” SMBO stands for sequential model-based optimization: keep a cheap statistical model (the surrogate, or meta network) of “how good would this configuration be”, use it to decide what to train next, and refit it after every real training.

One PMBO iteration: sample candidates, filter by size, predict with the surrogate, select, train, update 1. Samplesample_config_dict()random or near the last 2. Size filternb_parameters()keep 1,000 to 80,000 3. PredictSurrogateModelestimated 1 − F1 4. Select 1 of 200exp_max_pareto_efficiency()best score η (10 %: random) 5. Train for realrun(), hours on a GPUcost = 1 − best F1 6. Updateupdate_pareto(), retrain the surrogate, save pickles repeated until 200 candidates
One iteration of iterative_training_local() in PMBO/pareto_search.py. Steps 1 to 3 are repeated until NB_SAMPLED_MODELS_PER_ITERATION = 200 candidates have been collected; only one of them is trained.

Step 1: the search space and how candidates are sampled

The space is defined at the top of portiloop_software/portiloop_python/Utils/utils.py as [min, max, step] triples:

seq_len_range_t = [50, 50, 1]  # min, max, step
kernel_conv_range_t = [3, 11, 2]  # min, max, step
kernel_pool_range_t = [3, 11, 2]  # min, max, step
stride_conv_range_t = [1, 1, 1]  # min, max, step
stride_pool_range_t = [1, 1, 1]  # min, max, step
dilation_conv_range_t = [1, 1, 1]  # min, max, step
dilation_pool_range_t = [1, 1, 1]  # min, max, step
nb_channel_range_t = [1, 100, 5]  # min, max, step
hidden_size_range_t = [2, 100, 5]  # min, max, step
window_size_s_range_t = [0.05, 0.5, 0.008]  # min, max, step
seq_stride_s_range_t = [0.05, 0.2, 0.008]  # min, max, step
nb_conv_layers_range_t = [1, 5, 1]  # min, max, step
nb_rnn_layers_range_t = [1, 2, 1]  # min, max, step
rnn_range_t = [1, 1, 1]
envelope_input_range_t = [0, 0, 1]
lr_adam_range_t = [0.0003, 0.0009, 0.0002]
batch_size_range_t = [64, 256, 64]

sample_from_range() converts each triple to a grid of allowed values, with a rounding scheme that does not always produce what the triple suggests. For this tutorial, 20,000 samples of each range were drawn with the repository's function; the table lists the values that actually come out.

HyperparameterRange tripleValues actually sampledPublishedComment
nb_conv_layers[1, 5, 1]1, 2, 3, 4, 53
nb_channel[1, 100, 5]1, 6, 11, ..., 96, 100 (21 values)31Grid is offset by 1; 101 is clipped to 100.
kernel_conv, kernel_pool[3, 11, 2]5, 7, 9, 117, 73 is never sampled (Python rounds 1.5 to 2, banker's rounding, so the grid starts one step too high).
window_size_s[0.05, 0.5, 0.008]0.050, 0.058, ..., 0.498 (57 values)0.21812 to 124 samples.
seq_stride_s[0.05, 0.2, 0.008]0.050, 0.058, ..., 0.194, 0.200 (20 values)0.170The paper's “time dilation”, 12 to 50 samples.
hidden_size[2, 100, 5]2, 7, 12, ..., 97, 100 (21 values)7
nb_rnn_layers[1, 2, 1]1, 21
lr_adam[0.0003, 0.0009, 0.0002]0.0003, 0.0005, 0.0007, 0.00090.0005
batch_size[64, 256, 64]64, 128, 192, 256256
seq_len[50, 50, 1]5050Fixed (set to 1 if RNN were off).
RNN, envelope_input[1, 1, 1], [0, 0, 1]True, FalseTrue, FalseFixed: always a GRU, never the envelope branch.
strides, dilations[1, 1, 1]11Fixed.

Every other key is fixed inside sample_config_dict(): dropout = 0.5, adam_w = 0.01, first_layer_dropout = False, power_features_input = False, distribution_mode = 0, classification = True, split_idx = 0, validation_network_stride = 1, fe = 250, devices "cuda:0", nb_epoch_max = MAX_EPOCHS_PER_EXPERIMENT (150), early-stopping patience NETWORK_EARLY_STOPPING (20), nb_batch_per_epoch = NB_BATCH_PER_EPOCH (1000).

How a candidate is drawn. If there is no previous experiment, or with probability EPSILON_NOISE = 0.25, every value is drawn uniformly on its grid. Otherwise it is drawn from a Gaussian centred on the previous experiment's (unrounded) values, with a standard deviation of 10 % of each range. The architecture part (window, kernels, strides, dilations) is redrawn, with a growing standard deviation, until the network is valid (nb_out ≥ 1, see tutorial 04), and a configuration identical to one already tried (same_config_dict()) is rejected. The paper calls these two kinds of randomness “noise type 1” (0.25) and “noise type 2” (0.1, below) [1].

“The previous experiment” is the last network actually trained. In the local loop it is kept in a variable initialized once, before the loop, and updated after every training:

    prev_exp = {}  # last trained experiment, used to sample new configurations around it
    for meta_iteration in range(MAX_META_ITERATIONS):
        ...
            config_dict, unrounded = sample_config_dict(name=RUN_NAME + "_" + str(num_experiment), previous_exp=prev_exp, all_exp=all_experiments)
        ...
        prev_exp = exp
Older clonesBefore the November 2026 fix, prev_exp = {} sat inside the loop, so the local search drew every candidate uniformly at random and never refined around the last result. If git log shows an older version, run git pull. The distributed meta-learner (pareto_network.py) was not affected: it samples around the last result it received, for the first candidate it selects after each result.

Step 2: the hardware filter

def nb_parameters(config_dict):
    net = PortiloopNetwork(config_dict)
    res = sum(p.numel() for p in net.parameters())
    del net
    return res

Each candidate network is instantiated (not trained) only to count its parameters, exactly as in the calculator of tutorial 04. Candidates outside MIN_NB_PARAMETERS = 1,000 and MAX_NB_PARAMETERS = 80,000 (Utils/utils.py) are discarded and resampled. This range is the “range cost hardware 1000-80000” of the paper's supplementary Table I. Change it first if your hardware differs: it is the only place where the device's capacity enters the search.

Step 3: the surrogate model

Training a candidate costs hours; predicting its cost from its configuration costs microseconds. The surrogate is a small fully connected network (three nn.Linear layers, 10 inputs, 200 hidden units, 1 output):

def transform_config_dict_to_input(config_dict):
    x = [#float(config_dict["seq_len"]),  # idk why, but needed
         float(config_dict["nb_channel"]),
         config_dict["hidden_size"],
         int(config_dict["seq_stride_s"] * config_dict["fe"]),
         config_dict["nb_rnn_layers"],
         int(config_dict["window_size_s"] * config_dict["fe"]),
         config_dict["nb_conv_layers"],
         #config_dict["stride_pool"],
         #config_dict["stride_conv"],
         config_dict["kernel_conv"],
         config_dict["kernel_pool"],
         #config_dict["dilation_conv"],
         #config_dict["dilation_pool"],
         #int(config_dict['RNN']),
         #int(config_dict['envelope_input']),
         config_dict["lr_adam"],
         config_dict["batch_size"]]
    x = torch.tensor(x)
    return x

It is trained by train_surrogate() to predict cost_software (\(1 - F_1\), because MAXIMIZE_F1_SCORE = True in Utils/utils.py) from these 10 numbers, with mean squared error, plain SGD (learning rate 0.05, weight decay 0.01, gradient clipping at 10) and one experiment per batch. With 100 experiments or fewer it trains on all of them for as many epochs as there are experiments; above START_META_TRAIN_VAL_AFTER = 100 it keeps 20 % aside as a validation set and stops after META_EARLY_STOPPING = 30 epochs without improvement (at most MAX_META_EPOCHS = 500). A fresh surrogate is trained from scratch after every completed experiment.

For neuroscientists: a surrogate is a fitted dose-response curveIf each experiment were a costly session with a participant, you would not test stimulation intensities at random: you would fit a dose-response curve to the sessions run so far and use it to choose the next intensity. The surrogate plays the role of that curve, in 10 dimensions instead of one. Like any curve fitted to few points, it is unreliable where no data has been collected yet, which is why the algorithm keeps some randomness.
The inputs are not normalizedThe 10 inputs have very different scales (lr_adam around 0.0005, batch_size up to 256, window up to 124 samples) and are fed to the surrogate raw. In the rehearsal run below, the first surrogates predicted costs of 5.5, −29.1 and −1.6 (a cost \(1 - F_1\) must lie between 0 and 1) before settling once about eight experiments were available. If you modify the code, standardizing these inputs is a natural first improvement. The paper also reports that “the predictions of the meta-learner are often near-constant in well-performing areas of the search space” and that the authors “surmise that this is due to the large variance in model performance from one training session to another” [1].

Step 4: choosing one candidate out of 200

With probability EPSILON_EXP_NOISE = 0.1 (and always while the front is empty) a random candidate is chosen. Otherwise each candidate \(\hat E\), with its predicted software cost \(\hat L_s\) and its exact hardware cost \(L_h\), receives the heuristic “Pareto efficiency” of the supplementary Appendix J [1], computed against the set \(\mathcal E\) of experiments already completed:

$$\eta(\hat E) = \underbrace{1 - \frac{d_{\mathcal E}(\hat E)}{|\mathcal E|}}_{a:\ \text{not dominated}} + \underbrace{\frac{D_{\mathcal E}(\hat E)}{|\mathcal E|}}_{b:\ \text{dominates others}} + \underbrace{\frac{\min L_s}{\hat L_s}}_{s:\ \text{beats the best F1?}} - \underbrace{h_{\mathcal E}(\hat E)}_{\text{crowding penalty}}$$

where \(d\) counts the completed experiments that would dominate the candidate and \(D\) those it would dominate. The crowding penalty \(h\) is the density of completed experiments in the candidate's parameter-count bin (100 bins over 0 to 80,000), multiplied by the range width: it equals 100 times the fraction of past experiments that fall in the same 800-parameter bin. It is large compared with the other terms (a, b and s are of order 1), so in practice candidates in parameter ranges that have not been tried yet win; this spreads the trainings along the size axis. The code:

    score_not_dominated = 1.0 - float(nb_dominating) / len(all_experiments)
    score_dominating = nb_dominated / len(all_experiments)
    score_distance_from_best_loss = abs(best_cost_software / experiment[
        "cost_software"])  # The lower is the predicted experiment loss, the better. This score is close to 1 when you reach a loss as good as the lowest one of all exp. If yours is better, then the score will be above 1. Otherwise the farest you are, the lower is your score
    ...
    return score_dominating + score_not_dominated + score_distance_from_best_loss
        histo = np.histogram([exp["cost_hardware"] for exp in all_experiments], bins=100, density=True, range=(0, MAX_NB_PARAMETERS))
        ...
            efficiency = pareto_efficiency(exp, all_experiments)
            ...
            nerf = histo[0][min(idx, len(histo[0]) - 1)] * MAX_NB_PARAMETERS
            efficiency -= nerf
Known issue: predicted costs near zero or negative dominate the choiceThe term \(s = |\min L_s / \hat L_s|\) explodes when the surrogate predicts a cost close to 0, and the absolute value turns a (meaningless) negative prediction into a large positive score. In the rehearsal below, a candidate predicted at −0.00027 received a score of 1,559 (typical scores are 2 to 4). Clipping predictions to the interval 0 to 1 before scoring would avoid this.

Why bother with a surrogate? A toy experiment

The widget below is a toy: two made-up hyperparameters (“width” and “window”), a made-up F1 landscape with a narrow good region and a misleading bump, and a made-up parameter count. A “training” takes no time here: it just reads the landscape and adds noise. It compares random search (train one random configuration per iteration) with a PMBO-like strategy: draw N candidates (25 % uniformly, 75 % around the last trained point), predict their F1 with a kernel regression of the points trained so far (a simple surrogate, not the neural network of the real code), and train the candidate with the best score \(\eta\) computed exactly as above, crowding penalty included, with a 10 % chance of a random pick.

Surrogate-guided versus random search (toy problem)

Top: the true F1 landscape (brighter is better; the white circle marks the best point for an unlimited budget) and the configurations each strategy trained. Middle: the trained networks in the size versus F1 plane, with the true Pareto front dashed. Bottom: the “gap”, the F1 lost compared with the true front, averaged over hardware budgets from 2,000 to 81,000 parameters (0 means the front has been found). What to try: press Run and compare the two gap curves; then press “Average 30 searches” to remove the luck of a single run. Set N to 2 (the surrogate barely chooses: the advantage disappears) or the noise to 0.08 (very noisy trainings: the advantage shrinks).

Trainings
0
Gap, random
…
Gap, surrogate
…
Trainings to gap ≤ 0.03 (avg)
…
A toy for intuition only: not Portiloop data, not the real surrogate.

What the toy shows (averages over 40 seeds with the default settings, measured while building this page): during the first ten trainings the guided search is no better than random, because the surrogate has almost nothing to learn from and the crowding penalty forces exploration. After about 20 trainings it pulls ahead: with N = 50 its gap after 30 trainings (about 0.03) is roughly half that of random search (about 0.06), and random search has still not reached it after 60 trainings. With very noisy trainings the surrogate is misled more often. The real search space has 10 dimensions instead of 2, where blind sampling generally needs many more trainings to stumble on good regions, but the paper's remark about near-constant predictions is a reminder that the surrogate is only as good as the reproducibility of the trainings it learns from.

Step 5 and 6: training and bookkeeping

        best_loss, best_f1_score, exp["best_epoch"] = run(exp["config_dict"], f"{WANDB_PROJECT_PARETO}_runs_{PARETO_ID}", save_model=False, unique_name=True)
        exp["cost_software"] = 1 - best_f1_score if MAXIMIZE_F1_SCORE else best_loss

        pareto_front = update_pareto(exp, pareto_front)
        all_experiments.append(exp)

The selected configuration is trained by the same run() function as in tutorial 05, with save_model=False: no checkpoint is kept during the search, only the score. The software cost is \(1 - \) the best validation F1 reached during that training. The experiment is added to the front if no front member is at least as good on both costs, and the surrogate is retrained. After every iteration the two lists are pickled and a W&B plot of the front is logged.

Before you run: what is hard-coded

Nothing in PMBO is configured from the command line except the log file and, for the distributed version, the role and the server address. Everything else is a constant in the source. Check each line of this table.

ConstantFileValueWhat it controls
PARETO_ID, RUN_NAMEPMBO/pareto_search.py"tests", "pareto_search_tests"Name of the search: pickle file names, W&B run id, experiment names (RUN_NAME + "_" + number). Change it for every new search, or the old pickles are loaded and continued.
WANDB_PROJECT_PARETOpareto_search.py"pareto-public"W&B project of the search log. Each trained candidate is logged in the project pareto-public_runs_tests (f"{WANDB_PROJECT_PARETO}_runs_{PARETO_ID}").
MAX_META_ITERATIONSpareto_search.py1000Number of networks trained by the local search. The distributed meta-learner has no limit.
NB_SAMPLED_MODELS_PER_ITERATIONpareto_search.py200Candidates scored per selection (\(m\) in the paper).
META_MODEL_DEVICEpareto_search.py"cpu"Device for the surrogate (small; CPU is fine).
START_META_TRAIN_VAL_AFTER, META_TRAIN_VAL_RATIO, MAX_META_EPOCHS, META_EARLY_STOPPINGpareto_search.py100, 0.8, 500, 30Surrogate training (see Step 3). DEFAULT_META_EPOCHS and THRESHOLD = 0.2 in this file are not used.
path_dataset, path_paretopareto_search.pyportiloop_software/dataset, portiloop_software/paretoDerived from the file location. Commented lines show how the authors pointed them to Google Drive in Colab.
MIN_NB_PARAMETERS, MAX_NB_PARAMETERSUtils/utils.py1,000, 80,000Hardware range; candidates outside are discarded. Also sets the range of the crowding histogram.
MAX_EPOCHS_PER_EXPERIMENT, NB_BATCH_PER_EPOCH, NETWORK_EARLY_STOPPINGUtils/utils.py150, 1000, 20Training budget of each candidate: the main driver of the total cost.
EPSILON_NOISE, EPSILON_EXP_NOISEUtils/utils.py0.25, 0.1The two exploration probabilities.
*_range_tUtils/utils.pysee table aboveThe search space. To search over the envelope input, for example, set envelope_input_range_t = [0, 1, 1] (and uncomment int(config_dict['envelope_input']) in transform_config_dict_to_input(), then change nb_features = 10 in SurrogateModel to 11).
MAXIMIZE_F1_SCORE, PROFILE_METAUtils/utils.pyTrue, FalseSoftware cost is \(1 - F_1\) (False: validation loss). Profiling of the meta-learner with pyinstrument.
fixed keys in sample_config_dict()Utils/utils.pydevice_train = "cuda:0", ...Every candidate trains on cuda:0: a GPU is mandatory (run() asserts it). Use CUDA_VISIBLE_DEVICES to choose the physical GPU.
PHASE, TEST_SET, THRESHOLDANN/portiloop_detector_training.py (import branch)'full', True, 0.5Because the training module is imported, its else: branch applies: MODA phases 1 and 2, a test set is held out, labels are binarized at 0.5 (0.2 when the training script is run from the command line; identical if your classification labels are strictly 0 or 1). Dataset files as in tutorial 05.
IP_SERVER, PORT_META, PORT_WORKER, LEN_QUEUE_TO_LAUNCHPMBO/pareto_network_server_utils.pyan IP address of the original authors, 6666, 6667, 20Distributed mode only: default server address (override it with --ip_server), TCP ports, and size of the queue of selected configurations waiting for a worker.
Older clones: one required keyrun() reads config_dict["validation_network_stride"]. sample_config_dict() now sets it (config_dict["validation_network_stride"] = 1 # required by run()); in clones older than November 2026 it did not, and the search stopped at its first training with KeyError: 'validation_network_stride'. Run git pull if you see that error.

Rehearse the search without a GPU

A real search costs days of GPU time, so make sure the machinery works first. The script below runs the genuine PMBO loop (sampling, size filter, surrogate, selection, pickles) but replaces the training function by a fake one that returns a made-up F1 instantly. It needs neither the dataset nor a GPU, and it writes to a temporary folder.

  1. Install the requirements (tutorial 02, pip install -e . from the repository root, which also installs wandb).
  2. Save this file at the repository root as rehearse_pareto.py:
    # rehearse_pareto.py: exercise the PMBO loop without training any network.
    # Run from the repository root:  WANDB_MODE=disabled python3 rehearse_pareto.py
    import logging
    import random
    import tempfile
    from pathlib import Path
    
    import portiloop_software.portiloop_python.PMBO.pareto_search as ps
    
    logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG)
    for noisy in ("matplotlib", "PIL"):
        logging.getLogger(noisy).setLevel(logging.WARNING)
    
    
    def fake_run(config_dict, wandb_project, save_model, unique_name):
        """Stands in for run(): returns (best validation loss, best F1, best epoch) without training."""
        n = ps.nb_parameters(config_dict)
        f1 = min(0.75, 0.45 + 0.06 * (n / 10000) ** 0.5) + random.gauss(0, 0.02)
        return 1 - f1, f1, 0
    
    
    ps.run = fake_run                          # never touches the dataset or the GPU
    ps.MAX_META_ITERATIONS = 15                # 15 fake "trainings"
    ps.path_pareto = Path(tempfile.mkdtemp())  # keep the real pareto/ folder clean
    ps.iterative_training_local()
    print("pickles written to", ps.path_pareto, sorted(p.name for p in ps.path_pareto.iterdir()))
  3. Run it with W&B disabled (no account needed; WANDB_MODE=offline also works and keeps the search plot in ./wandb/):
    WANDB_MODE=disabled python3 rehearse_pareto.py 2>&1 | grep -v "^score" | tee rehearse.log
    It took two to four minutes on the CPU used to write this tutorial, for 15 iterations (most of the time goes into building 200 candidate networks per iteration to count their parameters). The grep hides the three score ... lines that pareto_efficiency() prints for every candidate. Expected output (numbers differ at every run, configurations shortened here):
    DEBUG: DEBUG: no meta dataset found, starting new run
    DEBUG: ---
    DEBUG: ITERATION N° 0
    DEBUG: config: {'experiment_name': 'pareto_search_tests_0', 'device_train': 'cuda:0', ...}
    DEBUG: nb parameters: 39227
    DEBUG: predicted cost: 5.542581081390381
    DEBUG: training...
    DEBUG: actual cost: 0.4187577551505618
    DEBUG: surprise: -5.123823326239819
    DEBUG: training new surrogate model...
    DEBUG: surrogate model loss: 36.187721252441406
    DEBUG: ---
    DEBUG: ITERATION N° 1
    DEBUG: DEBUG: selected 36339: efficiency:2.0143841196674344, nerf:0.0
    DEBUG: config: {'experiment_name': 'pareto_search_tests_1', 'device_train': 'cuda:0', ...}
    DEBUG: nb parameters: 36339
    DEBUG: predicted cost: -29.112504959106445
    ...
    DEBUG: End of meta-training.
    pickles written to /tmp/tmpqcxttqqx ['pareto_search_tests_finished.pkl', 'pareto_search_tests_pareto.pkl']
    How to read it: nb parameters is the hardware cost of the selected candidate; predicted cost is the surrogate's \(1 - F_1\) estimate; actual cost is \(1 - F_1\) returned by training; surprise is actual minus predicted; selected ...: efficiency ..., nerf ... gives \(\eta\) before the crowding penalty and the penalty itself (0 means the chosen size bin had never been tried). Iteration 0 has no “selected” line because the front is still empty, so the choice is random. A UserWarning about pin_memory on CPU-only machines is harmless.

Running a real search on one machine

  1. Prepare the data and a GPU. The MODA dataset files must be in portiloop_software/dataset/ (tutorial 02), and a single training from tutorial 05 should already work on this machine.
  2. Update your clone (git pull; the fixes described in the “Older clones” notes date from November 2026), and go through the table of hard-coded constants (at least PARETO_ID, the parameter range, the training budget).
  3. Choose how to log. With an account: wandb login (set WANDB_ENTITY to log into a team). Without one: WANDB_MODE=offline keeps the search plot and every candidate's learning curves in ./wandb/ (upload later with wandb sync), or WANDB_MODE=disabled records nothing (the pickles are still written). In clones older than November 2026, offline mode stopped every training with UsageError: No API key configured (raised by the W&B restore step of run(), which now ignores that error); git pull if you see it.
  4. Launch from the repository root, in a session that survives logout (tmux, screen, or a SLURM job):
    python3 -m portiloop_software.portiloop_python.PMBO.pareto_search --output_file pareto_tests.log
    --output_file sends the log to a file (otherwise it goes to the terminal). Each iteration trains one network for up to 150 epochs of 1,000 batches, so expect hours per iteration on one GPU. The search can be interrupted and restarted: at start-up it reloads the pickles of the same RUN_NAME (log line existing meta dataset loaded), retrains the surrogate and continues.

Distributed search: server, meta-learner, workers

This is the “parallel” in PMBO, the setup the paper used on 20 GPUs. pareto_network.py has three roles, chosen by a flag:

    parser.add_argument('--server', action='store_true')
    parser.add_argument('--meta', action='store_true')
    parser.add_argument('--worker', action='store_true')
    parser.add_argument('--output_file', type=str, default=None)
    parser.add_argument('--ip_server', type=str, default=IP_SERVER)
Security: run the distributed search only on a network you trust

The three roles exchange Python pickles over plain TCP, with no password, no encryption and no check of who is connecting. Every message is decoded with pickle.loads:

    send_ack(sock)
    return pickle.loads(msg)

Decoding a pickle can execute arbitrary code. Anyone who can open a connection to the server's ports can therefore run programs on the server, and through the server on the meta-learner and on every worker, which decode the server's messages the same way. The server listens on all network interfaces of its machine (it binds to the empty address ''), on TCP ports 6666 and 6667.

  • Use a private network you control (an isolated cluster network, a lab network or a VPN). Never expose ports 6666 and 6667 to the internet, nor to a shared network with users you do not trust (a campus network, a multi-user login node).
  • Close the ports to everyone else. For example, with ufw on the server, allow only your own subnet, then deny the rest:
    sudo ufw allow from 10.0.0.0/24 to any port 6666:6667 proto tcp
    sudo ufw deny 6666:6667/tcp
  • Machines on different networks: use an SSH tunnel instead of opening the ports. With the ports closed to the outside as above, run on each meta-learner and worker machine:
    ssh -N -L 6666:localhost:6666 -L 6667:localhost:6667 you@server-address
    then start the role with --ip_server 127.0.0.1. The traffic travels encrypted inside SSH and reaches the server on its loopback interface, so only people with an SSH account on the server can connect.
  • The result files are pickles too. Only load .pkl files from portiloop_software/pareto/ (for example with inspect_pareto.py below) if you produced them yourself.
  1. Start the server on a machine reachable by all others (ports 6666 and 6667 reachable from your own machines only, see the security warning above):
    cd /path/to/portiloop-training
    python3 portiloop_software/portiloop_python/PMBO/pareto_network.py --server --output_file server.log
  2. Start the meta-learner (one, anywhere; CPU is enough), giving the server address:
    python3 portiloop_software/portiloop_python/PMBO/pareto_network.py --meta --ip_server 10.0.0.5 --output_file meta.log
  3. Start one worker per GPU on machines that have the dataset:
    CUDA_VISIBLE_DEVICES=0 python3 portiloop_software/portiloop_python/PMBO/pareto_network.py --worker --ip_server 10.0.0.5 --output_file worker0.log
    CUDA_VISIBLE_DEVICES=1 python3 portiloop_software/portiloop_python/PMBO/pareto_network.py --worker --ip_server 10.0.0.5 --output_file worker1.log
    Replace 10.0.0.5 by your server's address. Workers can join at any time and reconnect automatically after a connection loss; a worker stopped in the middle of a training loses that experiment (the meta-learner does not re-queue it).
Warnings for the distributed mode
  • Run it as a script, not with python -m. pareto_network.py imports its neighbours as top-level modules (from pareto_network_server_utils import ..., from pareto_search import ...), which only works when the script's own folder is on the import path. With python3 -m portiloop_software...pareto_network it fails with ModuleNotFoundError: No module named 'pareto_network_server_utils' (checked). The package itself must be installed (pip install -e .).
  • Extra dependencies: requests and pyinstrument (both in setup.py).
  • Internet access: every role calls http://api.ipify.org (an external service) at start-up to print its public IP address, which also tells that service the machine is running; on a cluster node without internet access this call fails. Remove the self.public_ip = get(...) lines if needed.
  • Security: see the warning above before starting any role.
  • Pickle and W&B files are written by the meta-learner only, in its own portiloop_software/pareto/.
Duplicate resultsIf the meta-learner receives a result for a configuration it already has (rare, since same_config_dict() rejects duplicates when sampling), it keeps the better of the two software costs and updates the front with that experiment. Clones older than November 2026 crashed on this path (misspelled key "software_cost"); git pull fixes it.

Files, results and W&B

On the hard drive
  • portiloop_software/pareto/pareto_search_<PARETO_ID>_finished.pkl: Python list with one dictionary per trained network, keys config_dict (the full configuration, ready for run()), cost_hardware (parameters), cost_software (\(1 - F_1\) on validation), unrounded (the continuous values behind the sampled grid values, used for Gaussian sampling), best_epoch, plus surprise in distributed mode.
  • portiloop_software/pareto/pareto_search_<PARETO_ID>_pareto.pkl: the subset on the Pareto front, sorted by software cost (best F1 first). Both files are rewritten after every training.
  • No network weights: candidates are trained with save_model=False.
  • W&B: project pareto-public, run id pareto_search_<PARETO_ID>, logs surrogate_loss, surprise and pareto_plot (all experiments in blue, front in red, last experiment in green) after every result; project pareto-public_runs_<PARETO_ID> has one run per candidate with its training curves. Local W&B files go to ./wandb/.
  • pareto_viewer.py writes pareto_plot_<PARETO_ID>.pdf, ..._lowest_hardware.pdf and ..._lowest_software.pdf into portiloop_software/dataset/.
  1. Summarize the front with this script (tested on the files written by the rehearsal; pass the folder as argument, and change run_name if you changed PARETO_ID):
    # inspect_pareto.py: summarize a PMBO run (run from the repository root)
    import pickle
    import sys
    from pathlib import Path
    
    import pandas as pd
    
    folder = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("portiloop_software/pareto")
    run_name = "pareto_search_tests"  # RUN_NAME = "pareto_search_" + PARETO_ID
    with open(folder / f"{run_name}_finished.pkl", "rb") as f:
        finished = pickle.load(f)
    with open(folder / f"{run_name}_pareto.pkl", "rb") as f:
        front = pickle.load(f)
    
    print(len(finished), "experiments,", len(front), "on the Pareto front")
    print("keys of one experiment:", sorted(finished[0].keys()))
    rows = [dict(n_parameters=e["cost_hardware"], f1=1 - e["cost_software"],
                 **{k: e["config_dict"][k] for k in ("nb_conv_layers", "nb_channel", "kernel_conv", "kernel_pool",
                                                     "window_size_s", "seq_stride_s", "hidden_size", "nb_rnn_layers",
                                                     "lr_adam", "batch_size")})
            for e in front]
    print(pd.DataFrame(rows).sort_values("n_parameters").to_string(index=False))
    Output on the rehearsal files (fake F1 values; the first lines):
    15 experiments, 5 on the Pareto front
    keys of one experiment: ['best_epoch', 'config_dict', 'cost_hardware', 'cost_software', 'unrounded']
     n_parameters       f1  nb_conv_layers  nb_channel  kernel_conv  kernel_pool  window_size_s  seq_stride_s  hidden_size  nb_rnn_layers  lr_adam  batch_size
             1287 0.494525               4           1            9            9          0.458         0.130            7              1   0.0003         192
             3771 0.526260               5           1            5           11          0.354         0.074           17              2   0.0003          64
    ...
  2. Plot with the authors' viewer (optional). pareto_viewer.py is a script without arguments; it imports pareto_search as a top-level module, so run it by path: python3 portiloop_software/portiloop_python/PMBO/pareto_viewer.py. It prints the best network, saves the PDFs listed above and opens a window (plt.show()). It needs at least 5 networks on the front (it highlights pareto_front[-5]), and its third figure overwrites the file name of the second one (both are called ..._lowest_software.pdf).
  3. Check the surrogate (optional). pareto_trainer.py (also run by path) retrains a surrogate on all finished experiments but four random ones, prints predicted versus real cost for those four, and predictions for three random new configurations. It is a quick sanity check of how well the surrogate generalizes.
  4. Pick and retrain. Choose a configuration on the front that fits your hardware budget, copy its config_dict, give it a new experiment_name, adjust devices and training budget, and train it with checkpoints as in tutorial 05. Re-evaluate it on the test set (tutorial 06): the F1 seen during the search is a single training on the validation set, and trainings vary. Then export it (tutorial 10).
Troubleshooting
  • KeyError: 'validation_network_stride' at the first training: your clone predates the fix; git pull.
  • AssertionError: CUDA unavailable: no GPU visible; the devices are hard-coded to cuda:0.
  • FileNotFoundError on dataset_classification_full_big_250_matlab_standardized_envelope_pf.txt or subject_sequence_full_big.txt: the dataset is not installed (tutorial 02).
  • The log is flooded with score dominating lines: these are print() calls in pareto_efficiency(), 600 lines per iteration; filter them with grep -v.
  • A new search “remembers” old results: the pickles of the same PARETO_ID were found and reloaded. Change PARETO_ID or move the old files.

What the search found in the paper

Everything in this section is quoted from Valenchon et al. (2022) [1]; the repository does not contain the search logs.

The names of the shipped checkpoints, pareto_search_15_35_v4_<i>, follow the naming pattern of the search code (RUN_NAME + "_" + number), but the repository does not document what “15”, “35” and “v4” refer to.

Exercises

Dominated or not?

Three trained networks: A has 12,000 parameters and F1 = 0.66; B has 30,000 parameters and F1 = 0.70; C has 25,000 parameters and F1 = 0.64. Which are on the Pareto front? Which would you deploy on a device that holds at most 20,000 parameters? And at most 40,000?

Answer

C is dominated by A (fewer parameters and higher F1). A and B are on the front: neither is both smaller and better than the other. Budget 20,000: only A fits. Budget 40,000: B (best F1 within budget), unless the 4-point F1 difference is within the training-to-training variability, in which case A's lower cost (and faster forward pass) may be the wiser choice.

Compute the crowding penalty

After 50 completed experiments, 5 have between 24,000 and 24,799 parameters. A candidate has 24,500 parameters. What penalty \(h\) does exp_max_pareto_efficiency() subtract from its score, and what does that mean for its chances?

Answer

The bins are 800 parameters wide (80,000 / 100); this candidate is in the bin 24,000 to 24,799. The density is \(5 / (50 \times 800)\), multiplied by 80,000: \(h = 100 \times 5/50 = 10\). Since the other three terms are of order 1 (unless the predicted cost is near 0), a candidate in an empty bin (\(h = 0\)) will almost always be preferred: the search deliberately spreads its trainings over model sizes.

Plan a search for your hardware

Your embedded board can hold at most 15,000 parameters, and you want to know whether the envelope input helps at that size. List the edits you would make before launching.

Answer

In Utils/utils.py: MAX_NB_PARAMETERS = 15000; envelope_input_range_t = [0, 1, 1]; possibly reduce MAX_EPOCHS_PER_EXPERIMENT to save time. In pareto_search.py: a new PARETO_ID; uncomment int(config_dict['envelope_input']) in transform_config_dict_to_input() and set nb_features = 11 in SurrogateModel so the surrogate can tell the two kinds of networks apart. Note that the 2-input branch doubles the convolutional and GRU parameters (tutorial 04), so under a 15,000 budget the 2-input networks must be much narrower. Then rehearse with the fake trainer before using GPUs.

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 to 7 and from the supporting information S1 File (Appendices C, D and J).
  2. Yin Z, Gross W, Meyer BH (2020). Probabilistic sequential multi-objective optimization of convolutional neural networks. 2020 Design, Automation & Test in Europe Conference & Exhibition (DATE), 1055 to 1060 (as cited in S1 File). DATE 2020 proceedings archive.