Group meeting

remote_handler

Run an active-learning loop across several HPC clusters from one Python script, and see how it works inside.

workflows tasks & executors transport cluster-side scripts

Nico Unglert · github.com/nunglert/remote_handler

The problem

One active-learning iteration, by hand

GPU cluster MD · training CPU cluster 200 × VASP you scp model; sbatch md.shsqueuesqueuesqueue … scp traj.xyznotebookpick framesscp frames.xyz scp 200 dirs; sbatch --arrayresubmit 7 failed scp OUTCARsscp data; sbatch train.sh sample select label train ×20 done Fri 18:00 →next step Mon 9:00checking squeue at 11 pmmodel_v7_final2.pkl ?
  1. Sample: copy the model over, sbatch, watch squeue
  2. Select: copy trajectories home, pick frames
  3. Label: 200 VASP folders, an array job, resubmit the failures
  4. Train: parse OUTCARs, copy them over, train an ensemble
  5. Repeat, about 20 times. Get depressed
The science is in the sampler, the selection and the model. The rest is plumbing.
The idea

The same iteration, with remote_handler

GPU cluster Sampler · Trainer CPU cluster VASPEvaluator Selector on your machine run_al.py sampleselectlabeltrain×20 put data; sbatch --array put model; sbatch polls status get_dir trajectories put 200 dirs; sbatch --array get_dir (tar stream) finish_check next step starts assoon as the job ends it polls, you sleep trainer_it7_0.model ✓
  1. Sample: your Sampler, on the GPU cluster
  2. Select: a Selector, on your machine
  3. Label: VASPEvaluator, one array job
  4. Train: MaceFinetuningTrainer, on the GPU cluster
  5. Repeat: handler.run(), 20 iterations
The science is in the sampler, the selection and the model. The rest is plumbing, and remote_handler does the plumbing.
Using it

This is all the driver code you write

gpu = ClusterConfig.from_name("musica")
cpu = ClusterConfig.from_name("lugus")
gpu_fs = RemoteFileSystem(remote_alias="musica")
cpu_fs = RemoteFileSystem(remote_alias="lugus")

handler = StagedActiveLearningHandler.from_actors(
    sampler   = MyMDSampler(gpu_fs, gpu, temperature_K=800),
    selector  = UncertaintySelector(n_configs=50),
    evaluator = VASPEvaluatorORCAEvaluator(cpu_fs, cpu, stub=True),
    trainer   = MaceFinetuningTrainer(gpu_fs, gpu,
                    config_file="mace.yaml",
                    foundation_model="mp0.model"),
    calchome  = "calchome",
    num_iterations = 20,
    initial_trainer_out = "mp0.model",
)
handler.run()   # kill it, restart it: it resumes

Swap a cluster

Change one ClusterConfig. The actor code stays the same.

Swap a method

Change one actor, e.g. ORCAEvaluator instead of VASP. The loop stays the same.

Dry-run first

Most actors take stub=True: the whole loop runs with mock outputs and no real compute.

Runnable without a cluster: examples/local_emt_AL/run_al.py (MD → stride select → EMT → Morse fit, all on your machine)

Using it

What the handler gives you for free

calchome/
├── AL_progress.json     # progress file
├── 0/                   # iteration 0 workdirs
│   ├── sampler/ …
│   ├── selector/
│   ├── dft/ …
│   └── train/ …
├── 1/ …
├── sampler_output/
│   └── sampler_it0_0.extxyz
├── selector_output/
├── evaluator_output/
└── trainer_output/
    ├── trainer_it0_0.model
    └── trainer_it0_1.model …

Crash resume

Restart, and only the missing steps run. Running jobs are reattached.

Start / stop anywhere

Start from existing DFT data, end on a trained model.

Schedules

Per-iteration kwargs, e.g. ramp the MD temperature.

Accumulate or not

The trainer sees all labelled data; the sampler only the latest model.

Grow the run

Raise num_iterations and restart to extend a finished loop.

Hooks

Plots, dashboards, notifications after each stage.

Using it

Batteries included

Evaluators

  • VASPEvaluator
  • ORCAEvaluator
  • AseCalculatorEvaluator
  • EMTEvaluator

Trainers

  • MaceModelTrainer
  • MaceFinetuningTrainer
  • AceModelTrainer
  • GraceModelTrainer
  • NeuralilILTrainer

Selectors

  • Stride / Uniform / Random
  • LastFrame
  • Uncertainty
  • ForceFilter, UniformForce
  • QUESTS
  • Pipeline

Processors

  • optimize
  • rdf
  • steinhardt
