Training a new model
Run the reference training of the Portiloop spindle detector, understand what happens in every epoch (sampling, loss, validation, model selection, early stopping), find the files it writes, and train your own variant on a workstation or on a SLURM cluster.
In this tutorial you will
- Launch the reference training from the command line and know what every flag does.
- Understand, in experimental terms, how training examples are built and drawn, how the loss is computed and how the "best" model is chosen.
- Train a toy spindle detector in your browser and watch the learning curves.
- Know which files are written where, and what resuming really does.
- Train your own variant with a small, tested script, on your machine or on a cluster.
portiloop_software/portiloop_python/ANN/portiloop_detector_training.py. Code excerpts on this page are copied from it verbatim (line numbers refer to the current main branch). If your clone is older than the ONNX export commit, run git pull first: several behaviours described here were fixed recently (saving of the best model, the onnx dependency, W&B offline mode, max_duration, run names, the checkpoint contents and LDS).1. Before you start
- Install the package in editable mode (tutorial 02). From the repository root:
This installs PyTorch,pip install -e .wandb,scikit-learn(used for the subject split) andonnx(used to export the best model during training). Without this step, running the training script fails immediately withModuleNotFoundError: No module named 'portiloop_software', because the script imports its helpers through the package name. - Put the dataset in place. The training reads its data from
portiloop_software/dataset/, a path computed from the location of the script itself:
For the default run (phasepath_dataset = Path(__file__).absolute().parent.parent.parent / 'dataset'full, classification) you need these four files of the practice dataset (dataset.zipor the generator, tutorial 02), or of your own data converted to the same format:dataset_classification_full_big_250_matlab_standardized_envelope_pf.txt(the EEG, its envelope, a power-features ratio and the label, 4 comma-separated columns, 250 Hz);subject_sequence_full_big.txt,subject_sequence_p1_big.txt,subject_sequence_p2_big.txt(one line per subject: subject ID, first segment, end segment, exclusive).
dataset_regression_full_big_250_matlab_standardized_envelope_pf.txtinstead. - Check your GPU. The published configuration trains and validates on
'cuda':
If this printspython -c "import torch; print(torch.cuda.is_available(), torch.cuda.device_count())"False, the reference command stops at the very beginning ofrun()with
raised by these lines:AssertionError: CUDA unavailableif device_val.startswith("cuda") or device_train.startswith("cuda"): assert torch.cuda.is_available(), "CUDA unavailable"
Choosing the device (GPU or CPU)
Three keys of the configuration dictionary control where computations happen:
| Key | Published value | Used for |
|---|---|---|
device_train | 'cuda' | The network and every training batch (forward pass, loss, gradient step). |
device_val | 'cuda' | The validation pass at the end of each epoch (run_inference). |
device_inference | 'cpu' | Only for loading a trained model afterwards (get_trained_model, tutorials 08 and 09); not used by training. |
Valid values are any PyTorch device string: 'cuda' (first GPU), 'cuda:1' (second GPU), or 'cpu'. The command-line entry point has no flag for this; either edit get_final_model_config_dict() or, better, use the small script of section 7, which has a --device option.
2. Set up Weights & Biases (W&B)
The training logs its learning curves to Weights & Biases, a web service that plots metrics while the job runs (useful when the job is on a cluster). The logger is created at the start of run():
# Credentials come from your own W&B login (`wandb login`) or the WANDB_API_KEY environment variable.
# Runs go to your default W&B entity unless WANDB_ENTITY is set (e.g. to a lab team name).
# Without an account: WANDB_MODE=offline (curves saved locally in ./wandb, upload later with `wandb sync`)
# or WANDB_MODE=disabled (nothing recorded).
self.wandb_run = wandb.init(project=project_name, entity=os.environ.get("WANDB_ENTITY"), id=experiment_name,
resume="allow", config=c_dict, reinit=True)
- Create a free account at wandb.ai, then log in once on the machine that trains:
The key is stored inwandb login # paste the API key shown on https://wandb.ai/authorize~/.netrc. On a cluster you can instead exportWANDB_API_KEYin your job script; never commit a key to a repository. - Optional: log to your lab's team.
export WANDB_ENTITY=my-lab-team. Without it, runs go to your personal account. - Know where to look. The project name is
f"{PHASE}-dataset-public", so the reference run appears in projectfull-dataset-public; the run ID is the experiment name (id=experiment_name).
Two modes work without any W&B account (we tested both with wandb 0.31.0, no credentials and an empty home folder):
export WANDB_MODE=offline # curves recorded locally in ./wandb, upload later with `wandb sync`
export WANDB_MODE=disabled # nothing recorded; watch the console instead
In offline mode the run data go to ./wandb/offline-run-<date>_<time>-<experiment name>, and at the end wandb prints the command to upload them once you have an account (wandb sync wandb/offline-run-...), for example from a login node of a cluster whose compute nodes have no internet. Training, checkpoints and ONNX export are identical in all three modes (online, offline, disabled). In offline mode you will also see the harmless debug line W&B restore of ... skipped: UsageError: No API key configured (see resuming).
3. Run the reference training
From the repository root, this command retrains the published architecture on random subject split 0, with a held-out test set:
python portiloop_software/portiloop_python/ANN/portiloop_detector_training.py --phase full --experiment_index 0
Every flag explained
| Flag | Default | What it does |
|---|---|---|
--phase p1|p2|full | full | Which part of the MODA annotations to use. MODA was annotated in two phases: "phase 1 consisted of 100 younger subjects (mean age of 24.1 years old) and phase 2 consisted of 80 older subjects (mean age of 62.0 years old)" [3]. full uses both. The phase selects the data files, the W&B project name and the label threshold THRESHOLD (0.2, 0.35 and 0.2). |
--experiment_index N | 0 | Chooses the subject split: even N gives split 0, odd N gives split 2 (possible_split = [0, 2]). It also sets the default experiment name, sanity_check_final_model_N. |
--test_set / --no_test_set | test set on | With a test set, 80% of subjects train, 10% validate and 10% are kept aside for the final evaluation (tutorial 06). With --no_test_set, the whole 20% is used for validation and _no_test is appended to the name. |
--classification / --regression | classification | Classification learns 0/1 labels with a binary cross-entropy loss; regression learns the graded expert-agreement score with a mean squared error loss (section 8). Regression appends _regression to the name. |
--ablation 0|1|2 | 0 | Input ablation study from the paper (section 8). A non-zero value appends _ablation1 or _ablation2 to the name. |
--output_file PATH | none | Write the log to this file instead of the console (useful on clusters). |
--experiment_name NAME | none | Name of the run: the W&B run ID and the checkpoint file names. Without it, the name is sanity_check_final_model_<experiment_index>. The suffixes below are appended in any case. |
--max_split | 10 | Parsed but unused: only one split is trained per call. |
Here is how the flags are turned into the configuration (lines 1428 to 1441, then line 1450):
possible_split = [0, 2]
split_idx = possible_split[exp_index % 2]
classification = args.classification
TEST_SET = args.test_set
logging.debug(f"classification: {classification}")
config_dict = get_final_model_config_dict(exp_index, split_idx)
if exp_name is not None:
config_dict['experiment_name'] = exp_name
config_dict['distribution_mode'] = 0 if classification else 1
config_dict['classification'] = classification
config_dict['experiment_name'] += "_regression" if not classification else ""
config_dict['experiment_name'] += "_no_test" if not TEST_SET else ""
config_dict['experiment_name'] += f"_ablation{ABLATION}" if ABLATION else ""
seed() # reset the seed
...
run(config_dict=config_dict, wandb_project=WANDB_PROJECT_RUN, save_model=True, unique_name=False)
--experiment_index 0 and 1 get different names (sanity_check_final_model_0 and _1), but the phase is not part of the name: --phase p1 and --phase full with the same index write the same checkpoint files (in different W&B projects). Give such runs their own --experiment_name; a second run with an existing name resumes from, then overwrites, the existing checkpoints (section 6).What you should see
The script sets the root logger to DEBUG, so it prints its own messages and some debug lines from libraries. The excerpt below was captured from a short CPU run (2 epochs of 10 batches) of the script of section 7 on the synthetic practice dataset of tutorial 02, with the root logger set to DEBUG as the command-line entry point does; a full run prints the same lines, with larger numbers and much longer times. The wandb: lines appear only when W&B is enabled.
DEBUG: classification: True <- command line only
DEBUG: config_dict: {'experiment_name': 'smoke_dbg', 'device_train': 'cpu', 'device_val': 'cpu', ...}
wandb: Tracking run with wandb version ... <- when W&B is enabled
DEBUG: W&B restore of smoke_dbg skipped: ... <- online or offline mode
DEBUG: Create new model
DEBUG: Subjects in training : ['syn-p2-001' 'syn-p1-005' 'syn-p2-013' ... ]
DEBUG: Subjects in validation : ['syn-p2-003' 'syn-p2-005' 'syn-p1-008' 'syn-p1-016']
DEBUG: Subjects in test : ['syn-p1-002' 'syn-p2-014' 'syn-p1-020']
DEBUG: total number of spindles in this dataset : 184700
DEBUG: total number of spindles in this dataset : 26372
DEBUG: Validation dataloader batch size: 504
DEBUG: epoch: 0
DEBUG: proba: 0.5
DEBUG: Training time for 1 epoch : 32.70228576660156 s
DEBUG: Validation time for 1 epoch : 43.11477971076965 s
DEBUG: epoch: 1
DEBUG: proba: 0.5
DEBUG: Training time for 1 epoch : 23.826173782348633 s
DEBUG: Validation time for 1 epoch : 34.9319429397583 s
DEBUG: Delete logger
DEBUG: Logger deleted
W&B restore of ... skippedmeans W&B had no checkpoint to give back (normal, see section 6).Create new modelmeans no local checkpoint with this name was found either (Use checkpoint modelotherwise).total number of spindles in this datasetcounts spindle samples (not events), once for the training set and once for the validation set.Validation dataloader batch sizeis 42 times the number of validation segments (explained in section 4.5). It is printed withprint(), so it appears even when logging goes to a file.- Harmless warnings you may also see: a PyTorch warning about
pin_memoryon a CPU-only machine, and a W&B warning that a booleanreinitis deprecated.
In W&B, each epoch logs loss_train, accuracy_train, loss_validation, accuracy_validation, f1_validation, precision_validation, recall_validation and loss_early_stopping; the run summary holds the scores of the two best models (best_model_f1_score_validation, best_model_on_loss_loss_validation, and so on) and best_epoch, best_epoch_early_stopping.
accuracy_train is measured on the class-balanced training batches (about half spindles, section 4.2), whereas accuracy_validation is measured on the natural validation recordings (a small fraction of spindles). The two are not comparable; and validation accuracy is a poor score anyway (tutorial 06). Watch f1_validation and loss_validation.4. What happens inside one epoch
Training a network means adjusting its 25,679 weights so that its output (a number between 0 and 1) is close to 1 during spindles and close to 0 elsewhere. The training loop repeats the same cycle: show the network a batch of examples, measure how wrong it is (the loss), nudge every weight in the direction that reduces the error (a gradient step), and, every 1000 batches, test it on recordings it never trains on (validation).
4.1 The training examples (SignalDataset)
The data file is cut into segments of 145 s; only 115 s of each segment carry labels (the rest, including a 15 s lead-in, has a negative label and is used only as past context). A training example is built around one labeled sample: the network receives a sequence of seq_len = 50 short windows of window_size = 54 samples (216 ms), spaced seq_stride = 42 samples (168 ms) apart, the last window ending exactly on the labeled sample. Its target is the label of that last sample.
# list of indices that can be sampled:
self.indices = [idx for idx in range(len(self.data[0]) - self.window_size) # all possible idxs in the dataset
if not (self.data[3][idx + self.window_size - 1] < 0 # that are not ending in an unlabeled zone
or idx < self.past_signal_len)] # and far enough from the beginning to build a sequence up to here
...
signal_seq = self.full_signal[idx - (self.past_signal_len - self.idx_stride):idx + self.window_size].unfold(0, self.window_size, self.idx_stride)
...
label = torch.tensor(self.data[3][idx + self.window_size - 1], dtype=torch.float)
return signal_seq, envelope_seq, ratio_pf, label
The window length and spacing are given in seconds in the configuration and converted with int(), which truncates: int(0.218 * 250) = 54 and int(0.170 * 250) = 42. The convolutional layers look inside each window; the recurrent layer (GRU) carries information from one window to the next (tutorial 04). One example therefore spans \((50-1)\times 42 + 54 = 2112\) samples, about 8.4 s of EEG.
4.2 Drawing examples: class balancing (RandomSampler)
Spindles are rare: in the paper's words, "only about 5% of the signal is labeled as sleep spindles" [1]. If examples were drawn uniformly, a batch of 256 would contain only about a dozen spindle examples, and a network could reach a low loss by almost always answering "no spindle". The training sampler therefore draws each example from the spindle class or the non-spindle class with probability 0.5, with replacement:
proba = 0.5
if self.distribution_mode == 1:
proba = 1
logging.debug(f"proba: {proba}")
while cur_iter < self.length:
cur_iter += 1
sample_class = np.random.choice([0, 1], p=[1 - proba, proba])
if sample_class: # sample true
idx_file = randint(0, self.nb_true - 1)
idx_res = self.idx_true[idx_file]
else: # sample false
idx_file = randint(0, self.nb_false - 1)
idx_res = self.idx_false[idx_file]
yield idx_res
distribution_mode = 0 (classification) gives this 50/50 balancing. distribution_mode = 1 puts every example in the "true" list (see get_class_idxs) and sets proba = 1: examples are then drawn uniformly, with the natural spindle proportion. Regression requires mode 1. The authors report that "classifiers benefit highly from oversampling (i.e., sampling 50% of spindles and 50% of non-spindles from the dataset during training)" [1].
Note that before the first epoch, get_class_idxs loops over every training example in Python to sort them into the two lists; on the full dataset this takes a noticeable time, and the job looks idle meanwhile.
The lesson of the widget: balancing does not create information, it moves the operating point. The balanced classifier behaves as if spindles were as common as non-spindles, so its 0.5 boundary sits lower: more spindles caught (recall up), more false alarms (precision down). You can recover the other trade-off by changing the threshold afterwards, which is exactly what tutorial 06 does with the real network.
4.3 The loss and the optimizer
For classification the loss is the binary cross-entropy (nn.BCELoss), averaged over the batch. For one example with label \(y \in \{0,1\}\) and network output \(p\):
The weights are updated with AdamW [4] (optim.AdamW(net.parameters(), lr=lr_adam, weight_decay=adam_w)): an adaptive gradient method with learning rate lr_adam = 0.0005 and decoupled weight decay adam_w = 0.01, which slowly shrinks weights that the data do not support. Dropout (dropout = 0.5) sets a random half of the activations after the second and third convolutional layers to zero at every training step (the first layer has no dropout, first_layer_dropout = False), so the network cannot rely on any single feature; dropout is switched off for validation. One gradient step is taken per batch:
optimizer.zero_grad()
if classification:
batch_labels = (batch_labels > THRESHOLD)
batch_labels = batch_labels.float()
output, _, _, _ = net(batch_samples_input1, batch_samples_input2, batch_samples_input3, h1_zero, h2_zero)
output = output.view(-1)
loss = criterion(output, batch_labels)
...
loss = loss.mean()
loss_train += loss.item()
loss.backward()
optimizer.step()
Each training sequence starts with an empty GRU memory (h1_zero): during training, the network only knows the 8.4 s contained in the sequence.
4.4 What an "epoch" means here
Usually an epoch is one pass over the whole training set. Here it is simply nb_batch_per_epoch = 1000 batches of batch_size = 256 sequences, that is 256,000 examples drawn with replacement (self.length = nb_batch * batch_size in RandomSampler). Some examples are seen several times in an epoch, many are not seen at all. "Epoch" here only means "how often we validate".
4.5 Validation: whole recordings, with memory
After the 1000 batches, the network is evaluated on the validation subjects, the way the Portiloop will use it: a window ends on every labeled sample (validation_network_stride = 1), and the GRU state is carried from one window to the next window 42 samples later, across the whole 115 s labeled segment. ValidationSampler builds batches in which each row is one "stream" (one validation segment, one of the 42 possible phase offsets), and successive batches advance every stream by 42 samples:
def __iter__(self):
seed()
batches_per_segment = self.len_segment // self.seq_stride # len sequence = 115 s + add the 15 first s?
cursor_batch = 0
while cursor_batch < batches_per_segment:
for i in range(self.nb_segment):
for j in range(0, (self.seq_stride // self.network_stride) * self.network_stride, self.network_stride):
cur_idx = i * self.len_segment + j + cursor_batch * self.seq_stride
yield cur_idx
cursor_batch += 1
That is why the validation batch size is 42 times the number of validation segments. Inside run_inference, the hidden state returned for one batch is fed into the next (output, h1, h2, max_value = net_copy(..., h1, h2, max_value)), so each stream remembers its own past, exactly like one of the interleaved hidden states of the real-time device (tutorial 08). The validation loss, accuracy, precision, recall and F1 are then computed over every evaluated sample, with the output thresholded at 0.5 (details in tutorial 06).
4.6 Keeping the best models (and their ONNX export)
After each validation, two independent "best so far" checks are made. Each one first updates its record of the best scores, then overwrites its checkpoint:
| Criterion | File written in the dataset folder | ONNX copy |
|---|---|---|
| Highest validation F1 so far | <experiment_name> | <experiment_name>.onnx |
| Lowest validation loss so far | <experiment_name>_on_loss | <experiment_name>_on_loss.onnx |
if f1_validation > best_model_f1_score_validation:
best_model = copy.deepcopy(net)
best_epoch = epoch
best_model_f1_score_validation = f1_validation
best_model_precision_validation = precision_validation
best_model_recall_validation = recall_validation
best_model_loss_validation = loss_validation
best_model_accuracy = accuracy_validation
# torch.save(best_model.state_dict(), path_dataset / experiment_name, _use_new_zipfile_serialization=False)
if save_model:
torch.save({
'epoch': epoch,
'model_state_dict': best_model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'recall_validation_factor': recall_validation_factor,
'precision_validation_factor': precision_validation_factor,
'best_model_on_loss_loss_validation': best_model_on_loss_loss_validation,
'best_model_f1_score_validation': best_model_f1_score_validation,
}, path_dataset / experiment_name, _use_new_zipfile_serialization=False)
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)
updated_model = True
The ONNX export is automatic only for 1-input recurrent models (RNN true, no envelope input, no power-features input), which is the published architecture. It produces a single-step model with inputs x of shape (1, 1, 1, 54) and h (1, 7), outputs y and h_out, opset 11, ready for deployment (tutorial 10). The classification models published with the paper are the F1 files (get_trained_model loads <name> for classification and <name>_on_loss for regression).
4.7 Early stopping and the time limit
The validation loss is noisy from one epoch to the next, so the code smooths it with an exponential moving average (EMA) before deciding to stop. With smoothing factor \(\alpha\) = early_stopping_smoothing_factor = 0.1:
loss_early_stopping = loss_validation if loss_early_stopping is None and early_stopping_smoothing_factor == 1 else loss_validation if loss_early_stopping is None else loss_validation * early_stopping_smoothing_factor + loss_early_stopping * (
1.0 - early_stopping_smoothing_factor)
if loss_early_stopping < best_loss_early_stopping:
best_loss_early_stopping = loss_early_stopping
early_stopping_counter = 0
best_epoch_early_stopping = epoch
else:
early_stopping_counter += 1
...
if early_stopping_counter > nb_epoch_early_stopping_stop or time.time() - _t_run_start > max_duration:
logging.debug("Early stopping.")
break
Training stops when the smoothed loss has not improved for more than nb_epoch_early_stopping_stop epochs (the patience), or after nb_epoch_max = 150 epochs, or when the whole run has lasted more than max_duration = 257,400 s (about 71.5 hours; the clock _t_run_start is set once at the start of run()). Early stopping only decides when to stop; the models you keep are the two checkpoints of section 4.6. With the published patience of 100 and a maximum of 150 epochs, early stopping can only trigger if the smoothed loss stopped improving before about epoch 49. The supplementary table of the paper lists "epochs before early stopping 20" for the final model [1], so the value in the current code (100) differs from the one reported.
5. Try it: train a tiny spindle detector in your browser
This widget runs a complete, miniature version of the training loop in your browser, on synthetic NREM recordings generated and preprocessed with the same filters as the Portiloop (tutorial 03). Six recordings of 60 s are the "training subjects", three others the "validation subjects". Each example is one 54-sample window of standardized EEG, labeled by its last sample (delayed by the 10-sample filter latency). The model is a small two-layer perceptron (54 inputs, 16 hidden units, 1 output), trained with binary cross-entropy and AdamW (weight decay 0.01), with balanced or natural sampling, 40 batches per epoch, and validated on every 5th sample of the validation recordings.
What we observed when testing this widget (seeds fixed, learning rate 0.003, batch 64, 30 epochs): validation F1 at threshold 0.5 rose from about 0.17 after the first epoch to about 0.62 with balanced sampling (precision 0.52, recall 0.76) and about 0.74 with natural sampling (precision 0.93, recall 0.61). After choosing the best threshold on the validation recordings, both reached about 0.75, at a threshold near 0.85 for the balanced model and 0.3 to 0.4 for the natural one. Balancing moved the operating point; the threshold moved it back.
6. On the hard drive, and resuming
- Read:
portiloop_software/dataset/dataset_classification_<phase>_big_250_matlab_standardized_envelope_pf.txt(ordataset_regression_...) and thesubject_sequence_*_big.txtfiles. The whole data file is loaded into memory twice (once for the training set, once for the validation set). - Written, in the same folder
portiloop_software/dataset/:<name>: checkpoint of the best-F1 model (PyTorch file without extension);<name>_on_loss: checkpoint of the lowest-validation-loss model;<name>.onnxand<name>_on_loss.onnx: the same two models exported to ONNX (1-input recurrent models only).
- Written in the current working directory:
wandb/, with one sub-folder per run (logs, config, and, in offline runs, the data to upload later withwandb sync). - Log file: wherever
--output_filepoints, if given.
Each checkpoint is a Python dictionary with seven keys: epoch, model_state_dict (the weights), optimizer_state_dict (AdamW's internal state, needed to resume), recall_validation_factor and precision_validation_factor (the validation recall and precision of that epoch), best_model_f1_score_validation (best validation F1 so far) and best_model_on_loss_loss_validation (lowest validation loss so far). In the best-F1 file, the stored F1 is the F1 of the saved epoch; in the _on_loss file, the stored loss is the loss of the saved epoch (we checked both on a smoke test: the stored best F1 equals the value returned by run()).
import torch
ckpt = torch.load("portiloop_software/dataset/sanity_check_final_model_0", map_location="cpu", weights_only=False)
print(list(ckpt.keys()))
print("saved at epoch", ckpt["epoch"])
Resuming an interrupted run
At the start of run() the code tries to restore a previous run with the same experiment name:
try:
logger.restore(classification)
file_exp = experiment_name
file_exp += "" if classification else "_on_loss"
checkpoint = torch.load(path_dataset / file_exp)
logging.warning(f"Use checkpoint model: resuming from {path_dataset / file_exp} (epoch {checkpoint['epoch']}). Use a new experiment name to start from scratch.")
net.load_state_dict(checkpoint['model_state_dict'])
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
first_epoch = checkpoint['epoch'] + 1
...
except (ValueError, FileNotFoundError):
# net = PortiloopNetwork(config_dict).to(device=device_train)
logging.debug("Create new model")
# LoggerWandb.restore
def restore(self, classif):
name = self.experiment_name if classif else self.experiment_name + "_on_loss"
try:
self.wandb_run.restore(name, root=path_dataset)
except Exception as e: # nothing to restore, no credentials (WANDB_MODE=offline) or no network
logging.debug(f"W&B restore of {name} skipped: {type(e).__name__}: {e}")
What this means in practice:
- First, W&B is asked for a file with the checkpoint's name. The code never uploads checkpoints to W&B (the
wandb_run.savelines inLoggerWandb.logare commented out), so this normally fails; the failure, whatever its cause (no file, no credentials in offline mode, no network), is caught and logged asW&B restore of ... skipped. In disabled mode the call does nothing. - Then the local file
<dataset folder>/<name>is loaded if it exists. This happens in every W&B mode, with a real account too (clones older than November 2026 skipped the local file when an online W&B restore failed, so online runs always started from scratch). Tested in offline mode: a second run with the same name printedWARNING: Use checkpoint model: resuming from .../smoke_off (epoch 1). Use a new experiment name to start from scratch.thenDEBUG: epoch: 2. If you see this line and did not mean to continue an earlier run, stop the job (Ctrl+C) and choose another--experiment_name. - Resuming restarts from the best-F1 checkpoint (from
<name>_on_lossin regression), not from the last epoch; the early-stopping counter and moving average start again from zero; the loop runs anothernb_epoch_maxepochs (range(first_epoch, first_epoch + nb_epoch_max)); and the remembered validation loss of the best-F1 model is not restored, so until F1 improves again the summary reports it as 1.0 (seen in our test).
WARNING: Use checkpoint model line) and then overwrites them, even if you changed hyperparameters such as the learning rate, copy finished models elsewhere, or give each run its own name (unique_name=True appends a nanosecond timestamp to the name, which also disables resuming).7. Train your own variant
To study a variant (another GRU size, fewer filters, another split, the CPU), do not edit the training file: import it, copy the published configuration, change a few keys and call run(). The script docs/tools/train_custom.py does exactly that, with command-line options. Its core:
from portiloop_software.portiloop_python.ANN import portiloop_detector_training as pdt
def make_config(args):
"""Start from the published model and change only what we want to study."""
config = pdt.get_final_model_config_dict(index=0, split_i=args.split)
config["experiment_name"] = args.name
config["hidden_size"] = args.hidden_size # size of the GRU memory (published: 7)
config["nb_channel"] = args.nb_channel # convolution filters per layer (published: 31)
config["device_train"] = args.device # 'cuda', 'cuda:1', or 'cpu'
config["device_val"] = args.device
config["nb_epoch_max"] = args.epochs # published: 150
config["nb_batch_per_epoch"] = args.batches_per_epoch # published: 1000
config["lr_adam"] = args.lr # published: 0.0005
config["classification"] = not args.regression
config["distribution_mode"] = 1 if args.regression else 0 # regression requires 1 (no class balancing)
config["reg_balancing"] = args.reg_balancing # regression only: 'none' (published), 'lds' or 'sr'
return config
...
best_loss, best_f1, best_epoch_es = pdt.run(config, wandb_project=project, save_model=True, unique_name=args.unique)
- Check the configuration (no GPU, data or W&B needed). This builds the network, runs one dummy forward pass and lists the data files:
python docs/tools/train_custom.py --check --name my_variant_h10 --hidden-size 10
With the defaults (no option) the parameter count is 25,679, the published model.experiment name : my_variant_h10 window : 54 samples = 216 ms sequence : 50 windows, 42 samples (0.168 s) apart -> 8.4 s of context trainable parameters : 30875 dummy forward pass : output shape (2, 1), values in [0, 1]: True train / val device : cuda / cuda (CUDA available here: False) module globals : PHASE=full TEST_SET=True THRESHOLD=0.2 dataset folder : .../portiloop_software/dataset MISSING dataset_classification_full_big_250_matlab_standardized_envelope_pf.txt MISSING subject_sequence_full_big.txt MISSING subject_sequence_p1_big.txt MISSING subject_sequence_p2_big.txt - Smoke test on the CPU (a few minutes; the model will be poor, the point is to see the whole loop run and the files appear):
WANDB_MODE=offline python docs/tools/train_custom.py --device cpu --epochs 2 --batches-per-epoch 20 --name smoke_test - Real training on the GPU:
At the end the script prints the best validation F1, the validation loss of that model andpython docs/tools/train_custom.py --name my_variant_h10 --hidden-size 10 --split 0best_epoch_early_stopping(the three values returned byrun()), and where the checkpoints are.
Other options: --nb-channel, --lr, --epochs, --batches-per-epoch, --split (any integer; the command line only uses 0 and 2), --phase, --no-test-set, --regression, --reg-balancing, --dataset-dir (data folder; checkpoints are written there too), --project (W&B project) and --unique. Remember that changing the architecture changes the parameter count and the computation time on the device (tutorials 07 and 10).
Module globals: PHASE, TEST_SET, THRESHOLD
Some settings are not in the configuration dictionary but are global variables of the module. When the file is run as a script, the __main__ block sets them from the flags. When it is imported (as in the script above, or in a notebook), the else: branch at the bottom sets them instead:
else:
ABLATION = 0
PHASE = 'full'
TEST_SET = True
threshold_list = {'p1': 0.2, 'p2': 0.35, 'full': 0.5} # full = p1 + p2
THRESHOLD = threshold_list[PHASE]
# WANDB_PROJECT_RUN = f"tests_yann"
filename_regression_dataset = f"dataset_regression_{PHASE}_big_250_matlab_standardized_envelope_pf.txt"
filename_classification_dataset = f"dataset_classification_{PHASE}_big_250_matlab_standardized_envelope_pf.txt"
subject_list = f"subject_sequence_{PHASE}_big.txt"
subject_list_p1 = f"subject_sequence_p1_big.txt"
subject_list_p2 = f"subject_sequence_p2_big.txt"
So an imported module uses THRESHOLD = 0.5 for phase full, while the command line uses {'p1': 0.2, 'p2': 0.35, 'full': 0.2}. THRESHOLD turns labels into classes (batch_labels > THRESHOLD) and, in regression, also binarizes the network output for the metrics. Consequences:
- Classification: the labels of the classification file are exactly 0 or 1, so any threshold strictly between 0 and 1 gives the same classes. The difference does not matter.
- Regression: labels are graded (0 to 1 in steps of 0.05). A threshold of 0.5 instead of 0.2 changes which samples count as spindles in the validation metrics and in the class lists, so scores are not comparable with command-line runs. The thresholds 0.2 and 0.35 are the MODA consensus thresholds: "an optimum required consensus GCt between experts of 0.2 in phase 1 and 0.35 in phase 2" [3].
To change them, assign module attributes before calling run(). Since the file names are computed from PHASE at import time, set them too; train_custom.py has a helper that copies the command-line values:
def set_phase(phase="full", test_set=True, threshold=None):
pdt.PHASE = phase
pdt.TEST_SET = test_set
pdt.THRESHOLD = CLI_THRESHOLDS[phase] if threshold is None else threshold
pdt.filename_classification_dataset = f"dataset_classification_{phase}_big_250_matlab_standardized_envelope_pf.txt"
pdt.filename_regression_dataset = f"dataset_regression_{phase}_big_250_matlab_standardized_envelope_pf.txt"
pdt.subject_list = f"subject_sequence_{phase}_big.txt"
The same applies to pdt.path_dataset (the data and output folder) and pdt.ABLATION.
8. Regression mode, and the ablation flag
Regression: learning the experts' agreement
MODA labels come from several experts; the regression file keeps their graded agreement per sample (0 to 1 in steps of 0.05) instead of a binary label. With --regression:
- the data file is
dataset_regression_full_big_...txt(it exists for phasefull); - the loss is the mean squared error (
nn.MSELoss) and the network output is read as a predicted agreement score; - class balancing is off (
distribution_mode = 1; the code asserts it:assert classification or distribution_mode == 1); - metrics binarize both output and label at
THRESHOLD(see above); the paper reports that for its regressor "the optimal threshold is 0.27 for phase 1, 0.23 for phase 2 and 0.26 for the whole cohort" [1]; - the deployed model is the
_on_losscheckpoint.
The configuration key reg_balancing (not exposed on the command line) chooses a reweighting of the regression loss: 'none' (published), 'lds' (label distribution smoothing, after Yang et al. [5], who define it as follows: "LDS convolves a symmetric kernel with the empirical density distribution to extract a kernel-smoothed version that accounts for the overlap in information of data samples of nearby labels") or 'sr' (SurpriseReweighting, a custom scheme that adapts per-bin weights to the running loss). The paper reports that "all the balancing techniques we tried for regression (including oversampling, Label Distribution Smoothing [42] and a custom version of the latter) actually hinder training" [1].
'lds', the labels of all training examples are binned into 100 bins between 0 and 1, the histogram is smoothed with a Gaussian kernel, and each example's loss is multiplied by the inverse of the square root of the smoothed frequency of its bin, so rare agreement levels count more:
labels = dataset.data[3][np.asarray(dataset.indices) + dataset.window_size - 1]
logging.debug(f"Computing the label distribution of {len(labels)} samples (kernel_std: {kernel_std})")
dist = np.bincount(label_bin_indices(labels, nb_bins), minlength=nb_bins).astype(np.float64)
bins = np.linspace(0.0, 1.0, nb_bins + 1)
lds = gaussian_filter1d(input=dist, sigma=kernel_std, axis=-1, order=0, mode='reflect', truncate=4.0)
weights = np.sqrt(lds) if reweight == 'inv_sqrt' else lds
weights = weights / np.sum(weights)
logging.debug(f"dist: {dist}")
return weights, dist, lds, bins
run() creates it with kernel_std=0.01 (in bins), which in practice means almost no smoothing: the weights follow the raw histogram. To try it: python docs/tools/train_custom.py --regression --reg-balancing lds (needs the regression data file).Ablation (--ablation)
The global ABLATION replaces one input by the other at the start of forward(): 1 copies the envelope sequence into the signal input, 2 copies the signal into the envelope input.
if ABLATION == 1:
x1 = copy.deepcopy(x2)
elif ABLATION == 2:
x2 = copy.deepcopy(x1)
This was designed for the 2-input network of the paper. With the published 1-input configuration (envelope_input false), --ablation 1 trains the network on the envelope instead of the EEG, and --ablation 2 has no effect. A non-zero ablation value adds _ablation1 or _ablation2 to the experiment name, so ablation runs do not overwrite the reference run.
9. Running on a SLURM cluster
The authors trained on a SLURM cluster; their example job scripts are in the release file scripts.zip (1.9 KB). Its train.sh requests one V100 GPU, 6 CPU cores, 32 GB of memory and 12 hours (#SBATCH --gres=gpu:v100l:1, --mem=32000M, --time=00-12:00), copies the code to the node's local disk ($SLURM_TMPDIR), creates a virtual environment, runs pip install ., and launches the training with --experiment_name=$EXPERIMENT_NAME --experiment_index=$SLURM_ARRAY_TASK_ID. One detail matters if you reuse it as is: the checkpoints are written inside $SLURM_TMPDIR, which is deleted when the job ends (and with a single array index the name it passes, run_v5_CLASSIFIER_BALANCING_TEST_0, is the same for every submission).
Below is an adapted, commented version (account name, module names and paths depend on your cluster; this one follows the conventions of the Digital Research Alliance of Canada clusters used by the authors). Each array task trains one subject split under its own name, and the checkpoints are written directly to persistent storage, so they survive a job that hits its time limit; resubmitting the same task resumes from them (section 6).
#!/bin/bash
#SBATCH --job-name=portiloop-train
#SBATCH --account=def-yourpi # your allocation
#SBATCH --ntasks=1
#SBATCH --cpus-per-task=6
#SBATCH --gres=gpu:1 # one GPU of any type (the authors used gpu:v100l:1)
#SBATCH --mem=32000M # the data file is loaded twice in memory
#SBATCH --time=1-00:00 # wall time, enforced by SLURM
#SBATCH --array=0-9 # 10 tasks = 10 subject splits (split = task index)
#SBATCH --output=%x_%A_%a.out # one log file per task
set -euo pipefail
REPO=$HOME/portiloop-training # your clone (git pull first)
DATA=$HOME/portiloop-data # the 4 dataset files (tutorial 02)
SPLIT=$SLURM_ARRAY_TASK_ID
NAME=portiloop_split${SPLIT} # unique name per task: no shared files or W&B run IDs
OUT=$SCRATCH/portiloop_runs/$NAME # persistent folder for this task
# One folder per task holding links to the data: run() writes its checkpoints next to the data.
mkdir -p "$OUT"
ln -sf "$DATA"/* "$OUT"/
# Python environment on the node's local disk (fast), code installed in editable mode.
module load python/3.11 # check `module avail python` on your cluster
virtualenv --no-download "$SLURM_TMPDIR/venv"
source "$SLURM_TMPDIR/venv/bin/activate"
pip install --no-index --upgrade pip # --no-index: use the cluster's wheelhouse (Alliance clusters)
pip install -e "$REPO"
# W&B: online if compute nodes have internet and you ran `wandb login` on a login node;
# otherwise offline: curves are kept in $OUT/wandb, upload them later with `wandb sync` from a login node.
export WANDB_MODE=${WANDB_MODE:-offline}
export WANDB_DIR=$OUT # keep the wandb/ folder with the results
cd "$OUT"
python "$REPO/docs/tools/train_custom.py" \
--name "$NAME" --split "$SPLIT" --dataset-dir "$OUT" --device cuda
Submit with sbatch train_portiloop.sh, follow with squeue -u $USER, and read the logs in portiloop-train_<job>_<task>.out. If pip install cannot reach the internet on compute nodes, build the environment once on a login node and only source it in the job.
10. Troubleshooting
| Symptom | Cause | What to do |
|---|---|---|
AssertionError: CUDA unavailable | The configuration asks for 'cuda' and PyTorch sees no GPU (no GPU, CPU-only PyTorch build, or a job submitted without --gres=gpu). | Check with python -c "import torch; print(torch.cuda.is_available())"; install a CUDA build of PyTorch; or use --device cpu for tests (section 7). |
torch.OutOfMemoryError: CUDA out of memory | A batch does not fit in GPU memory, typically after enlarging the network or batch_size, or another process uses the GPU. | Check nvidia-smi; reduce batch_size or nb_channel; the validation batch (42 times the number of validation segments, processed with device_val) can also be large: set device_val to 'cpu' if only validation fails. |
Process killed, or MemoryError while loading | The text dataset is read by pandas and held in memory twice. | Request more RAM (the authors used 32 GB). |
Loss becomes nan, or AssertionError: loss is nan or inf | Learning rate too high, or missing values in the data file. | Lower lr_adam (for example by a factor of 10); check the data file for empty or non-numeric fields. |
UsageError, AuthenticationError or CommError from wandb, at wandb.init | Online mode without valid credentials, or no internet on the node. (The same errors inside restore() are caught and only logged.) | Run wandb login, or use WANDB_MODE=offline or disabled (section 2). |
ModuleNotFoundError: No module named 'portiloop_software' | The package is not installed in the active environment. | pip install -e . from the repository root, in the environment you run. |
ModuleNotFoundError: No module named 'onnx' after the first validation | An old installation without the onnx dependency. | git pull then pip install -e . (or pip install onnx). |
FileNotFoundError: ... dataset_classification_full_big_...txt or subject_sequence_..._big.txt | Data not in portiloop_software/dataset/ of the checkout you run (for example a non-editable install, or the files in a sub-folder after unzipping). | Move the files up so they sit directly in that folder, or pass --dataset-dir to train_custom.py. |
TypeError about delim_whitespace | pandas 3 removed this argument, and your copy of the code predates the fix. | git pull (the code now uses sep=r"\s+"), or install "pandas<3". |
IndexError on [:, 0] with your own subject lists | A split with a single subject: .squeeze() turns the array into one dimension. | Use at least 10 subjects per phase list so that validation and test sets get two or more subjects. |
| A run starts at a later epoch, or two runs overwrite each other's checkpoints | A checkpoint with the same experiment name already exists in the dataset folder (see section 3). | Use --experiment_name (command line), --name or --unique (train_custom.py), or move old checkpoints away. |
Exercises
How much EEG does the published network see during training?
Using the configuration values, compute the number of samples and seconds spanned by one training example, and the overlap between two consecutive windows.
Answer
\((50-1)\times 42 + 54 = 2112\) samples, that is 8.45 s at 250 Hz (the configuration stores time_in_past = 8.5). The windows are 54 samples long and start every 42 samples, so consecutive windows overlap by 12 samples (48 ms). You can check this in the first widget.
Balanced or natural sampling?
In the toy trainer, train once with balanced and once with natural sampling (same learning rate and batch size). Compare precision and recall at 0.5, then the best-threshold F1. Which choice gives more stimulations, and what would you change before using the balanced model in a closed-loop experiment?
Answer
The balanced model has higher recall and lower precision at 0.5: it would stimulate more often, including more false alarms. After moving the threshold (to the best value found on the validation recordings) both reach a similar F1. Before an experiment, choose the threshold on validation data according to what matters more in your protocol, missed spindles or stimulations outside spindles (tutorial 06).
When does the published configuration stop early?
With nb_epoch_max = 150, nb_epoch_early_stopping_stop = 100 and the rule early_stopping_counter > nb_epoch_early_stopping_stop, what is the last epoch at which the smoothed loss can reach its minimum for early stopping to happen before epoch 150? Check your answer in the early-stopping widget with patience 100.
Answer
Epochs are numbered 0 to 149. If the last improvement is at epoch \(b\), the counter reaches 101 at epoch \(b + 101\), so early stopping happens only if \(b + 101 \le 149\), that is \(b \le 48\). Otherwise training runs the full 150 epochs.
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 5.1 and 6, and S1 File, Table II).
- O'Reilly C, Gosselin N, Carrier J, Nielsen T (2014). Montreal Archive of Sleep Studies: an open-access resource for instrument benchmarking and exploratory research. Journal of Sleep Research 23(6): 628 to 635. doi:10.1111/jsr.12169
- Lacourse K, Yetton B, Mednick S, Warby SC (2020). Massive online data annotation, crowdsourcing to generate high quality sleep spindle annotations from EEG data. Scientific Data 7: 190. doi:10.1038/s41597-020-0533-4
- Loshchilov I, Hutter F (2019). Decoupled weight decay regularization. International Conference on Learning Representations (ICLR). arXiv:1711.05101
- Yang Y, Zha K, Chen YC, Wang H, Katabi D (2021). Delving into deep imbalanced regression. Proceedings of the 38th International Conference on Machine Learning, PMLR 139: 11842 to 11851. proceedings.mlr.press/v139/yang21m.html