Run an active-learning loop across several HPC clusters from one Python script, and see how it works inside.
Nico Unglert · github.com/nunglert/remote_handler
sbatch, watch squeueSampler, on the GPU clusterSelector, on your machineVASPEvaluator, one array jobMaceFinetuningTrainer, on the GPU clusterhandler.run(), 20 iterationsgpu = 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
Change one ClusterConfig. The actor code stays the same.
Change one actor, e.g. ORCAEvaluator instead of VASP. The loop stays the same.
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)
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 …
Restart, and only the missing steps run. Running jobs are reattached.
Start from existing DFT data, end on a trained model.
Per-iteration kwargs, e.g. ramp the MD temperature.
The trainer sees all labelled data; the sampler only the latest model.
Raise num_iterations and restart to extend a finished loop.
Plots, dashboards, notifications after each stage.
Sampler interface.# 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.
What happens between handler.run() and a job running on a compute node?
What to do, every iteration
Runs the loop of actors and records its progress, so a run can always resume.
workflows/
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
Where the files are
The same file API locally or over SSH, through one connection that survives dropouts.
file_handler · ssh
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.
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.
Actor interface implemented yet :|
Reusable anywhere: the same VASPEvaluator works with combine on or off, in another loop, or outside active learning.
Neighbours, accumulation, seed, schedule, bookkeeping. Generic, so a new stage needs no new handler code.
@dataclass
class Stage:
name: str
actor: object # update + getter
combine: bool # teal edges
extra_inputs: dict # dashed edges
initial_input: Path # seed
schedule: Schedule
extra_inputs adds edges from any stage: {"reference": InputSource("evaluator")}AL_progress.json marks finished nodes, and resume runs the restfrom_actors(...) just builds the four stages on the right. Pass your own list to add or drop stages.
The evaluator prepares one input per configuration
$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
$ sbatch run_slurm.sh → job 4711
$ python dft_singlepoint.py calcdirs/7Asks for the job status every loop_time; once done, finish_check() verifies the outputs
$ sacct -j 4711 → RUNNING … COMPLETED
calchome/0/dft/results/ mirror of $savepath/dft ├── calcdirs/0 … 199/ └── evaluated_configs.extxyz merged
$savepath/dft/
└── calcdirs/
├── 0/ … dft_dft.extxyz labelled
└── … 199/class RemoteTask(ABC):
def allocate_data(self): ... # ① required
def submit(self): ... # ② + ③ required
def collect_results(self): ... # ④ required
def finish_check(self): ... # optional hook
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.One script, one input, one job.
used by: NeuralIL trainer, remote selector, the example actors
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
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
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.
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_array.sh.j2MAP=({{ 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.
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
get_dir skips files that are already there and writes via .part + rename, so an interrupted copy resumes.
With transfer: "tar", thousands of small files stream through one remote tar.
Drops are retried. With a ConnectionPolicy, an expired certificate pauses the driver rather than crashing it.
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(...) ⑤
ScriptInput dataclass checks the paths where they actually existfinish_check() looks for itdft_ / orca_ / ase_singlepoint.py, mace/, neuralil/, ace/, grace/, selection/, and the processing/ driver
Payloads import remote_handler.scripts, so install it in the cluster env. remote_handler check --connect probes that env.
AL_progress.json tracks the hostWritten after every stage. On restart, finished stages are skipped.
task_manifest.json is a handle to the jobWritten right after submit, on host and cluster. On restart the task reattaches instead of resubmitting.
path = task.detach()
h = TaskHandle.from_file(path)
h.wait(); h.collect()RemoteTrajectoryProcessor(
traj_files=["md.extxyz"], shard_size=500, num_parallel=10,
processors=[OptimizeProcessor(...), RDFProcessor(cutoff=6.0),
CoordProcessor(cutoff=3.0)],
).run()no handler · no actors · no stages: a task used on its own
…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)
driver.py imports each step's registration_module, then looks up run in the REGISTRYSingleScriptTask(...).run(), or detach() now and collect later.Every tier skips itself when its need is missing, so plain pytest always runs.
python:3.13 container→
localhost sshd→
pytest, all tiers→
repo coverage ≥ 50%→
changed lines ≥ 90%→
✓
The silicon phase diagram from 1 to 16 GPa: twelve active-learning iterations across two clusters, 9 to 22 October 2026.
# 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
The Schedule in action: walkers K, replicas M and atoms N ramp up from iteration to iteration, with no change to the actors.
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
Rendered after every stage by an on_stage_complete=[DashboardHook()] hook, as a job of its own.
plots/: one page per iteration














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

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

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.
Each actor on any machine; stages wire them into a loop.
One contract; SLURM or no scheduler; local or over SSH.
AL_progress.json knows what's done, task manifests what's still running.
$ python examples/local_emt_AL/run_al.py
docs/ (Sphinx, on GitHub Pages)