Samplers live in the downstream project repos: RENS, torch-sim, LAMMPS, SSPD, … all built on the same Sampler interface.
Using it

Getting set up takes about five minutes

# 1. install
pip install -e ".[mace]"

# 2. make sure `ssh musica` just works
#    (keys, ProxyJump in ~/.ssh/config)

# 3. global config + one JSON per cluster
remote_handler configure
remote_handler configure cluster musica

# 4. sanity check: SSH, sbatch, conda env
remote_handler check --connect

A cluster is a small JSON file:

{
  "remote_machine": "musica",  // ssh alias
  "partition": "zen4_0768_h100x4",
  "conda_env": "mace",
  "savepath": "/scratch/me/rh",
  "template": "musica.sh.j2",
  "executor": "slurm",  // or "direct"
  "transfer": "tar"     // or "sftp"
}

Stored under $XDG_CONFIG_HOME/remote_handler/. remote_handler show prints what was resolved and where it came from.

Part 2

Under the hood

What happens between handler.run() and a job running on a compute node?

Architecture

Four building blocks

runs on your machine
runs on the cluster

Workflows

What to do, every iteration

Runs the loop of actors and records its progress, so a run can always resume.

workflows/
uses

Tasks & executors

Ship it, run it, collect it

One unit of remote work. It runs under SLURM, or with no scheduler at all.

core/tasks.py · executors
uses

Transport

Where the files are

The same file API locally or over SSH, through one connection that survives dropouts.

file_handler · ssh
ships & starts

Payloads

The actual compute

Python scripts that run in the cluster's conda env: DFT, training, processing.

scripts/ · processing/

Each block hides its details from the block to its left: workflows never see SLURM, and tasks know nothing about active learning.

workflows

Active learning as a ring of actors

Sampler MD, nested sampling, RSS… Selector uncertainty, QUESTS… Evaluator VASP, ORCA, ASE calc Trainer MACE, ACE, GRACE… trajectories .extxyz candidates labelled data model .model / .pkl × N iterations

An actor follows a two-method contract:

def update(self, calcdir, actor_input, **kw):
    """do this iteration's work"""

def get_output(self) -> Path | list[Path]:
    """hand files to the next actor"""

Only paths pass between actors. An actor does not know or care where the next one runs.

No unified Actor interface implemented yet :|
workflows

Two layers: the actor computes, the stage wires

Stage(name="evaluator") knows the loop Actor e.g. VASPEvaluator update(calcdir, input, **kw) get_output() → paths knows: its folder, its input, its kwargs calcdir, input **kw paths predecessor's output or all of them, if combine initial_input seed before the first run extra_inputs e.g. a novelty reference schedule → kwargs for iteration k evaluator_it3_0.extxyz copied into calchome/ AL_progress.json (iteration 3, "evaluator") done

Actor = what to compute

Reusable anywhere: the same VASPEvaluator works with combine on or off, in another loop, or outside active learning.

Stage = how it is wired into the loop

Neighbours, accumulation, seed, schedule, bookkeeping. Generic, so a new stage needs no new handler code.

workflows

Stages: the interface for a DAG

@dataclass
class Stage:
    name: str
    actor: object          # update + getter
    combine: bool          # teal edges
    extra_inputs: dict     # dashed edges
    initial_input: Path    # seed
    schedule: Schedule
  • Stage n consumes stage n−1: a ring that, unrolled over iterations, is a DAG
  • extra_inputs adds edges from any stage: {"reference": InputSource("evaluator")}
  • The plan walks this graph in order; AL_progress.json marks finished nodes, and resume runs the rest

from_actors(...) just builds the four stages on the right. Pass your own list to add or drop stages.

seed model iteration 0samplerselectorevaluatortrainer iteration 1samplerselectorevaluatortrainer iteration 2samplerselectorevaluatortrainer primary input (predecessor; wraps to next iteration) combine=True: outputs of all iterations so far extra_inputs: from any stage, e.g. a novelty reference in AL_progress.json still to run
tasks

One RemoteTask, step by step

files on disk command that runs sent over SSH
Host your laptop, runs the driver
Cluster e.g. musica, $savepath/dft/

The evaluator prepares one input per configuration

① allocate_data()
SFTP put
$savepath/dft/
├── run_slurm.sh         job script
├── dft_singlepoint.py   payload
└── calcdirs/
    ├── 0/  dft.extxyz  input_dft.json
    └── … 199/

Sends the submit command over SSH and gets the job id 4711 back

② submit()
command via SSH
runs on the login node
$ sbatch run_slurm.sh   → job 4711
then, per array element, on a compute node
$ python dft_singlepoint.py calcdirs/7

