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.
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.
Two costs and the Pareto front
PMBO minimizes two costs. In the words of the supplementary material (S1 File, Appendix J) [1]:
- Software cost: “We cast this into a minimization problem by defining our software cost as \(L_s = 1 - f_1\).” Here \(f_1\) is the F1 score of the trained network on the validation set (tutorial 06).
- Hardware cost: “we use the number of trainable weights in the ANN as a proxy for these concerns, and call this number our hardware cost \(L_h\).” (The text explains that true memory use and execution time are only known after the model is synthesized on the board, “a lengthy process”.)
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.”
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.
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.
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.
| Hyperparameter | Range triple | Values actually sampled | Published | Comment |
|---|---|---|---|---|
nb_ | [1, 5, 1] | 1, 2, 3, 4, 5 | 3 | |
nb_ | [1, 100, 5] | 1, 6, 11, ..., 96, 100 (21 values) | 31 | Grid is offset by 1; 101 is clipped to 100. |
kernel_, kernel_ | [3, 11, 2] | 5, 7, 9, 11 | 7, 7 | 3 is never sampled (Python rounds 1.5 to 2, banker's rounding, so the grid starts one step too high). |
window_ | [0.05, 0.5, 0.008] | 0.050, 0.058, ..., 0.498 (57 values) | 0.218 | 12 to 124 samples. |
seq_ | [0.05, 0.2, 0.008] | 0.050, 0.058, ..., 0.194, 0.200 (20 values) | 0.170 | The paper's “time dilation”, 12 to 50 samples. |
hidden_ | [2, 100, 5] | 2, 7, 12, ..., 97, 100 (21 values) | 7 | |
nb_ | [1, 2, 1] | 1, 2 | 1 | |
lr_ | [0.0003, 0.0009, 0.0002] | 0.0003, 0.0005, 0.0007, 0.0009 | 0.0005 | |
batch_ | [64, 256, 64] | 64, 128, 192, 256 | 256 | |
seq_ | [50, 50, 1] | 50 | 50 | Fixed (set to 1 if RNN were off). |
RNN, envelope_ | [1, 1, 1], [0, 0, 1] | True, False | True, False | Fixed: always a GRU, never the envelope branch. |
| strides, dilations | [1, 1, 1] | 1 | 1 | Fixed. |
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
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.
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:
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
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.
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.
| Constant | File | Value | What it controls |
|---|---|---|---|
PARETO_, RUN_ | PMBO/ | "tests", "pareto_ | 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_ | pareto_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_ | pareto_search.py | 1000 | Number of networks trained by the local search. The distributed meta-learner has no limit. |
NB_ | pareto_search.py | 200 | Candidates scored per selection (\(m\) in the paper). |
META_ | pareto_search.py | "cpu" | Device for the surrogate (small; CPU is fine). |
START_, META_, MAX_, META_ | pareto_search.py | 100, 0.8, 500, 30 | Surrogate training (see Step 3). DEFAULT_META_EPOCHS and THRESHOLD = 0.2 in this file are not used. |
path_, path_ | pareto_search.py | portiloop_, portiloop_ | Derived from the file location. Commented lines show how the authors pointed them to Google Drive in Colab. |
MIN_, MAX_ | Utils/ | 1,000, 80,000 | Hardware range; candidates outside are discarded. Also sets the range of the crowding histogram. |
MAX_, NB_, NETWORK_ | Utils/ | 150, 1000, 20 | Training budget of each candidate: the main driver of the total cost. |
EPSILON_, EPSILON_ | Utils/ | 0.25, 0.1 | The two exploration probabilities. |
*_ | Utils/ | see table above | The 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_, PROFILE_ | Utils/ | True, False | Software cost is \(1 - F_1\) (False: validation loss). Profiling of the meta-learner with pyinstrument. |
fixed keys in sample_ | Utils/ | device_, ... | Every candidate trains on cuda:0: a GPU is mandatory (run() asserts it). Use CUDA_VISIBLE_DEVICES to choose the physical GPU. |
PHASE, TEST_, THRESHOLD | ANN/ (import branch) | 'full', True, 0.5 | Because 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_, PORT_, PORT_, LEN_ | PMBO/ | an IP address of the original authors, 6666, 6667, 20 | Distributed mode only: default server address (override it with --ip_server), TCP ports, and size of the queue of selected configurations waiting for a worker. |
run() 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.
- Install the requirements (tutorial 02,
pip install -e .from the repository root, which also installswandb). - 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())) - Run it with W&B disabled (no account needed;
WANDB_MODE=offlinealso works and keeps the search plot in./wandb/):
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). TheWANDB_MODE=disabled python3 rehearse_pareto.py 2>&1 | grep -v "^score" | tee rehearse.loggrephides the threescore ...lines thatpareto_efficiency()prints for every candidate. Expected output (numbers differ at every run, configurations shortened here):
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. ADEBUG: 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']UserWarningaboutpin_memoryon CPU-only machines is harmless.
Running a real search on one machine
- 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. - 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 leastPARETO_ID, the parameter range, the training budget). - Choose how to log. With an account:
wandb login(setWANDB_ENTITYto log into a team). Without one:WANDB_MODE=offlinekeeps the search plot and every candidate's learning curves in./wandb/(upload later withwandb sync), orWANDB_MODE=disabledrecords nothing (the pickles are still written). In clones older than November 2026, offline mode stopped every training withUsageError: No API key configured(raised by the W&B restore step ofrun(), which now ignores that error);git pullif you see it. - 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_filesends 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 sameRUN_NAME(log lineexisting 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)
- The server only relays messages. It listens on TCP port 6666 for the meta-learner and 6667 for workers, keeps a queue of up to
LEN_QUEUE_TO_LAUNCH= 20 selected configurations, hands one to each idle worker and forwards finished results to the meta-learner. - The meta-learner owns the pickles, the surrogate and the W&B log. Whenever the server asks for work or sends results, it updates the front, retrains the surrogate and selects one new configuration (Steps 1 to 4).
- Each worker trains the configuration it receives with
run()(Step 5) and sends back the result, including thesurprise.
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
ufwon 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:
then start the role withssh -N -L 6666:localhost:6666 -L 6667:localhost:6667 you@server-address--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
.pklfiles fromportiloop_software/pareto/(for example withinspect_pareto.pybelow) if you produced them yourself.
- 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 - 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 - Start one worker per GPU on machines that have the dataset:
ReplaceCUDA_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.log10.0.0.5by 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).
- Run it as a script, not with
python -m.pareto_network.pyimports 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. Withpython3 -m portiloop_software...pareto_networkit fails withModuleNotFoundError: No module named 'pareto_network_server_utils'(checked). The package itself must be installed (pip install -e .). - Extra dependencies:
requestsandpyinstrument(both insetup.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 theself.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/.
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
portiloop_software/pareto/pareto_search_<PARETO_ID>_finished.pkl: Python list with one dictionary per trained network, keysconfig_dict(the full configuration, ready forrun()),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, plussurprisein 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 idpareto_search_<PARETO_ID>, logssurrogate_loss,surpriseandpareto_plot(all experiments in blue, front in red, last experiment in green) after every result; projectpareto-public_runs_<PARETO_ID>has one run per candidate with its training curves. Local W&B files go to./wandb/. pareto_viewer.pywritespareto_plot_<PARETO_ID>.pdf,..._lowest_hardware.pdfand..._lowest_software.pdfintoportiloop_software/dataset/.
- Summarize the front with this script (tested on the files written by the rehearsal; pass the folder as argument, and change
run_nameif you changedPARETO_ID):
Output on the rehearsal files (fake F1 values; the first lines):# 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))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 ... - Plot with the authors' viewer (optional).
pareto_viewer.pyis a script without arguments; it importspareto_searchas 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 highlightspareto_front[-5]), and its third figure overwrites the file name of the second one (both are called..._lowest_software.pdf). - 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. - Pick and retrain. Choose a configuration on the front that fits your hardware budget, copy its
config_dict, give it a newexperiment_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).
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 tocuda:0.FileNotFoundErrorondataset_classification_full_big_250_matlab_standardized_envelope_pf.txtorsubject_sequence_full_big.txt: the dataset is not installed (tutorial 02).- The log is flooded with
score dominatinglines: these areprint()calls inpareto_efficiency(), 600 lines per iteration; filter them withgrep -v. - A new search “remembers” old results: the pickles of the same
PARETO_IDwere found and reloaded. ChangePARETO_IDor 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.
- Scale of the final search: “we run PMBO on 20 Tesla V100 GPU workers over a period of 24h.” The PMBO settings (supplementary Table I) were a hardware range of 1000-80000, noise type 1 of 0.25, noise type 2 of 0.1, \(m = 200\), and a 3-layer MLP meta network of hidden size 200 trained with SGD (learning rate 0.05, weight decay 0.01): the values found in the current code.
- Choice of the model: “We select the best model in terms of software cost (i.e. the one with the highest classification performance) irrespective of its hardware cost i.e., the model corresponding to the right-hand end of the Pareto front. This model is acceptable because it is anyway rather small, with only 25.6k parameters. We measure the execution time of this architecture to be 20 ms per forward pass on the Portiloop (vs. 40 ms for the 2-input version).”
- The time between windows of one memory chain was chosen by the search: “the time-dilation (set to 168 ms by PMBO)”. Supplementary Table II marks batch size, learning rate, window size, time dilation and all architecture hyperparameters as chosen by PMBO.
- A first search (with the envelope as a second input) produced the 2-input model; an ablation then showed that the envelope could be dropped, and PMBO was run “one more time to devise our final Pareto-optimal ANN architecture, now with only the cleaned signal as input.”
- Limits: “the predictions of the meta-learner are often near-constant in well-performing areas of the search space, suggesting that the meta-model could not further predict the software cost. In other words, we were unable to differentiate between the best-performing configurations of the neural network.” The supplementary Fig 1 caption adds that part of each window is ignored by the model, “Therefore, it is probably possible to shrink our model even more, although PMBO did not find this.”
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
- 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).
- 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.