Asks for the job status every loop_time; once done, finish_check() verifies the outputs

③ wait
command via SSH
runs on the login node
$ sacct -j 4711   → RUNNING … COMPLETED
calchome/0/dft/results/   mirror of $savepath/dft
├── calcdirs/0 … 199/
└── evaluated_configs.extxyz   merged
④ collect_results()
get_dir of the whole dir
$savepath/dft/
└── calcdirs/
    ├── 0/  … dft_dft.extxyz   labelled
    └── … 199/
tasks

Three kinds of task, one contract

class RemoteTask(ABC):
    def allocate_data(self): ...      # ① required
    def submit(self): ...             # ② + ③ required
    def collect_results(self): ...    # ④ required
    def finish_check(self): ...       # optional hook
Why finish_check? SLURM's "COMPLETED" only means the process exited. A VASP run can exit cleanly and still be useless, so the evaluator checks the outputs and needs at least required_fraction of the calculations to have succeeded.

SingleScriptTask

One script, one input, one job.

used by: NeuralIL trainer, remote selector, the example actors

ArrayScriptTask

One script over calcdirs/0…N as a single job array. %20 caps how many run at once; map_indices reruns only the failed ones.

used by: MACE, ACE and GRACE ensemble trainers

RemoteAtomsHandler

An array task for trajectories: split the frames into shards, run them, put them back in the original order.

used by: DFT evaluators, trajectory processing

executors

Executors: SLURM is just one backend

Task.submit() knows only the ABC make_array_executor( cluster_config) reads config.executor "slurm" "direct" SlurmArrayHandler Jinja: cluster header template + job body sbatch → job id · poll sacct / squeue validates partition and conda env up front DirectArrayExecutor nohup bash launch.sh &, via remote_fs.run_command done when a sentinel file appears workstations, laptops, CI, the local example
class Executor(ABC):
    def submit(self): ...                 # required
    def wait_until_finished(self): ...    # required
    def is_finished(self) -> bool: ...    # required
    def attach(self, job_id): ...         # optional: resume

The surface is small on purpose: run it, and wait for it. Adding PBS or a cloud batch queue means one more class and one more branch in the factory. No task or actor changes.

executors SLURM backend

Job scripts are built from Jinja templates

Header · one per cluster dirona.sh.j2
#!/bin/sh
#SBATCH --job-name={{ jobname }}
#SBATCH --ntasks={{ n_cores }}
#SBATCH --partition={{ partition }}
{{ slurm_header_add }}

{{ conda_activation }}

{% include job_type_template %}
Body · one per job type body_array.sh.j2
MAP=({{ map_indices | join(' ') }})
PER_TASK={{ per_task }}
# START, END from $SLURM_ARRAY_TASK_ID
for (( run=START; run<=END; run++ )); do
  run_id=${MAP[$((run-1))]}
  python {{ python_script_path }} {{ calcdir }}/$run_id
done

Condensed. The array range comes from the command line:
sbatch --array=1-200%20. body_single.sh.j2 is the one-liner for single jobs.

render() values from the
ClusterConfig
+ the task
Result · uploaded as run_slurm.sh
#!/bin/sh
#SBATCH --job-name=dft
#SBATCH --ntasks=8
#SBATCH --partition=normal
module load vasp

source ~/miniconda3/bin/activate
conda activate dft

MAP=(0 1 2 … 199)
PER_TASK=1
# START, END from $SLURM_ARRAY_TASK_ID
for (( run=START; run<=END; run++ )); do
  run_id=${MAP[$((run-1))]}
  python dft_singlepoint.py …/dft/calcdirs/$run_id
done
from header from body
transport

One file-system API, local or remote

Task code remote_fs.put(…) remote_fs.get_dir(…) remote_fs.run_command(…) FileSystemHandlerBase one API LocalFileSystem your disk · local subprocess RemoteFileSystem one paramiko connection SFTP for files · exec for commands hosts & keys from ~/.ssh/config, ProxyJump supported cluster

Incremental downloads

get_dir skips files that are already there and writes via .part + rename, so an interrupted copy resumes.

tar mode

With transfer: "tar", thousands of small files stream through one remote tar.

Resilient

Drops are retried. With a ConnectionPolicy, an expired certificate pauses the driver rather than crashing it.

Payload scripts

Payloads: the code that runs on the cluster

Every payload follows the same shape. Condensed from scripts/dft_singlepoint.py:

def main(argv):
    calcpath = Path(argv[1])                   ①
    cfg = DftSinglepointInput.from_file(
        calcpath / "input_dft.json")
    cfg.validate(calcpath)                     ②

    atoms = ase.io.read(calcpath / cfg.DATABASE)
    atoms.calc = Vasp(directory=calcpath, ...)
    energy = atoms.get_potential_energy()      ③
    if not scf_converged(calcpath):
        sys.exit("SCF not converged")

    ase.io.write(calcpath / "dft_dft.extxyz", atoms) ④
    (calcpath / "is_finished.info").write_text(...)  ⑤
  1. One argument: the folder it should work in
  2. Validate on the cluster: a ScriptInput dataclass checks the paths where they actually exist
  3. Do the work in the cluster's conda env
  4. Write outputs into the same folder
  5. Success marker only if the result is valid. finish_check() looks for it

What ships with the package

dft_ / orca_ / ase_singlepoint.py, mace/, neuralil/, ace/, grace/, selection/, and the processing/ driver

Needs the package on the cluster too

Payloads import remote_handler.scripts, so install it in the cluster env. remote_handler check --connect probes that env.

tasks workflows

Crash resume: two strands, two files

Hostthe driver Clusterthe jobs time → samplerselectorevaluator AL_progress.json MD sbatch task_manifest.json job 4711 · remote dir · backend driver dies DFT array job keeps running rerun run_al.py skip done stages read on restart attach(4711) no resubmit wait collect evaluator ✓trainertrain

AL_progress.json tracks the host

Written after every stage. On restart, finished stages are skipped.

task_manifest.json is a handle to the job

Written right after submit, on host and cluster. On restart the task reattaches instead of resubmitting.

Also usable on its own

path = task.detach()
h = TaskHandle.from_file(path)
h.wait(); h.collect()
Putting it together

One iteration, end to end

Host GPU cluster CPU cluster SAMPLE put model + md.py + input.json, sbatch poll, then get_dir: trajectories SELECT runs locally on the host (SelectorActor) LABEL put 200 folders + dft_singlepoint.py, sbatch --array, write manifest 200 array elements ≤ 20 at once finish_check, then collect (tar stream) → evaluator_output/…extxyz TRAIN put all labelled data (combine=True), sbatch --array ensemble of 5 MACE models collect → trainer_output/trainer_itK_0…4.model AL_progress.json updated after each stage → models feed iteration K+1
Beyond active learning

Post-processing: the same tasks, no loop

RemoteTrajectoryProcessor(
    traj_files=["md.extxyz"], shard_size=500, num_parallel=10,
    processors=[OptimizeProcessor(...), RDFProcessor(cutoff=6.0),
                CoordProcessor(cutoff=3.0)],
).run()
WorkflowsTasksTransportPayloads

no handler · no actors · no stages: a task used on its own

  • The trajectory is sharded once; every shard runs all steps, as one array job

…where CoordProcessor is one file, three parts:

# my_pkg/processors/coord.py
@dataclass
class CoordArgs(ScriptInput):         # 1. shared schema
    cutoff: float

def run(atoms_list, args, calcpath=None): # 2. cluster side
    for at in atoms_list:
        at.arrays["cn"] = coordination(at, args["cutoff"])
    return atoms_list

class CoordProcessor(Processor):        # 3. host side
    name = "coord"
    def build_args(self, savepath):
        return CoordArgs(self.cutoff).to_dict()

register("coord", run, schema=CoordArgs)
  • On the cluster, driver.py imports each step's registration_module, then looks up run in the REGISTRY
  • Downstream packages add processors with no change to remote_handler
Not just post-processing: any script runs the same way, with SingleScriptTask(...).run(), or detach() now and collect later.
Engineering

How it stays trustworthy

{ }unitnothingmock SSH providerlocallocal file systemsynthesized configsshlivea real sshdCI localhost or Dockerintegrationthe ML stackMACE & co.slurma local sbatchskips in CIremoteyour live clusteropt-in: -m remoterun in CI on every PRno dependenciescloser to production

Every tier skips itself when its need is missing, so plain pytest always runs.

CI pull request→ clean python:3.13 container→ localhost sshd→ pytest, all tiers→ repo coverage ≥ 50%→ changed lines ≥ 90%→ ✓
Part 3

A real run

The silicon phase diagram from 1 to 16 GPa: twelve active-learning iterations across two clusters, 9 to 22 October 2026.

A real run · run25

The campaign: silicon, 1–16 GPa

Phase 1 · bootstrap, once MACE foundation → 1 NS run → 1000 strided → VASP 1000 labels seed phase 2 PHASE 2 · 12 ITERATIONS JAXRENS nested samplingJaxrensNSSamplerjaxrens_almusica · GPU stride + uncertaintyNeuralILCommitteeUncertaintySelectorjaxrens_almusica · GPU VASP r²SCAN singlepointsVASPEvaluatorbuilt-inlugus · CPU NeuralIL committee of 10NeuralilILTrainerbuilt-inmusica · GPU
2
clusters
musica (GPU) · lugus (CPU)
12
AL iterations
plus one bootstrap round
3 200
DFT singlepoints
1000 + 11 × 200
13
days
9 → 22 October
6
launches of the driver
one run, resumed each time
6.7 GB
of NS trajectories
phase 2 alone
A real run · run25

The real driver, phase 2

# run25/run_al_staged.py (condensed)
musica = ClusterConfig.from_name("musica")   # GPUs
lugus  = ClusterConfig.from_name("lugus")    # DFT

handler = build_committee_al_handler(  # wraps from_actors
    sampler   = JaxrensNSSampler(musica_fs, musica,
                    config_file="ns_neuralil.yaml"),
    selector  = NeuralILCommitteeUncertaintySelector(
                    n_configs=200, force_metric="relative"),
    evaluator = VASPEvaluator(lugus_fs, lugus,
                    num_parallel=25, incar_kwargs=R2SCAN),
    trainer   = NeuralilILTrainer(musica_fs, musica,
                    training_kwargs=NEURALIL_KWARGS),
    sampler_schedule = NeuralILSamplerSchedule(14),
    entry_stage = "trainer",               # start by training
    initial_evaluator_out = phase1_labels,  # on phase 1's data
    combine_evaluator_outputs = True,     # always all data
    num_iterations = 14,
    on_stage_complete = [DashboardHook()],
)
handler.run()

violet: actors from the downstream jaxrens_al package · the rest is remote_handler

Schedule: walkers, replicas and atoms per AL iteration

The Schedule in action: walkers K, replicas M and atoms N ramp up from iteration to iteration, with no change to the actors.

A real run · run25

13 days, 6 launches, one run

weekendweekend910111213141516171819202122October 2026 →Hostthe driverClustersthe jobsjobs on musica & lugus keep runningit 1 → 3it 3 → 9it 9 → 12SSH auth failedSun 06:07training jobfaileddriver died,no tracebackstopped by handNS it 1VASP it 3VASP it 3 againtraining it 9
from the logs, at every restart
INFO staged_active_learning | Continuing run from calchome_staged/phase2_neuralil/AL_progress.json ...
INFO staged_active_learning | Found a pending manifest for stage 'VASPEvaluator' at .../3/dft/results.manifest.json -- reattaching
A real run · run25

A dashboard after every stage, automatically

An AL workflow has many screws: sampler settings, selection, DFT, training hyperparameters, the schedule. Any of them can quietly go wrong, so you want to see them all, every iteration.
Selectionwhat was picked, and from where?energy / force / volume of the picks · where along the NS runs
Sampleris the sampling healthy?step sizes · acceptance rates · replica-exchange swaps
Modelis it learning, does it generalise?training curve · parity on training and on freshly sampled data
Physicsdoes the result make sense?heat capacity · order parameters · E(V), H(P) vs reference phases

Rendered after every stage by an on_stage_complete=[DashboardHook()] hook, as a job of its own.

plots/: one page per iteration

dashboard iteration 0
0
dashboard iteration 1
1
dashboard iteration 2
2
dashboard iteration 3
3
dashboard iteration 4
4
dashboard iteration 5
5
dashboard iteration 6
6
dashboard iteration 7
7
dashboard iteration 9
9
dashboard iteration 10
10
dashboard iteration 11
11
dashboard iteration 12
12
plots/Iteration1.pdf
Automatically generated dashboard of AL iteration 1
A real run · run25

What came out

Model error per AL iteration

The model gets better. The error on data it has not seen yet falls until it matches the training error.

Melting line per AL iteration

The physics converges. The melting line settles over the iterations (light → dark) and corrects the MACE foundation (dotted).

Phase diagram compared with the literature

And it agrees with the literature: the phase diagram against Unglert et al. and Kubo et al.

Panels d, h and f of the run25 paper figure.

Take-home

Three things to remember

Actors pass paths

Each actor on any machine; stages wire them into a loop.

Tasks: ship, run, collect

One contract; SLURM or no scheduler; local or over SSH.

Crashes are cheap

AL_progress.json knows what's done, task manifests what's still running.

try it today: a full AL loop on your laptop, no cluster needed
$ python examples/local_emt_AL/run_al.py
github.com/nunglert/remote_handler
Docs: docs/ (Sphinx, on GitHub Pages)
Questions, ideas, new processors: talk to me