API Reference

This section contains the complete API reference for remote_handler.

Core Modules

Core modules provide the foundational functionality for cluster interaction, file management, and task execution.

Configuration Management

Configuration management for remote_handler.

This module provides centralized configuration handling with clear precedence: 1. Explicit parameters (highest priority) 2. Environment variables 3. Config files 4. Built-in defaults (lowest priority)

Example

>>> from remote_handler.config import get_config
>>> config = get_config()
>>> config_dir = config.get_config_dir()
>>> template_dirs = config.get_template_dirs()
remote_handler.config.get_persistent_config_dir()[source]

Fixed XDG location of the persistent global config directory.

$XDG_CONFIG_HOME/remote_handler if set, else ~/.config/remote_handler. Read at call time so it honours a monkeypatched environment in tests.

Return type:

Path

remote_handler.config.get_persistent_config_file()[source]

Path to the persistent global config JSON (may not exist).

Return type:

Path

class remote_handler.config.RemoteHandlerConfig(config_dir=None, slurm_templates_dir=None, default_partition='normal', default_conda_env='base', default_conda_source='~/miniconda3/bin/activate', test_cluster=None)[source]

Bases: object

Centralized configuration for remote_handler.

Each field is documented inline below.

config_dir: Optional[Path] = None

Directory containing cluster configuration JSON files.

slurm_templates_dir: Optional[Path] = None

Directory containing custom SLURM job templates.

default_partition: str = 'normal'

Default SLURM partition for job submission.

default_conda_env: str = 'base'

Default conda environment name.

default_conda_source: str = '~/miniconda3/bin/activate'

Default path to conda activation script.

test_cluster: Optional[str] = None

Name (without .json) of the per-cluster config used as the target for the remote test tier. None falls back to remote.json.

classmethod from_env()[source]

Load configuration from environment variables.

Reads:

REMOTE_HANDLER_CONFIG_DIR: Path to cluster config directory REMOTE_HANDLER_SLURM_TEMPLATES: Path to custom SLURM templates

Return type:

RemoteHandlerConfig

Returns:

RemoteHandlerConfig with values from environment

Raises:

ConfigurationError – If environment variables point to invalid paths

Example

>>> config = RemoteHandlerConfig.from_env()
classmethod from_file(config_file)[source]

Load configuration from JSON file.

Parameters:

config_file (Path) – Path to JSON configuration file

Return type:

RemoteHandlerConfig

Returns:

RemoteHandlerConfig with values from file

Raises:

ConfigurationError – If file doesn’t exist, is invalid JSON, or missing required fields

Example

>>> config = RemoteHandlerConfig.from_file(Path("config.json"))
get_config_dir(required=True)[source]

Get configuration directory with validation.

Parameters:

required (bool) – If True, raises error when config_dir is not set

Return type:

Optional[Path]

Returns:

Path to config directory, or None if not required and not set

Raises:

ConfigurationError – If required=True and config_dir is not set

Example

>>> config = get_config()
>>> config_dir = config.get_config_dir()
get_config_file(filename)[source]

Get path to a specific config file.

Parameters:

filename (str) – Name of config file (e.g., “cluster.json”)

Return type:

Path

Returns:

Full path to config file

Raises:

ConfigurationError – If config_dir not set or file doesn’t exist

Example

>>> config = get_config()
>>> cluster_config = config.get_config_file("my_cluster.json")
get_template_dirs()[source]

Get SLURM template search directories in priority order.

Returns list of directories to search for templates: 1. Custom templates directory (if set) 2. Built-in package templates (always included as fallback)

Return type:

list[Path]

Returns:

List of Path objects in search order

Example

>>> config = get_config()
>>> for template_dir in config.get_template_dirs():
...     print(f"Searching: {template_dir}")
find_template(template_name)[source]

Find a SLURM template file by name.

Searches template directories in priority order and returns the first match found.

Parameters:

template_name (str) – Name of template file (e.g., “body_single.sh.j2”)

Return type:

Optional[Path]

Returns:

Path to template file, or None if not found

Example

>>> config = get_config()
>>> template = config.find_template("body_single.sh.j2")
>>> if template:
...     print(f"Found: {template}")
validate()[source]

Validate configuration settings.

Checks that all paths are valid and accessible.

Raises:

ConfigurationError – If any configuration is invalid

Return type:

None

Example

>>> config = RemoteHandlerConfig(config_dir=Path("/invalid"))
>>> config.validate()  # Raises ConfigurationError
to_dict()[source]

Convert configuration to dictionary.

Return type:

dict

Returns:

Dictionary representation of configuration

Example

>>> config = get_config()
>>> config_dict = config.to_dict()
>>> print(json.dumps(config_dict, indent=2))
classmethod resolve()[source]

Resolve configuration with full precedence.

Precedence (highest first): environment variables > persistent config file (fixed XDG location) > built-in defaults. config_dir defaults to the persistent config directory when neither the file nor the environment set it, so per-cluster JSONs live next to config.json with no prior setup.

Return type:

RemoteHandlerConfig

Returns:

Merged RemoteHandlerConfig.

__repr__()[source]

String representation of configuration.

Return type:

str

__init__(config_dir=None, slurm_templates_dir=None, default_partition='normal', default_conda_env='base', default_conda_source='~/miniconda3/bin/activate', test_cluster=None)
remote_handler.config.get_config()[source]

Get the global configuration instance.

Lazily resolves configuration on first access with precedence environment > persistent config file > built-in defaults.

Return type:

RemoteHandlerConfig

Returns:

Global RemoteHandlerConfig instance

Example

>>> config = get_config()
>>> config_dir = config.get_config_dir()
remote_handler.config.set_config(config)[source]

Set the global configuration instance.

Useful for testing or when you need to override configuration.

Parameters:

config (RemoteHandlerConfig) – RemoteHandlerConfig instance to use globally

Return type:

None

Example

>>> # For testing
>>> test_config = RemoteHandlerConfig(config_dir=Path("/tmp/test"))
>>> set_config(test_config)
remote_handler.config.reset_config()[source]

Reset global configuration to None.

Useful for testing to ensure clean state.

Example

>>> reset_config()
>>> config = get_config()  # Will reinitialize from environment
Return type:

None

Cluster Configuration

Backend-agnostic configuration for a remote compute target.

ClusterConfig describes where and as whom work runs (SSH alias, conda env, save path) plus cross-cutting policy (connection resilience, which execution backend to use). It is consumed by every executor backend – SLURM and the scheduler-free direct one alike – so it deliberately lives apart from any single backend’s handler code.

class remote_handler.core.cluster_config.ClusterConfig(remote_machine, partition, conda_env, conda_source, savepath, template, conda_env_dir=None, resilient_connection=False, connection_retry_interval=60.0, connection_max_wait=None, connection_command_timeout=120.0, executor='slurm', transfer='sftp', slurm_header_add='', environment=dict())[source]

Bases: object

Configuration for a remote compute target, independent of execution backend.

Encapsulates the cluster-specific settings needed to run work on a remote machine – where it connects, as whom, which conda env, where results are saved – plus the choice of execution backend (executor). It is shared by all backends, so most fields are generic; partition/template are only consulted by the SLURM backend.

Parameters:
  • remote_machine (str) – SSH alias or hostname of the remote machine

  • partition (str) – SLURM partition name to submit jobs to (SLURM backend only)

  • conda_env (str) – Name of the conda environment to activate on the remote

  • conda_env_dir (Optional[str]) – Directory on the remote where the named environments live, for setups that store envs outside the conda install’s envs/ and ~/.conda/envs. None (default) means only those two standard locations are searched. A leading ~ is expanded against the remote home. Used by env-existence validation.

  • savepath (str) – Default path on the remote where computations are saved

  • template (str) – Jinja2 template file for SLURM job headers (SLURM backend only)

  • resilient_connection (bool) – Opt-in. When True, SSH operations to this cluster pause-and-retry instead of crashing if the connection/credential drops (e.g. an expired step ssh login cert), resuming once it is refreshed. Off by default; most clusters don’t need it.

  • connection_retry_interval (float) – Seconds between retries while paused.

  • connection_max_wait (Optional[float]) – Give up after this many seconds paused; None (default) waits indefinitely until the credential is refreshed.

  • connection_command_timeout (Optional[float]) – Hard timeout (seconds) on each subprocess ssh call, so a hung ssh (e.g. blocked on an interactive QR/MFA prompt after the credential expired) fails with TimeoutExpired instead of parking the driver forever. Applies regardless of resilient_connection; None disables it. Defaults to 120s.

  • executor (str) – Which execution backend to run jobs through. "slurm" (default) submits via sbatch; other backends are selected by the executor factory. Unset in a config JSON means "slurm".

  • transfer (str) – How directory downloads (get_dir, i.e. result collection) move files. "sftp" (default) fetches them one by one over SFTP. "tar" streams them through one remote tar process over the same SSH connection – far faster for many small files, at the cost of needing tar on the remote (it falls back to "sftp" when tar is missing).

  • slurm_header_add (str) – Cluster-intrinsic SLURM header lines prepended to the header of every job on this cluster, before any per-call slurm_header_add an actor passes. Use it for setup that is a property of the machine rather than of the job – e.g. datalab’s export TMPDIR=$HOME/tmp (its /tmp is permission-denied, so any job writing there fails). SLURM backend only; empty by default.

  • environment (dict) – Per-application shell setup for this cluster, keyed by application name (e.g. "vasp", "orca"). Each value is shell lines injected into the SLURM header for jobs of that application (module loads, source of an env script, export of paths like VASP_PP_PATH). This is where cluster- and site-specific setup belongs – so it lives in the (per-user) cluster JSON rather than hardcoded in an actor. Actors that need it (e.g. VASPEvaluator -> "vasp") look up their key; anything passed as slurm_header_add is appended after it. Empty by default.

Example

>>> config = ClusterConfig.from_file("my_cluster.json")
>>> print(config.remote_machine)
'my-hpc-cluster'
remote_machine: str
partition: str
conda_env: str
conda_source: str
savepath: str
template: str
conda_env_dir: Optional[str] = None
resilient_connection: bool = False
connection_retry_interval: float = 60.0
connection_max_wait: Optional[float] = None
connection_command_timeout: Optional[float] = 120.0
executor: str = 'slurm'
transfer: str = 'sftp'
slurm_header_add: str = ''
environment: dict
property connection_policy: ConnectionPolicy

Build the ConnectionPolicy described by this config.

remote_fs(**kwargs)[source]

Open a RemoteFileSystem to this cluster under its policy.

Prefer this over constructing RemoteFileSystem by hand: it can’t forget connection_policy or transfer, so the initial connect and every SFTP op honour resilient_connection and directory downloads use the configured transfer mode. kwargs are forwarded; explicit values win.

Return type:

RemoteFileSystem

classmethod from_file(config_file)[source]

Load cluster configuration from a JSON file.

Parameters:

config_file (str) – Path to the configuration file. Can be either: - An absolute path to a JSON file - A relative filename (will be searched in REMOTE_HANDLER_CONFIG_DIR)

Return type:

ClusterConfig

Returns:

ClusterConfig instance with loaded configuration

Raises:

ConfigurationError – If the config file doesn’t exist or config directory not set for relative paths

Example

>>> # Using absolute path
>>> config = ClusterConfig.from_file("/home/user/configs/cluster.json")
>>> # Using relative path (requires REMOTE_HANDLER_CONFIG_DIR)
>>> config = ClusterConfig.from_file("cluster.json")
classmethod from_name(name)[source]

Load the cluster registered under name (e.g. "lugus").

Looks for <name>.json in the resolved config directory – where remote_handler configure cluster <name> writes it – and loads it. A trailing .json in name is accepted and ignored, so both from_name("lugus") and from_name("lugus.json") work.

Parameters:

name (str) – Registered cluster name (the <name>.json stem).

Return type:

ClusterConfig

Returns:

ClusterConfig loaded from the registered JSON.

Raises:

ConfigurationError – If no cluster is registered under name. The message lists the names that are available.

Example

>>> config = ClusterConfig.from_name("lugus")
classmethod available_names()[source]

Names of clusters registered in the resolved config directory.

These are the <name>.json stems (excluding the global config.json) that from_name() accepts. Returns an empty list when nothing is configured.

Return type:

list[str]

to_dict()[source]

Serialise this config to a plain dict (JSON-round-trippable).

The inverse of from_dict(): from_dict(cfg.to_dict()) yields an equal config. Used to embed a self-contained snapshot of the cluster in a task manifest, so a job can be resumed later without the original cluster JSON still being present in the config dir.

Return type:

dict

classmethod from_dict(config_dict)[source]

Create a ClusterConfig from a dictionary.

Parameters:

config_dict (dict) – Dictionary containing cluster configuration

Return type:

ClusterConfig

Returns:

ClusterConfig instance

Example

>>> config = ClusterConfig.from_dict({
...     "remote_machine": "my-cluster",
...     "partition": "normal",
...     "conda_env": "myenv",
...     "savepath": "/scratch/user/jobs",
...     "template": "slurm_template.sh.j2"
... })
classmethod get_known(args_dict)[source]
__init__(remote_machine, partition, conda_env, conda_source, savepath, template, conda_env_dir=None, resilient_connection=False, connection_retry_interval=60.0, connection_max_wait=None, connection_command_timeout=120.0, executor='slurm', transfer='sftp', slurm_header_add='', environment=<factory>)

SLURM job submission/management for remote HPC systems.

The backend-agnostic ClusterConfig now lives in remote_handler.core.cluster_config; it is re-exported here for backward compatibility (from ...cluster_handler import ClusterConfig still works).

class remote_handler.core.cluster_handler.SlurmHandlerBase(jobname, cluster_config, savepath, n_processors, slurm_header_add, remote_fs, loop_time=30.0, time_limit=None, memory=None)[source]

Bases: ABC

Class to handle file transfers and computations via slurm on a remote HPC cluster.

Methods to implement: - submit: Submit a job array to slurm. - write_jobfile: Write a slurm jobfile. - check_status: Check the status of the slurm job.

Parameters:
  • jobname (str) – Name of the job used in slurm.

  • cluster_config (ClusterConfig) – ClusterConfig instance containing cluster-specific settings (partition, conda_env, template, remote_machine).

  • savepath (PathLike) – Root path wherein computations are saved on remote directory.

  • n_processors (int) – Number of processors that are requested per job. For CPU this refers to n_tasks, where as for GPU on datalab this refers to the number of GPU devices requested on a single node.

  • slurm_header_add (str) – This allows for adding additional header lines to the slurm file. You may also consider creating you own jinja templates instead. An example would be ‘# SBATCH –nodelist=SOME_NODE’

  • remote_fs (FileSystemHandlerBase) – A FileSystemHandlerBase derived object for file operations.

  • loop_time (float) – The time interval which is used to check whether the job is completed.

__init__(jobname, cluster_config, savepath, n_processors, slurm_header_add, remote_fs, loop_time=30.0, time_limit=None, memory=None)[source]
abstractmethod submit()[source]

Submit a job array to slurm.

abstractmethod write_jobfile()[source]

Write a slurm jobfile.

abstractmethod check_status()[source]

Check the status of the slurm job.

wait_until_finished()[source]

Wait until the job is finished by periodically checking the status.

is_finished()[source]

Non-blocking completion poll (see Executor.is_finished).

Thin wrapper over check_status(); requires the job to have been submitted or Executor.attach-ed first.

Return type:

bool

class remote_handler.core.cluster_handler.SlurmJobHandler(jobname, cluster_config, savepath, n_processors, slurm_header_add, remote_fs, jobfile_name='run_slurm.sh', loop_time=10.0, job_type_template='body_single.sh.j2', time_limit=None, memory=None)[source]

Bases: SlurmHandlerBase, SingleExecutor

supports_node_retry = True

True if the backend can re-place a job to dodge a bad node (SLURM). Tasks consult this to decide whether to run their node-exclusion retry loop; backends without a notion of nodes leave it False.

__init__(jobname, cluster_config, savepath, n_processors, slurm_header_add, remote_fs, jobfile_name='run_slurm.sh', loop_time=10.0, job_type_template='body_single.sh.j2', time_limit=None, memory=None)[source]
write_jobfile(input_file, python_script_path, exclude_nodes=None)[source]

Write the slurm jobfile for a single job.

Parameters:
  • input_file – Path to the input file that is used in the job.

  • python_script_path – Path to the python script that is executed in the job.

submit()[source]

Submit the job to slurm.

check_status()[source]

Check the status of the job via squeue.

class remote_handler.core.cluster_handler.SlurmArrayHandler(jobname, cluster_config, savepath, n_processors, remote_fs, slurm_header_add='', jobfile_name='run_slurm.sh', loop_time=10.0, job_type_template='body_array.sh.j2', num_parallel=10, map_indices=None, time_limit=None, memory=None)[source]

Bases: SlurmHandlerBase, ArrayExecutor

Class to handle job arrays via slurm on a remote HPC cluster.

Parameters:
  • jobname (str) – Name of the job used in slurm.

  • cluster_config (ClusterConfig) – ClusterConfig instance containing cluster-specific settings.

  • savepath (str) – Root path wherein computations are saved on remote directory.

  • n_processors (int) – Number of processors that are requested per job. For CPU this refers to n_tasks, where as for GPU on datalab this refers to the number of GPU devices requested on a single node.

  • remote_fs (FileSystemHandlerBase) – A FileSystemHandlerBase derived object for file operations.

  • slurm_header_add (str) – This allows for adding additional header lines to the slurm file. You may also consider creating you own jinja templates instead. An example would be ‘# SBATCH –nodelist=SOME_NODE’

  • jobfile_name (str) – Name of the jobfile that will be created.

  • loop_time (float) – The time interval which is used to check whether the job is completed.

  • job_type_template (str) – Template for array jobs.

  • num_parallel (int) – Maximum number of tasks that are submitted in parallel. It is the number after the ‘%’ in the ‘#SBATCH –array=0-N%num_parallel’

  • map_indices (Optional[list[int]]) – Optional list of indices that are used to map the array job indices to specific tasks. For example if you have 100 tasks but only want to run tasks 0, 2, 5, you can set map_indices=[0, 2, 5].

__init__(jobname, cluster_config, savepath, n_processors, remote_fs, slurm_header_add='', jobfile_name='run_slurm.sh', loop_time=10.0, job_type_template='body_array.sh.j2', num_parallel=10, map_indices=None, time_limit=None, memory=None)[source]
write_jobfile(python_script_path, num_array_tasks)[source]

Write the slurm jobfile for the array job.

Parameters:
  • python_script_path – Path to the python script that is executed in each array job.

  • num_array_tasks – Total number of array tasks.

submit()[source]

Submit a job array to slurm.

check_status()[source]

Check the status of the slurm job.

File System Handlers

class remote_handler.core.file_handler.CommandResult(returncode, stdout, stderr)

Bases: tuple

returncode

Alias for field number 0

stderr

Alias for field number 2

stdout

Alias for field number 1

class remote_handler.core.file_handler.NumpyEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: JSONEncoder

default(obj)[source]

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return super().default(o)
class remote_handler.core.file_handler.FileSystemHandlerBase[source]

Bases: ABC

Interface for handling file operations and directory management on a file system.

This class provides an abstract interface for common file operations that can work with both local and remote file systems. The concrete operations (get, put, makedirs, mkdir, …) are documented on their individual methods below.

__init__()[source]
abstractmethod get(remote, local)[source]

Copy a file from a remote machine to the local machine.

Parameters:
  • remote (PathLike) – The path of the file or directory to copy.

  • local (PathLike) – The path where the file or directory should be copied to.

Return type:

None

abstractmethod put(local, remote)[source]

Copy a file or directory from the local machine to a remote machine.

Parameters:
  • local (PathLike) – The path of the file or directory to copy.

  • remote (PathLike) – The path where the file or directory should be copied to.

Return type:

None

abstractmethod makedirs(path, exist_ok=False)[source]

Create a directory at the specified path, including any necessary parent directories.

Parameters:
  • path (PathLike) – The directory path to create.

  • exist_ok (bool) – If True, do not raise an error if the directory already exists. Defaults to False.

Return type:

None

abstractmethod mkdir(path)[source]

Create a directory at the specified path.

Parameters:

path (PathLike) – The directory path to create.

Return type:

None

abstractmethod write_str_to_file(string, filepath)[source]

Write a string to a file at the specified file path.

Parameters:
  • string (str) – The string content to write to the file.

  • filepath (PathLike) – The path of the file where the string should be written.

Return type:

None

abstractmethod write_dict_to_json(filepath, param_dict)[source]

Write a dictionary to a JSON file at the specified file path.

Parameters:
  • filepath (PathLike) – The path of the file where the dictionary should be written.

  • param_dict (dict) – The dictionary to serialize and write to the JSON file.

Return type:

None

abstractmethod read_ase(filepath, **kwargs)[source]

Read an ASE Atoms object from a file at the specified file path.

Parameters:
  • filepath (PathLike) – The path of the file to read the ASE Atoms object from.

  • **kwargs – Additional keyword arguments to customize the reading process.

Returns:

An ASE Atoms object or a list of them read from the file.

Return type:

list[Atoms]

abstractmethod write_ase(filepath, atoms_list, **kwargs)[source]

Write a list of ASE Atoms objects to a file at the specified file path.

Parameters:
  • filepath (PathLike) – The path of the file where the ASE Atoms objects should be written.

  • atoms_list (list[Atoms]) – A list of ASE Atoms objects to write to the file.

  • **kwargs – Additional keyword arguments to customize the writing process.

Return type:

None

abstractmethod exists(path)[source]

Check if a file or directory exists at the specified path.

Parameters:

path (PathLike) – The path to check for existence.

Returns:

True if the path exists, False otherwise.

Return type:

bool

abstractmethod create_tempdir()[source]

Create a temporary directory and return its path.

Return type:

PathLike

abstractmethod remove(path)[source]

Remove a file at the specified path.

Parameters:

path (PathLike) – The path of the file to remove.

Return type:

None

tag_path(savepath)[source]

Append a random string to a filename or directory name to create a unique path. :param savepath: The full path where the file or directory is located. :type savepath: PathLike

Returns:

The new path with the random string appended to the filename or directory name.

Return type:

PathLike

secure_path(path, is_directory=False)[source]

Ensure that the provided path is unique by appending a timestamp if it already exists.

Parameters:
  • path (PathLike) – The original file or directory path.

  • is_directory (bool) – If True, indicates that the path is a directory. Defaults to False.

Returns:

A unique file or directory path.

Return type:

PathLike

class remote_handler.core.file_handler.LocalFileSystem[source]

Bases: FileSystemHandlerBase

LocalFileSystem is a concrete implementation of FileSystemHandlerBase for handling file operations on the local filesystem.

__init__()[source]
copy(source, destination)[source]

Copy a file from source to destination on the local filesystem. :param source: The path of the file to copy. :type source: PathLike :param destination: The path where the file should be copied. :type destination: PathLike

Return type:

None

put(source, destination)[source]

Copy a file from source to destination on the local filesystem. :param source: The path of the file to copy. :type source: PathLike :param destination: The path where the file should be copied. :type destination: PathLike

Return type:

None

get(destination, source)[source]

Copy a file from source to destination on the local filesystem. :param source: The path of the file to copy. :type source: PathLike :param destination: The path where the file should be copied. :type destination: PathLike

Return type:

None

makedirs(path, exist_ok=False)[source]

Create a directory at the specified path, including any necessary parent directories.

Parameters:
  • path (PathLike) – The directory path to create.

  • exist_ok (bool, optional) – If True, do not raise an error if the directory already exists. Defaults to False.

Return type:

None

mkdir(path)[source]

Create a directory at the specified path.

Parameters:

path (PathLike) – The directory path to create.

Return type:

None

rmtree(path, ignore_errors=True)[source]

Recursively delete a directory on the local filesystem.

Parameters:
  • path (PathLike) – The path of the directory to delete.

  • ignore_errors (bool, optional) – If True, ignore errors during deletion. Defaults to True.

Return type:

None

put_dir(src_dir, dst_dir)[source]

Recursively copy local directory to another location on the local filesystem. :param src_dir: Local directory path :type src_dir: PathLike :param dst_dir: Local target path :type dst_dir: PathLike

Return type:

None

get_dir(src_dir, dst_dir)[source]

Recursively copy local directory to another location on the local filesystem. An existing dst_dir is completed (files are overwritten), matching the incremental RemoteFileSystem.get_dir. :param src_dir: Local directory path :type src_dir: PathLike :param dst_dir: Local target path :type dst_dir: PathLike

Return type:

None

write_str_to_file(string, filepath)[source]

Write a string to a file at the specified file path. :param string: The string content to write to the file. :type string: str :param filepath: The path of the file where the string should be written. :type filepath: PathLike

Return type:

None

write_dict_to_json(filepath, param_dict)[source]

Write a dictionary to a JSON file at the specified file path. :param filepath: The path of the file where the dictionary should be written. :type filepath: PathLike :param param_dict: The dictionary to serialize and write to the JSON file. :type param_dict: dict

Return type:

None

read_ase(filepath, **kwargs)[source]

Read an ASE file from the specified file path. :param filepath: The path of the ASE file to read. :type filepath: PathLike

Returns:

An ASE Atoms object or a list of them read from the file.

Return type:

list[Atoms]

write_ase(filepath, atoms_list, **kwargs)[source]

Write an ASE Atoms object or a list of them to the specified file path. :param filepath: The path of the file where the Atoms object(s) should be written. :type filepath: PathLike :param atoms_list: A list of ASE Atoms objects to write to the file. :type atoms_list: list[Atoms]

Return type:

None

exists(path)[source]

Check if a file or directory exists at the specified path. :param path: The path to check for existence. :type path: PathLike

Returns:

True if the path exists, False otherwise.

Return type:

bool

create_tempdir()[source]

Create a temporary directory on the local filesystem and return its path.

Return type:

PathLike

remove(path)[source]

Remove a file at the specified path.

Parameters:

path (PathLike) – The path of the file to remove.

Return type:

None

run_command(command, timeout=120)[source]

Run a shell command on the local machine.

Counterpart to RemoteFileSystem.run_command(), so executor code can launch work the same way regardless of where the filesystem lives. Raises CommandTimeoutError if it runs longer than timeout seconds (None waits indefinitely).

Return type:

CommandResult

remote_handler.core.file_handler.reconnect_on_failure(func)[source]

Decorator to reconnect if SSH/SFTP operation fails. This decorator wraps methods that perform SSH/SFTP operations. If an SSHException, EOFError, or OSError is raised during the execution of the decorated method, it attempts to reconnect and retries the operation once.

If that single reconnect+retry still fails with a connection/auth error and the filesystem’s connection_policy is enabled (opt-in, off by default), the operation escalates to resilience.run_resilient: it pauses and keeps reconnecting on an interval until the credential is refreshed, rather than crashing. Disabled is exactly the old behaviour.

class remote_handler.core.file_handler.RemoteFileSystem(remote_alias, identityfile=None, remote_temp_path=None, local_temp_path=None, ssh_client_provider=None, connection_policy=None, transfer='sftp')[source]

Bases: FileSystemHandlerBase

RemoteFileSystem is a concrete implementation of FileSystemHandlerBase for handling file operations on remote systems via SSH and SFTP.

Parameters:
  • remote_alias (str) – The alias for the remote host as defined in the SSH config.

  • identityfile (Optional[str]) – Path to SSH identity file to use.

  • remote_temp_path (Optional[str]) – Path on the remote system to use for temporary files.

  • local_temp_path (Optional[str]) – Path on the local system to use for temporary files.

  • ssh_client_provider (Optional[SSHClientProvider]) – Custom provider for SSH/SFTP clients. If None, uses ConfigBasedSSHClientProvider. This parameter is primarily for testing.

  • connection_policy (Optional[ConnectionPolicy]) – Pause-and-retry behaviour on connection/auth loss. Disabled by default.

  • transfer (str) – How get_dir() moves files: "sftp" (default) or "tar". See ClusterConfig.

__init__(remote_alias, identityfile=None, remote_temp_path=None, local_temp_path=None, ssh_client_provider=None, connection_policy=None, transfer='sftp')[source]
put(local, remote)[source]

SFTP put with automatic reconnect on failure. :param local: The path of the file or directory to copy. :type local: PathLike :param remote: The path where the file or directory should be copied to. :type remote: PathLike

get(remote, local)[source]

SFTP get with automatic reconnect on failure. :param remote: The path of the file or directory to copy. :type remote: PathLike :param local: The path where the file or directory should be copied to. :type local: PathLike

Return type:

None

makedirs(path, exist_ok=False)[source]

SFTP makedirs with automatic reconnect on failure.

Parameters:
  • path (PathLike) – The directory path to create.

  • exist_ok (bool, optional) – If True, do not raise an error if the directory already exists. Defaults to False.

Return type:

None

mkdir(path)[source]

SFTP mkdir with automatic reconnect on failure.

Parameters:

path (PathLike) – The directory path to create.

Return type:

None

rmtree(remotepath)[source]

Recursively delete a directory on the remote system via SFTP.

Symlinks are removed, never followed, so a link pointing outside remotepath cannot cause anything there to be deleted. If the connection drops midway, the reconnect retry relists and continues with what is left.

Parameters:

remotepath (PathLike) – The path of the directory to delete.

Return type:

None

put_dir(local_dir, remote_dir)[source]

Recursively copy local directory to remote host via SFTP.

Parameters:
  • local_dir (PathLike) – Local directory path

  • remote_dir (PathLike) – Remote target path

Return type:

None

get_dir(remote_dir, local_dir)[source]

Recursively copy a remote directory to the local host.

Incremental: a file that already exists locally with the remote size is skipped, so calling this again after an interruption only fetches what is missing or incomplete. Files are written via a .part sibling and renamed when complete, so a dropped connection never leaves a truncated file under its final name. A missing remote_dir is a no-op.

How the files travel depends on transfer. "sftp" fetches them one after another over SFTP. "tar" streams them all through a single remote tar over the same SSH connection; if the remote has no tar it falls back to the "sftp" path.

Parameters:
  • remote_dir (PathLike) – Remote directory path

  • local_dir (PathLike) – Local target path

Return type:

None

write_str_to_file(string, filepath)[source]

Write a string to a file at the specified file path on the remote system.

Parameters:
  • string (str) – The string content to write to the file.

  • filepath (PathLike) – The path of the file where the string should be written.

Return type:

None

write_dict_to_json(filepath, param_dict)[source]

Write a dictionary to a JSON file at the specified file path on the remote system. :param filepath: The path of the file where the dictionary should be written. :type filepath: PathLike :param param_dict: The dictionary to serialize and write to the JSON file. :type param_dict: dict

Return type:

None

read_ase(filepath, **kwargs)[source]

Read an ASE file from the specified file path on the remote system by temporarily downloading it to the local system. :param filepath: The path of the ASE file to read. :type filepath: PathLike

Return type:

list[Atoms]

read_str_from_file(filepath)[source]

Read a string from a file at the specified file path on the remote system.

Parameters:

filepath (PathLike) – The path of the file to read the string from.

Return type:

str

write_ase(filepath, atoms_list, **kwargs)[source]

Write an ASE Atoms object to a file at the specified file path on the remote system by temporarily creating it on the local system. :param filepath: The path of the file where the ASE Atoms object should be written :type filepath: PathLike :param atoms_list: A list of ASE Atoms objects to write to the file. :type atoms_list: list of Atoms

Return type:

None

exists(path)[source]

Check if a file or directory exists at the specified path on the remote system. :param path: The path to check for existence. :type path: PathLike

Returns:

True if the path exists, False otherwise.

Return type:

bool

create_tempdir()[source]

Create a temporary directory on the remote filesystem and return its path.

Return type:

PathLike

remove(path)[source]

Remove a file at the specified path on the remote system.

Parameters:

path (PathLike) – The path of the file to remove.

Return type:

None

run_command(command, timeout=120)[source]

Run a command on the remote host over the SSH connection.

Uses the same authenticated paramiko client as the SFTP transport, so it honours whatever ssh-config/credentials the filesystem connected with (no separate ssh subprocess, no dependency on the default ~/.ssh/config). Detached launches (nohup ... &) return at once because the foreground statement exits immediately.

Raises CommandTimeoutError if the command has not exited within timeout seconds (None waits indefinitely). The channel is closed then; the remote process may keep running.

Return type:

CommandResult

Task Management

remote_handler.core.tasks.finalize_manifest_kwargs(cls, base_kwargs, extra)[source]

Merge manifest-derived kwargs with caller-supplied extra overrides.

Used by from_manifest() classmethods to build the final constructor call – shared across modules (ArrayScriptTask/SingleScriptTask here, RemoteAtomsHandler in atoms_handler.py), so it is public rather than module-private. Any extra key that is not a real parameter of cls.__init__ is a typo and raises loudly; anything else (including a stale key that ends up in base_kwargs) is silently dropped rather than raising a confusing TypeError from the constructor call.

Return type:

dict

remote_handler.core.tasks.attach_from_manifest(task, manifest)[source]

Re-bind a from_manifest-reconstructed task to its running job.

Shared by every from_manifest() (ArrayScriptTask/ SingleScriptTask here, RemoteAtomsHandler in atoms_handler.py): attaches task.executor to the manifest’s job so executor.is_finished() can tell whether the job is still running – which DetachableTaskMixin.wait_if_needed needs to avoid collecting a reattached array before all its tasks are done. SLURM needs the recorded job_id; direct needs no handle (it polls a sentinel file). A SLURM manifest without a job_id is left unattached, and wait_if_needed falls back to polling markers.

Return type:

None

class remote_handler.core.tasks.RemoteTask(logfile, savepath, remote_fs, jobname='job', collect_only=False)[source]

Bases: ABC

This serves as an interface for tasks that should be performed on a remote machine. Tasks are always meant to be executed via subprocess. A RemoteTask can be a slurm job, but does not necessarily have to be one. Effectively, RemoteTask just provides the interface handling the questions: - What needs to be transferred to the remote machine? - How can I start your job? - Once it finished, how should I collect the results? and optionally: - how can I properly check (on top of slurm) whether your job finished?

Methods that need to be implemented are:

  • allocate_data: Logic for the allocation of files on the remote file system required for the task.

  • submit: Logic for the submission of the job. This can be a simple subprocess.run(...) call, but can also include more elaborate slurm handling via remote_handler.core.cluster_handler.

  • collect_results: Logic for the collection of results. This can be a simple copy of files from the remote machine to the host, but can also include parsing of files and returning only the relevant information.

  • finish_check (optional): Logic for an additional check whether the job finished properly. This is useful, as slurm does not know anything about your job itself. Hence, this can be a good complementary way of checking whether a job has really finished.

Parameters:
  • logfile (str) – A log file on the host machine where output is printed

  • savepath (PathLike) – The path on the remote system where computations should be performed. Will try to use temporary dir if None.

  • remote_fs (FileSystemHandlerBase) – A FileSystemHandlerBase derived object.

  • jobname (str) – A label for the task, used in jobname and savepath tagging.

  • collect_only (bool) – By default, RemoteTask creates a new tagged savepath if the provided savepath already exists. If you want RemoteTask act on a savepath that exists already, set this to True. This can be helpful if a task has crashed and you want to continue it or collect its results.

__init__(logfile, savepath, remote_fs, jobname='job', collect_only=False)[source]
abstractmethod allocate_data()[source]

Function handling the allocation of files on the remote file system required for the task.

Example

Say you want to do e.g. DFT calculations on another machine. Then this function would handle the logic of setting up the directories on the remote machine where the computations are supposed to be performed. Furthermore, it would transfer required input/submission files or create them in-place.

abstractmethod submit()[source]

Function submitting the slurm job(s). This should depend on how the slurm logic was handled in setup_slurm.

abstractmethod collect_results()[source]

Function controlling how the computed results are collected. Should files be copied/moved from the remote machine to the host or should the results only be parsed and returned?

Example

Your task is a DFT run. It was succesfully run, but you now have a directory with all VASP related files (POSCAR, KPOINTS, POTCAR, ..) in the computatin path on the remote machine. This`function (collect_results) should provide the logic for the retrieval of the data that is required. Do you want the full directory? Is the vasprun.xml or OUTCAR enough?

finish_check()[source]

Optionally, the logic for an additional check can be implemented for a given task. Using only slurm to detect whether a job has finished can be error prone. Slurm does not know anything about our job itself, so this is a good complementary way of checking whether a job has really finished.

Example

Your task consists of running a python script. You could write a small (empty) file is_finished.info at the end of your script. This function (finish_check) could then look for this file when called to confirm that the job is really finished. If your task is a VASP run, one could check whether the OUTCAR ends with the characteristic lines, etc.

class remote_handler.core.tasks.SingleScriptTask(script_file, input_file, local_savepath, cluster_config, remote_fs, logfile='task.log', additional_files=[], remote_savepath=None, collect_only=False, loop_time=30.0, jobname='job', n_processors=2, jobfile_name='run_slurm.sh', job_type_template='body_single.sh.j2', time_limit=None, memory=None, write_manifest_on_submit=True)[source]

Bases: RemoteTask

This class handles the submitting of a single script job, able to run a python script with an input file. The savepath defines the computation directory on the remote machine and all output files will be written there.

This simple implementation just copies the whole computation directory to the local_savepath if the results are collected by collect_results.

Parameters:
  • script_file (PathLike) – Path to a python script that performs the computation.

  • input_file (PathLike) – Path to an input file that is read by the script.

  • local_savepath (PathLike) – Path where finished results will be copied from remote to local machine

  • cluster_config (ClusterConfig) – ClusterConfig instance containing cluster-specific settings.

  • remote_fs (FileSystemHandlerBase) – FileSystemHandlerBase derived object for file operations.

  • logfile (PathLike) – Path to the logfile of the task.

  • remote_savepath (Optional[PathLike]) – Path on remote machine, where computation will be performed. If None, falls back to cluster_config.savepath.

  • collect_only (bool) – If True, results are collected from remote_savepath if it already exists. If False a new savepath will be created with a tag to prevent overwriting.

  • loop_time (float) – The time interval which is used to check whether the job is completed.

  • jobname (str) – Name of the job used in slurm.

  • n_processors (int) – Number of processors that are requested per job. For CPU this refers to n_tasks, where as for GPU on datalab this refers to the number of GPU devices requested on a single node.

  • jobfile_name (str) – Name of the slurm job script that is created to submit the job.

  • job_type_template (PathLike) – The template that is used to create the slurm job script. This needs to be present in one of the TEMPLATE_DIRS of remote_handler.core.slurm_utils.

  • write_manifest_on_submit (bool) – If True (default), submit persists a resume manifest right after submission (best-effort), so a driver crash during the wait does not orphan the running job. Set False to opt out.

__init__(script_file, input_file, local_savepath, cluster_config, remote_fs, logfile='task.log', additional_files=[], remote_savepath=None, collect_only=False, loop_time=30.0, jobname='job', n_processors=2, jobfile_name='run_slurm.sh', job_type_template='body_single.sh.j2', time_limit=None, memory=None, write_manifest_on_submit=True)[source]
copy_file(local_path)[source]

Copies a local file to the remote calculation directory. :type local_path: :param local_path: Path to the local file.

Returns:

The path to the file on the remote machine.

copy_path(local_path)[source]

Copy a local file or directory tree to the remote calcdir.

Use this instead of copy_file() when the artifact may be a directory (e.g. a mace-jax model bundle); files behave identically.

Parameters:

local_path – Path to the local file or directory.

Returns:

The path to the file/directory on the remote machine.

allocate_data()[source]

Allocate the script and input file on the remote machine and prepare the slurm job script.

submit(only_start=False)[source]

Submit the job and wait until it is finished.

Persists a resume manifest right after submission and before the wait (best-effort; disable with write_manifest_on_submit=False), so a driver crash during the wait does not orphan the running job.

collect_results(resume=False)[source]

Copy the entire calculation directory from the remote machine to the local machine using ResultCollector.

Parameters:

resume (bool) – Complete an existing local results directory (e.g. from an interrupted collect) instead of moving it aside first.

finish_check()[source]

Check for the presence of the ‘is_finished.info’ file in the calculation directory on the remote machine to confirm that the job has finished successfully.

node_problem()[source]

If the Node has the requested resources there should be a file called ‘node_check.info’ in the calculation directory on the remote machine.

Returns:

False, no problem on node. True, problem on node.

run(only_start=False)[source]

Run the entire workflow: allocate data, submit job, and collect results.

write_manifest(local_path=None, write_remote=True)[source]

Persist a resume handle for this (submitted) task.

Call after submit/run(only_start=True). Reload it later with TaskHandle.from_file to poll and collect the job from another process.

Return type:

Path

submit_detached(local_path=None, write_remote=True)[source]

Start the job and persist a manifest, without allocating first.

The half of detach() that starts after allocation; useful for a caller that has already run allocate_data() itself (e.g. a workflow actor that allocates as part of update() and only wants to detach at submit time).

Suppresses submit’s own manifest write and writes exactly once here instead, so the local_path / write_remote arguments are honored (and the remote copy is not written twice).

Return type:

Path

detach(local_path=None, write_remote=True)[source]

Allocate, start the job, persist a manifest, and return at once.

The detach-on-submit path: fire the remote job and hand back the local manifest path without waiting, so submission feels like a local backgrounded command. Resume with TaskHandle.from_file.

Return type:

Path

classmethod from_manifest(manifest_path, remote_fs=None, **extra)[source]

Reconstruct a collect-only task from a persisted manifest.

Rebuilds the task exactly as it ran (same resolved savepath, cluster config, and filesystem), without re-allocating or re-submitting, so finish_check() / collect_results() can be called on it in a fresh process. script_file/input_file are never read in collect_only mode, so they are left None.

Parameters:
  • manifest_path (PathLike) – Local *.manifest.json file written by write_manifest/detach.

  • remote_fs (Optional[FileSystemHandlerBase]) – Filesystem to use; rebuilt from the manifest if not given.

  • **extra – Additional/overriding constructor kwargs (e.g. logfile); must be valid SingleScriptTask parameters.

Return type:

SingleScriptTask

class remote_handler.core.tasks.Writeable(content, filename, remote_fs)[source]

Bases: ABC

This base class serves as an interface for one unit of data supplied to a slurm job.

Example

You run DFT with an ArrayScriptTask. You have 1000 configs in total, you distribute them to 10 individual jobs in an array. Then each job of the array will require 100 configurations, which you will have to prepare in the directory of the job.

Methods that need to be implemented are:

  • write: Logic for writing the content to disk. This can be a simple write to a file, but can also include more elaborate logic like writing an ASE trajectory file.

content: Any
filename: str
remote_fs: FileSystemHandlerBase
abstractmethod write(calcpath)[source]

Specify the logic to write content to disk

__init__(content, filename, remote_fs)
class remote_handler.core.tasks.DictJSON(content, filename, remote_fs)[source]

Bases: Writeable

write(calcpath)[source]

Specify the logic to write content to disk

class remote_handler.core.tasks.AtomsBatch(content, filename, remote_fs)[source]

Bases: Writeable

write(calcpath)[source]

Specify the logic to write content to disk

class remote_handler.core.tasks.Reader[source]

Bases: ABC

abstractmethod read(calcpath)[source]
class remote_handler.core.tasks.FileAllocator(remote_fs, rootpath)[source]

Bases: object

Handles file allocation and copying to remote filesystem.

This component is responsible for: - Copying individual files to remote - Allocating shared resources that all jobs can access - Creating calculation directories and writing individual resources

Parameters:
  • remote_fs (FileSystemHandlerBase) – FileSystemHandlerBase instance for remote operations

  • rootpath (PathLike) – Root directory on remote where files are allocated

__init__(remote_fs, rootpath)[source]
copy_file(local_path)[source]

Copy a single file from local to remote rootpath.

Parameters:

local_path (PathLike) – Path to the local file to copy

Return type:

Path

Returns:

Path to the file on the remote machine

copy_path(local_path)[source]

Copy a local file or directory tree to remote rootpath.

Like copy_file(), but if local_path is a directory (e.g. a mace-jax model bundle of config.json + params.msgpack) it is uploaded recursively via put_dir rather than the single-file put. A plain file is handled exactly as copy_file would.

Parameters:

local_path (PathLike) – Path to the local file or directory to copy

Return type:

Path

Returns:

Path to the file/directory on the remote machine

allocate_shared_resources(shared_resources)[source]

Copy shared resources to remote rootpath.

Shared resources are files that all jobs in an array can access, such as model parameters or configuration files.

Parameters:

shared_resources (list[PathLike]) – List of paths to files to copy

Return type:

list[Path]

Returns:

List of paths to the copied files on remote

allocate_individual_resources(individual_resources, calcdir)[source]

Create calculation directories and write individual resources.

For array jobs, each task needs its own calculation directory with its own input data. This method creates these directories and writes the Writeable objects to them.

Parameters:
  • individual_resources (list[list]) – List of lists of Writeable objects

  • calcdir (Path) – Base calculation directory (will create subdirs 0, 1, 2, …)

Return type:

list[Path]

Returns:

List of paths to created calculation directories

class remote_handler.core.tasks.ResultCollector(remote_fs, local_fs)[source]

Bases: object

Handles result collection from remote to local filesystem.

This component is responsible for copying results back from the remote machine to the local machine after jobs complete. It handles directory creation and provides utilities for selective result collection.

Parameters:
__init__(remote_fs, local_fs)[source]
collect_directory(remote_path, local_path, move=True, resume=False)[source]

Copy an entire directory from remote to local.

Parameters:
  • remote_path (PathLike) – Path to directory on remote machine

  • local_path (PathLike) – Path where directory should be copied on local machine

  • move (bool) – If True, handle existing local_path by moving it aside; if False, delete it. Ignored when resume is set.

  • resume (bool) – Keep an existing local_path and only fetch what is missing or incomplete (get_dir skips files whose size already matches) – e.g. to finish an interrupted collect.

Return type:

None

collect_file(remote_path, local_path)[source]

Copy a single file from remote to local.

Parameters:
  • remote_path (PathLike) – Path to file on remote machine

  • local_path (PathLike) – Path where file should be copied on local machine

Return type:

None

class remote_handler.core.tasks.ArrayScriptTask(local_savepath, cluster_config, remote_fs, python_script_file=None, individual_ressources=[], shared_ressources=[], logfile='task.log', remote_savepath=None, collect_only=False, num_parallel=10, loop_time=30.0, jobname='job', n_processors=2, jobfile_name='run_slurm.sh', slurm_header_add='', time_limit=None, memory=None, write_manifest_on_submit=True, num_array_tasks=None)[source]

Bases: RemoteTask

This is a task that consists of running the same script for a bunch of inputs using the slurm array functionality. The remote_savepath is the parent directory of all computations run on the remote machine. The idea behind this implementation is, that you prepare a indexed directory for each individual job of the array (like remote_savepath/0, remote_savepath/1, …). The slurm array then iterates through all of these directories. The logic for each individual computation needs to be inferred inside the python script by parsing a config file.

Hence, preparing an ArrayScriptTask is more involved than running a SingleScriptTask, as it requires a more elaborate preparation. However, it also allows you to efficiently handle a huge amount of data without overcharging slurm.

Parameters:
  • local_savepath (PathLike) – Path where finished results will be copied from remote to local machine

  • cluster_config (ClusterConfig) – ClusterConfig instance containing cluster-specific settings.

  • remote_fs (FileSystemHandlerBase) – FileSystemHandlerBase derived object for file operations.

  • python_script_file (PathLike) – Python script that performs the computation.

  • individual_ressources (list[list[Writeable]]) – A list of lists of Writeable objects that are needed for the individual jobs of the array.

  • shared_ressources (list[PathLike]) – A list of paths to files that are copied to the remote computation directory, but are not specific to one job of the array. This can be e.g. a potential file that is read by the script.

  • logfile (PathLike) – Path to the logfile of the task.

  • remote_savepath (Optional[PathLike]) – Path on remote machine, where computation will be performed. If None, falls back to cluster_config.savepath.

  • collect_only (bool) – If True, results are collected from remote_savepath if it already exists. If False a new savepath will be created with a tag to prevent overwriting.

  • num_parallel (int) – Number of array jobs that are submitted in parallel.

  • loop_time (float) – The time interval which is used to check whether the job is completed.

  • jobname (str) – Name of the job used in slurm.

  • n_processors (int) – Number of processors that are requested per job. For CPU this refers to n_tasks, where as for GPU on datalab this refers to the number of GPU devices requested on a single node.

  • jobfile_name (str) – Name of the slurm job script that is created to submit the job.

  • slurm_header_add (str) – Additional lines that are added to the header of the slurm job script.

  • write_manifest_on_submit (bool) – If True (default), submit persists a resume manifest right after submission (best-effort), so a driver crash during the wait does not orphan the running array. Set False to opt out.

  • num_array_tasks (Optional[int]) – Explicit number of array tasks. Only needed when individual_ressources is empty (e.g. reconstructing a collect_only task via from_manifest(), where no allocation happens); inferred from individual_ressources otherwise. Passing both must agree.

__init__(local_savepath, cluster_config, remote_fs, python_script_file=None, individual_ressources=[], shared_ressources=[], logfile='task.log', remote_savepath=None, collect_only=False, num_parallel=10, loop_time=30.0, jobname='job', n_processors=2, jobfile_name='run_slurm.sh', slurm_header_add='', time_limit=None, memory=None, write_manifest_on_submit=True, num_array_tasks=None)[source]
copy_file(local_path)[source]

Copies a local file to the remote rootpath directory. :type local_path: :param local_path: Path to the local file.

Returns:

The path to the file on the remote machine.

copy_path(local_path)[source]

Copy a local file or directory tree to the remote rootpath.

Use this instead of copy_file() when the artifact may be a directory (e.g. a mace-jax model bundle); files behave identically.

Parameters:

local_path – Path to the local file or directory.

Returns:

The path to the file/directory on the remote machine.

allocate_data(slurm_only=False)[source]

Allocate the script and input files on the remote machine and prepare the slurm job script.

Parameters:

slurm_only (bool) – Write only the SLURM file, don’t allocate ressources.

property all_calcpaths: list[Path]

The per-task calculation directories, calcdir/0, calcdir/1, …

Computed from num_array_tasks rather than stored, so it works equally whether this task just allocated its own directories or was reconstructed via from_manifest() without allocating at all – as long as calcdir resolves to the same directory both times (guaranteed by reusing the manifest’s resolved remote_savepath).

submit(only_start=False)[source]

Submit the array job.

Persists a resume manifest right after submission and before the wait (best-effort; disable with write_manifest_on_submit=False), so a driver crash during the wait does not orphan the running array.

Parameters:

only_start – If True, return right after submission instead of blocking until the array finishes – used by detach.

collect_results(resume=False)[source]

Copy the entire rootpath directory from the remote machine to the local machine using ResultCollector.

Parameters:

resume (bool) – Complete an existing local results directory (e.g. from an interrupted collect) instead of moving it aside first.

write_manifest(local_path=None, write_remote=True)[source]

Persist a resume handle for this (submitted) array task.

See SingleScriptTask.write_manifest(); records num_array_tasks so the array executor is rebuilt correctly.

Return type:

Path

submit_detached(local_path=None, write_remote=True)[source]

Start the array job and persist a manifest, without allocating first.

See SingleScriptTask.submit_detached(); useful when allocate_data() has already run (e.g. a trainer that allocates during update() and only wants to detach at submit time).

Return type:

Path

detach(local_path=None, write_remote=True)[source]

Allocate, start the array job, persist manifest, return at once.

See SingleScriptTask.detach().

Return type:

Path

classmethod from_manifest(manifest_path, remote_fs=None, **extra)[source]

Reconstruct a collect-only array task from a persisted manifest.

Rebuilds the task exactly as it ran (same resolved savepath, cluster config, filesystem, and num_array_tasks), without re-allocating or re-submitting, so finish_check() / collect_results() can be called on it in a fresh process.

Parameters:
  • manifest_path (PathLike) – Local *.manifest.json file written by write_manifest/detach.

  • remote_fs (Optional[FileSystemHandlerBase]) – Filesystem to use; rebuilt from the manifest if not given.

  • **extra – Additional/overriding constructor kwargs (e.g. python_script_file, logfile); must be valid ArrayScriptTask parameters.

Return type:

ArrayScriptTask

finish_check()[source]

Check for the presence of the ‘is_finished.info’ file in each calculation directory on the remote machine to confirm that all jobs have finished successfully.

class remote_handler.core.tasks.DetachableTaskMixin[source]

Bases: object

Shared “submit now, collect later” logic for task-wrapping actors.

Every actor that wraps one remote task per iteration (build, allocate, submit, later collect) – a ModelTrainer, a GroundTruthEvaluator, or a downstream Sampler (concrete samplers live outside this package, in downstream repos, so this needs to be public) – needs the same collect_only mode switch: build+allocate+submit on the original call, or reconstruct the already-submitted task from its manifest – with no allocation, no re-submit – on a later, standalone collect call. Before this mixin, each actor hand-rolled that branch itself (see remote_handler.workflows.trainers._MaceArrayTrainer’s git history); factoring it out here means any task-wrapping actor gets “detach one process, collect from another” for free instead of re-implementing it.

Mix this into a class that already sets self.collect_only and self.remote_fs in its own __init__ – those stay declared per-class (they belong in each actor’s own constructor signature/ docstring, same as n_processors, loop_time, etc.), only the logic that uses them is shared here.

Works for both task kinds an actor might wrap – see build_or_resume_array_task() (ArrayScriptTask, an ensemble/ array of jobs) and build_or_resume_single_task() (SingleScriptTask, one job). Both funnel through build_or_resume_task(), identical apart from which class’s from_manifest gets called.

Note that “wrap the task-building step in a closure” only gets an actor this far, not all the way: an actor whose downstream code depends on something the build step computes (e.g. a per-run remote filename) needs that piece made available independent of the closure too, since the closure is never called in collect_only mode – see NeuralilILTrainer’s pickle_filename, computed from calcdir alone up front, precisely so get_trained_model() does not depend on the closure having run.

collect_only: bool
remote_fs: FileSystemHandlerBase
iteration_dir(calcdir)[source]

This iteration’s working directory, calcdir / _iteration_subdir.

Computed from calcdir alone (never from instance state like self.results_dir), so it gives the same answer whether called from update() while building this iteration’s task, or from pending_manifest() before update() has ever run – which is the whole point of the latter.

Return type:

Path

results_dir_for(calcdir)[source]

This iteration’s results_dir, i.e. where this actor’s task is built with local_savepath= and where manifest_path() then looks for a manifest. Single source of truth for both update() (which assigns its result to self.results_dir) and pending_manifest().

Return type:

Path

pending_manifest(calcdir)[source]

Default pending_manifest for any actor that sets _iteration_subdir – overrides the Sampler/ GroundTruthEvaluator/ModelTrainer ABCs’ own default (always None) via normal MRO resolution, since this mixin is listed first (class Foo(DetachableTaskMixin, ModelTrainer)). See ModelTrainer.pending_manifest for the full rationale.

Returns None (reattach unsupported, the ABC default) rather than raising when _iteration_subdir isn’t set, unlike iteration_dir() – an actor that hasn’t wired this up yet should just not support reattach, not crash the whole loop.

Return type:

Optional[Path]

manifest_path(results_dir)[source]

Where write_manifest/detach puts this task’s manifest.

A fixed naming convention (<results_dir>.manifest.json, matching RemoteTask._save_manifest’s own default) rather than a constructor argument – so a later collect_only=True call can find it from results_dir alone, without the caller having to remember/pass a manifest path explicitly.

Return type:

Path

build_or_resume_task(task_cls, results_dir, build_task, **from_manifest_extra)[source]

Return this iteration’s task, built fresh or resumed from a manifest.

collect_only=False (the normal path): calls build_task() – supplied by the concrete actor, since only it knows how to construct its own task (payload script, inputs, shared resources, …) – then allocates it. Allocation stays here rather than inside build_task so every caller gets it uniformly, the same way it’s skipped uniformly below.

collect_only=True: reconstructs the task an earlier, collect_only=False call already submitted, via task_cls.from_manifest at manifest_path(), with no allocation and no re-submit. build_task is never called in this branch – constructing it would touch things a pure collect call shouldn’t need (e.g. resolving a remote train-runner path, or the original training data).

Parameters:
  • task_cls (type) – ArrayScriptTask or SingleScriptTask – whichever this actor wraps.

  • results_dir (PathLike) – This iteration’s task directory (e.g. self.results_dir); also anchors the manifest lookup.

  • build_task (Callable[[], RemoteTask]) – Zero-arg callable building this actor’s task. Only invoked when not collect_only.

  • **from_manifest_extra – Extra constructor overrides for the collect_only path (e.g. python_script_file); ignored otherwise.

Return type:

RemoteTask

build_or_resume_array_task(results_dir, build_task, **from_manifest_extra)[source]

build_or_resume_task() for an ArrayScriptTask.

Return type:

ArrayScriptTask

build_or_resume_single_task(results_dir, build_task, **from_manifest_extra)[source]

build_or_resume_task() for a SingleScriptTask.

Return type:

SingleScriptTask

submit_if_needed(task)[source]

Submit task, unless it was already submitted in another process.

Return type:

None

wait_if_needed(task, *, finish_check=None, poll_interval=None, max_wait=None, error_message=None)[source]

Require – or, when reattached, wait for – task’s completion.

finish_check defaults to task.finish_check (no args); pass e.g. lambda: task.finish_check(required_fraction) for the array/fraction variant. Called with no arguments either way.

Non-collect_only: task.submit() (via submit_if_needed, called before this) already blocked – via the executor’s own queue-/sentinel-based wait – until the job left the queue. So a single finish_check() here is correct: if the marker is missing now, the job is done one way or another (successfully or not), not still running, and this raises immediately rather than polling for a marker that will never appear.

collect_only (reattached): *.from_manifest re-attaches the executor to the recorded job (see attach_from_manifest()), so this polls task.executor.is_finished() – the queue, not the success markers – every poll_interval seconds (default: task.loop_time if present, else 30.0) until the job is done or max_wait seconds have elapsed (None, the default, means wait forever – matching ConnectionPolicy’s convention). Only then is finish_check() applied, once, exactly as on the fresh path. Polling finish_check() directly would be wrong for a fraction-based check: a reattached array would be collected as soon as required_fraction of its tasks had finished, with the rest still running.

If the executor could not be attached (an old SLURM manifest with no job_id), there is no way to ask the queue, so this falls back to polling finish_check() itself and logs a warning.

Parameters:

error_message (Optional[str]) – Used verbatim as the exception message when finish_check() fails (on either path); also the prefix of the message raised when collect_only polling exceeds max_wait. Defaults to a generic message naming the task type.

Raises:

TaskError – If the job never finishes within max_wait, or if finish_check() fails once the job is done.

Return type:

None

SLURM Utilities

remote_handler.core.slurm_utils.validate_slurm_available(ssh_command, target, policy)[source]

Probe that sbatch is available on the target system.

Runs which sbatch through the same resilient wrapper as submit_job() / the status checks: with an enabled policy an expired/lost credential pauses-and-retries here instead of crashing, and policy.command_timeout still bounds a hung ssh.

Parameters:
  • ssh_command – The ssh <alias> prefix, or None to probe the local machine.

  • target – Human-readable name of the machine, for error messages.

  • policy – The cluster’s resilience.ConnectionPolicy.

Raises:
  • RemoteConnectionError – The probe failed at the ssh level (expired cert, auth, unreachable host) – which sbatch truly absent exits 1 on the remote, whereas ssh’s own connect/auth failure exits 255.

  • DependencyError – sbatch is genuinely missing, or a bounded probe timed out.

remote_handler.core.slurm_utils.submit_job(script_path, output_path, ssh_command=None, cwd=None, connection_policy=ConnectionPolicy(enabled=False, poll_interval=60.0, max_wait=None, command_timeout=120.0, sleep=<built-in function sleep>, monotonic=<built-in function monotonic>))[source]

Submit a slurm job.

Parameters:
  • script_path (os.PathLike) – Path to the slurm script to be submitted.

  • output_path (os.PathLike) – Path to the directory where slurm output and error files will be written.

  • ssh_command (Optional[str], optional) – SSH command to be used for remote submission. Defaults to None.

  • cwd (Optional[os.PathLike], optional) – If provided, the command will be executed in this directory. Defaults to None.

Returns:

The job ID of the submitted job.

Return type:

str

remote_handler.core.slurm_utils.submit_job_array(script_path, output_path, num_array_tasks, num_parallel=10, ssh_command=None, cwd=None, connection_policy=ConnectionPolicy(enabled=False, poll_interval=60.0, max_wait=None, command_timeout=120.0, sleep=<built-in function sleep>, monotonic=<built-in function monotonic>))[source]

Submit a slurm job array.

Parameters:
  • script_path (PathLike) – Path to the slurm script to be submitted.

  • output_path (PathLike) – Path to the directory where slurm output and error files will be written.

  • num_array_tasks (int) – Number of tasks in the job array.

  • num_parallel (int) – Maximum number of tasks to run in parallel. Defaults to 10.

  • ssh_command (Optional[str]) – SSH command to be used for remote submission. Defaults to None.

  • cwd (Optional[PathLike]) – If provided, the command will be executed in this directory. Defaults to None.

Returns:

The job ID of the submitted job array.

Return type:

str

remote_handler.core.slurm_utils.check_job_status_sacct(job_ids, ssh_command='ssh lugus', connection_policy=ConnectionPolicy(enabled=False, poll_interval=60.0, max_wait=None, command_timeout=120.0, sleep=<built-in function sleep>, monotonic=<built-in function monotonic>))[source]

Tries to retrieve information on the job using the slurm sacct functionality. I designed this for arrays. Somehow sacct does not work on all clusters, so you might want to use check_job_status_squeue.

In principle this function would allow for more control, as it can also indicate whether a run failed or succesfully finished.

Parameters:
  • job_ids (list) – List of job IDs to check.

  • ssh_command (str, optional) – SSH command to be used for remote checking. Defaults to “ssh lugus”.

Returns:

List of booleans indicating whether each job has finished.

Return type:

list

remote_handler.core.slurm_utils.check_job_status_squeue(job_id, ssh_command='ssh lugus', connection_policy=ConnectionPolicy(enabled=False, poll_interval=60.0, max_wait=None, command_timeout=120.0, sleep=<built-in function sleep>, monotonic=<built-in function monotonic>), retries=10, retry_wait=30.0)[source]

Tries to retrieve information on the job using the slurm squeue command. This is a quite naive method that just checks whether squeue returns and output for the given job id. If not, it considers the job as being finished.

Once a job leaves the queue, squeue -j <id> may either return just its header (exit 0, no rows) or, on some SLURM builds, exit non-zero with slurm_load_jobs error: Invalid job id specified – the controller has already purged the completed job. Both mean the same thing: finished. The non-zero-exit form is handled explicitly so a job that completes while the connection is briefly down (e.g. during a credential refresh) is reported as finished rather than crashing the driver. A genuine ssh/connection failure still propagates through _run_ssh’s resilience handling.

Any other non-zero exit is retried: squeue also fails when the controller is briefly unresponsive (e.g. Socket timed out on send/recv operation), which says nothing about the job. Only after retries further failures, retry_wait seconds apart, is the error raised.

Parameters:
  • job_id (str) – The job ID to check.

  • ssh_command (str, optional) – SSH command to be used for remote checking. Defaults to “ssh lugus”.

  • retries (int) – Retries of a failing squeue before raising.

  • retry_wait (float) – Seconds between those retries.

Returns:

False if the job is still running, True if it has finished.

Return type:

bool

class remote_handler.core.slurm_utils.LoggingFileSystemLoader(searchpath, encoding='utf-8', followlinks=False)[source]

Bases: FileSystemLoader

Custom Jinja2 file system loader that logs which template files are loaded.

get_source(environment, template)[source]

Override the get_source method to add logging.

remote_handler.core.slurm_utils.get_array_slurm_str(calcdir, python_script_path, num_array_tasks=1, num_parallel=10, jobname='job', partition='normal', n_processors=8, conda_env='jaxnest', conda_source='~/miniconda3', map_indices=None, header_template='lugus.sh.j2', job_type_template='body_array.sh.j2', slurm_header_add='', per_task=1, time_limit=None, memory=None)[source]

Get the SLURM script for an array job as a string. The directories contained in TEMPLATE_DIRS will be scanned in order until the first succesful hit of a header_template file.

Parameters:
  • calcdir (os.PathLike) – Path to the calculation directory.

  • python_script_path (os.PathLike) – Path to the python script to be executed.

  • num_array_tasks (int, optional) – Number of tasks in the job array. Defaults to 1.

  • num_parallel (int, optional) – Maximum number of tasks to run in parallel. Defaults to 10.

  • jobname (str, optional) – Name of the job used in slurm. Defaults to “job”.

  • partition (str, optional) – Name of the partition on the HPC setup. Defaults to “normal”.

  • n_processors (int, optional) – Number of CPU cores to request. Defaults to 8.

  • conda_env (str, optional) – Name of the conda environment to activate. Defaults to “jaxnest”.

  • map_indices (Optional[np.ndarray], optional) – Specific indices for the array tasks. If None, defaults to np.arange(num_array_tasks). Defaults to None.

  • header_template (str, optional) – Template file for the slurm header. Defaults to “lugus.sh.j2”.

  • job_type_template (str, optional) – Template file for the job body. Defaults to “body_array.sh.j2”.

  • slurm_header_add (str, optional) – Additional lines to add to the slurm header. Defaults to “”.

  • per_task (int, optional) – Number of array tasks per job. Defaults to 1.

Returns:

The rendered SLURM script as a string.

Return type:

str

remote_handler.core.slurm_utils.get_slurm_str(input_file, python_script_path, jobname='job', partition='normal', n_cores=8, conda_env='jaxnest', conda_source='/home/user/miniconda3', header_template='dirona.sh.j2', job_type_template='body_single.sh.j2', slurm_header_add='', exclude_nodes=None, time_limit=None, memory=None)[source]

Get the SLURM script as a string. The directories contained in TEMPLATE_DIRS will be scanned in order until the first succesful hit of a header_template file.

Parameters:
  • input_file (os.PathLike) – Path to the input file for the python script.

  • python_script_path (os.PathLike) – Path to the python script to be executed.

  • jobname (str, optional) – Name of the job used in slurm. Defaults to “job”.

  • partition (str, optional) – Name of the partition on the HPC setup. Defaults to “normal”.

  • n_cores (int, optional) – Number of CPU cores to request. Defaults to 8.

  • conda_env (str, optional) – Name of the conda environment to activate. Defaults to “jaxnest”.

  • header_template (str, optional) – Template file for the slurm header. Defaults to “lugus.sh.j2”.

  • job_type_template (str, optional) – Template file for the job body. Defaults to “body_single.sh.j2”.

  • slurm_header_add (str, optional) – Additional lines to add to the slurm header. Defaults to “”.

  • exclude_nodes (str) – Comma-separated string of nodes to exclude. Defaults to None.

Returns:

The rendered SLURM script as a string.

Return type:

str

Handlers

Atoms Handler

Remote SLURM array driver for ASE Atoms trajectory processing.

RemoteAtomsHandler couples ArrayScriptTask (remote execution) with AtomsShardManager (trajectory domain logic) via composition.

class remote_handler.core.atoms_handler.RemoteAtomsHandler(traj_files, cluster_config, remote_fs, shard_size, remote_savepath, num_parallel, loop_time=30, jobname='opt', every=None, start=None, end=None, local_savepath=None, logfile='opt.log', collect_only=False, tag='opt_', n_processors=2, slurm_header_add='', time_limit=None, memory=None, num_array_tasks=None)[source]

Bases: ArrayScriptTask

Coordinates SLURM array job execution for processing ASE Atoms trajectories.

This class combines ArrayScriptTask (for SLURM infrastructure) with AtomsShardManager (for trajectory handling) using composition. It manages the full workflow: reading trajectory files, sharding them into batches, submitting array jobs, collecting results, and redistributing them back into the original file structure.

Architecture:

  • Inherits from ArrayScriptTask for SLURM job submission infrastructure

  • Composes AtomsShardManager for domain-specific Atoms handling logic

  • Delegates trajectory operations to shard_manager

  • Orchestrates the overall workflow

Parameters:
  • traj_files (Optional[list[str]]) – List of extxyz files containing atomic configurations. None skips the shard manager entirely (no reading, no sharding) – only used by from_manifest(), where num_array_tasks is supplied directly instead, exactly the way ArrayScriptTask(num_array_tasks=...) lets a collect_only reconstruction skip individual_ressources. Never pass None directly; it leaves trajectory-shape-aware methods (collect, regroup, redistribute, collect_and_harvest, recompute_failed) unusable.

  • cluster_config (ClusterConfig) – ClusterConfig instance containing cluster-specific settings.

  • remote_fs (FileSystemHandlerBase) – Instance of a RemoteFileSystem or LocalFileSystem (in case of running on a local machine with SLURM).

  • shard_size (Optional[int]) – Number of configurations per task. None or a negative value (e.g. -1) processes all configs in one shard.

  • savepath – Remote path where the temporary calculation directories are created and where the final results are written to.

  • num_parallel (int) – Number of parallel jobs to submit to the cluster, i.e. the size of the slurm array job.

  • loop_time (float) – Time in minutes between checking for finished jobs.

  • jobname (str) – Name of the job to be submitted to the cluster.

  • every (Optional[int]) – If provided, only every every-th configuration is taken from each trajectory file.

  • start (Optional[int]) – If provided, only configurations starting from this index are taken from each trajectory file.

  • end (Optional[int]) – If provided, only configurations up to this index are taken from each trajectory file.

  • local_savepath (Optional[PathLike]) – Local path where the trajectory files are stored initially and where the final results are written to.

  • logfile (str) – Path to a logfile where the output of this script is written.

  • collect_only (bool) – If True, only collect results from the remote machine, do not submit new jobs.

  • tag (str) – A string tag that is prepended to the filenames of the trajectory files when they are written to the local file system.

  • n_processors (int) – Number of processors to request per job.

  • slurm_header_add (str) – Additional lines to add to the SLURM header.

Example

Given a set of 3 trajectory files, containing 50 configs per file, with a shard_size of 20, this will shard the configs in 8 batches (arising from ceil(3 * 50 / 20)). For each batch a directory will be created in savepath/calcdirs. After the computations were run, the savepath should look like this:

savepath
|___calcdirs
    |___0
    |   |___0.extxyz
    |   |___input_opt.json
    |   |___opt_0.extxyz
    |
    |___1
        |___ ...

The opt_X.extxyz files are collected and redistributed into the shape of the original trajectory files.

__init__(traj_files, cluster_config, remote_fs, shard_size, remote_savepath, num_parallel, loop_time=30, jobname='opt', every=None, start=None, end=None, local_savepath=None, logfile='opt.log', collect_only=False, tag='opt_', n_processors=2, slurm_header_add='', time_limit=None, memory=None, num_array_tasks=None)[source]
classmethod from_manifest(manifest_path, remote_fs=None, tag='opt_', **extra)[source]

Reconstruct a collect-only handler from a persisted manifest.

Mirrors from_manifest(), for consistency: rebuilds the task exactly as it ran (same resolved savepath, cluster config, filesystem, and num_array_tasks), without re-reading or re-sharding the original trajectory files – which a plain RemoteAtomsHandler(traj_files=..., collect_only=True, ...) reconstruction would still do today, purely to recompute num_array_tasks, even though a collect call never uses the shards themselves.

Because traj_files=None skips the shard manager entirely (see __init__), the returned handler has no shard_manager and cannot do trajectory-shape-aware collection (collect(), regroup(), redistribute(), collect_and_harvest(), recompute_failed()). It supports exactly what ArrayScriptTask itself offers: finish_check() and the generic, per-job collect_results() – which is all AseCalculatorEvaluator actually uses (it scans results_dir/calcdirs itself rather than calling collect()/regroup()).

Parameters:
  • manifest_path (PathLike) – Local *.manifest.json file written by write_manifest/detach.

  • remote_fs (Optional[FileSystemHandlerBase]) – Filesystem to use; rebuilt from the manifest if not given.

  • tag (str) – Restored onto the handler for API parity with a normal construction (used by redistribute, which is unavailable here regardless).

  • **extra – Additional/overriding constructor kwargs; must be valid RemoteAtomsHandler parameters.

Return type:

RemoteAtomsHandler

finish_check(required_fraction=0.8)[source]

Check the fraction of jobs that wrote is_finished.info.

Lives here (not on a subclass) because it only touches all_calcpaths/remote_fs – both available regardless of whether this handler was built normally or via from_manifest() (shard_manager=None), so a reconstructed collect-only handler supports the exact same finish_check(required_fraction) call a freshly-built one does, with no special-casing needed by callers like AseCalculatorEvaluator.

Parameters:

required_fraction (float) – Minimum success fraction to return True.

Return type:

bool

combine_trajs(traj_files, indices)[source]

Combines configurations from all provided trajectories into a single list of Atoms objects.

Deprecated: This method is kept for backwards compatibility. Use shard_manager.combine_trajs() directly instead.

read_configs()[source]

Reads all configurations from the provided trajectory files and shards them into batches of size shard_size.

Deprecated: This method is kept for backwards compatibility. Sharding now happens automatically in __init__ via shard_manager.

collect(only_finished=True)[source]

Scan temporary directories for extxyz files containing processed Atoms objects.

Parameters:

only_finished (bool) – If True, only collect configurations that have the is_finished flag set to True in their info dict.

Returns:

  • A list of all collected Atoms objects.

  • A list of indices of batches that failed to process.

Return type:

tuple[list[Atoms], list[int]]

regroup(all_atoms)[source]

Regroup a flat list of Atoms objects into a list of lists, where each sublist corresponds to the configurations from a single original trajectory file.

Parameters:

all_atoms – A flat list of Atoms objects, each with an info dict containing a ‘file_index’ key that indicates the original trajectory file index.

Return type:

list[list[Atoms]]

Returns:

A list of lists, where each sublist contains Atoms objects from the same original trajectory file.

redistribute(all_atoms_sets)[source]

Redistribute the grouped Atoms objects back into their original trajectory files, writing them to the local file system with the specified tag prepended to the filenames.

Parameters:

all_atoms_sets – List of lists, where each sublist contains Atoms from the same original trajectory file.

check_and_harvest(all_atoms, failed_indices)[source]

Check for failed batches and redistribute collected configurations into their original trajectory files.

Parameters:
  • all_atoms – All collected Atoms objects.

  • failed_indices – Indices of batches that failed.

Raises:

Exception – If any batches failed or if collected count is insufficient.

collect_and_harvest()[source]

Collect processed configurations from the remote machine and redistribute them into their original trajectory files.

Raises an exception if any batch failed to process or if the number of collected configurations is less than the total expected.

recompute_failed()[source]

Attempt to recompute any batches that failed during the initial processing. This method is only applicable when collect_only is set to True. It collects the failed batches, resubmits them for processing, and then collects the results again.

Pure-domain sharding/collection logic for ASE Atoms trajectories.

Extracted from atoms_handler so the trajectory math (read, shard, collect, regroup, redistribute) lives free of any SLURM/cluster dependency. RemoteAtomsHandler composes AtomsShardManager from here.

remote_handler.core.atoms_shard.split_list(lst, shard_size)[source]

Splits a list into smaller sublists of a specified size.

Parameters:
  • lst (list[Any]) – The list to be split.

  • shard_size (int) – The size of each shard.

Returns:

A list of sublists, where each sublist has a length of shard_size, except possibly the last one.

Return type:

list[list[Any]]

remote_handler.core.atoms_shard.reduce_to_unique_order(arr)[source]

Reduce an array to its unique elements while preserving the order of first appearance.

Parameters:

arr (iterable) – The input array or list to process.

Returns:

A list of unique elements in the order of their first appearance.

Return type:

list

remote_handler.core.atoms_shard.regroup(some_list, indices)[source]

Group elements of a list based on an array of indices, preserving the order of first appearance of unique indices.

Parameters:
  • some_list (list) – The input list of elements to group.

  • indices (array-like) – An array of indices specifying the grouping. Consecutive occurrences of the same index form a group.

Returns:

A list of groups, where each group contains elements

from some_list corresponding to a unique index in indices, in the order of their first appearance.

Return type:

list of lists

remote_handler.core.atoms_shard.front_tag(filepath, tag)[source]

Prepends a tag to the filename in a given filepath. :param filepath: The original file path. :type filepath: str or Path :param tag: The tag to prepend to the filename. :type tag: str

Returns:

The modified file path with the prepended tag.

Return type:

Path

class remote_handler.core.atoms_shard.AtomsShardManager(traj_files, shard_size, indices)[source]

Bases: object

Manages sharding and collection of ASE Atoms trajectories.

This class contains pure domain logic for handling atomic trajectory files: reading, sharding, collection, regrouping, and redistribution. It has no dependencies on SLURM or cluster infrastructure.

Parameters:
  • traj_files (list[str]) – List of extxyz files containing atomic configurations.

  • shard_size (Optional[int]) – Number of configurations per shard. None or a negative value (e.g. -1) means “no sharding”: the entire set of configurations is processed as a single shard.

  • indices (slice) – Slice object specifying which configurations to read (start:end:step).

__init__(traj_files, shard_size, indices)[source]
combine_trajs(traj_files, indices, local_fs)[source]

Combines configurations from all provided trajectories into a single list of Atoms objects.

Parameters:
  • traj_files (list[str]) – List of extxyz files containing atomic configurations.

  • indices (slice) – Slice object specifying which configurations to read from each trajectory file.

  • local_fs (FileSystemHandlerBase) – Filesystem handler for reading trajectory files.

Return type:

list[Atoms]

Returns:

List of Atoms objects. Two attributes are stored as entries in the info dict, making each Atoms object unambiguously attributable to its origin:

  • file_index: The index of the trajectory file from which the configuration was taken.

  • iteration_index: The index of the configuration in its original file.

read_and_shard(local_fs)[source]

Reads all configurations from the provided trajectory files and shards them into batches of size shard_size. A shard_size of None or a negative value processes the whole set as one shard.

Parameters:

local_fs (FileSystemHandlerBase) – Filesystem handler for reading trajectory files.

Return type:

list[list[Atoms]]

Returns:

List of sharded Atoms lists.

collect(calcdir, remote_fs, num_array_tasks, map_indices, tag, only_finished=True)[source]

Scan calculation directories for extxyz files containing processed Atoms objects.

Parameters:
  • calcdir (Path) – Base calculation directory containing subdirectories 0, 1, 2, …

  • remote_fs (FileSystemHandlerBase) – Filesystem handler for accessing remote files.

  • num_array_tasks (int) – Number of array tasks to collect from.

  • map_indices (Optional[list[int]]) – Optional mapping of task indices (for recompute scenarios).

  • tag (str) – Tag used to identify result files.

  • only_finished (bool) – If True, only collect configurations that have the is_finished flag set to True in their info dict.

Returns:

  • A list of all collected Atoms objects.

  • A list of indices of batches that failed to process.

Return type:

tuple[list[Atoms], list[int]]

regroup(all_atoms)[source]

Regroup a flat list of Atoms objects into a list of lists, where each sublist corresponds to the configurations from a single original trajectory file.

Parameters:

all_atoms (list[Atoms]) – A flat list of Atoms objects, each with an info dict containing a ‘file_index’ key that indicates the original trajectory file index.

Return type:

list[list[Atoms]]

Returns:

A list of lists, where each sublist contains Atoms objects from the same original trajectory file.

redistribute(all_atoms_sets, local_fs, tag)[source]

Redistribute the grouped Atoms objects back into their original trajectory files, writing them to the local file system with the specified tag prepended to the filenames.

Parameters:
  • all_atoms_sets (list[list[Atoms]]) – List of lists, where each sublist contains Atoms from the same original trajectory file.

  • local_fs (FileSystemHandlerBase) – Filesystem handler for writing trajectory files.

  • tag (str) – Tag to prepend to output filenames.

check_and_harvest(all_atoms, failed_indices, local_fs, tag, savepath)[source]

Check for failed batches and redistribute collected configurations into their original trajectory files.

Parameters:
  • all_atoms (list[Atoms]) – All collected Atoms objects.

  • failed_indices (list[int]) – Indices of batches that failed.

  • local_fs (FileSystemHandlerBase) – Filesystem handler for writing results.

  • tag (str) – Tag to prepend to output filenames.

  • savepath (Path) – Path to check for SLURM output (for error messages).

Raises:

Exception – If any batches failed or if collected count is insufficient.

Trajectory Processing

A guide with examples is in Trajectory Processing.

remote_handler.processing is a self-contained plugin framework: a single composable core (RemoteTrajectoryProcessor) runs an ordered list of Processor steps over a shared sharding/collection base, and RemoteOptimizationHandler is a thin factory for the optimize step. Structural analysis is just the core with the processors you want (e.g. processors=[RDFProcessor(), SteinhardtProcessor()]). Each built-in processor keeps its arg schema, cluster-side run, and host-side Processor spec in one module under processing/processors/.

Trajectory processing – a self-contained, extensible plugin framework.

Unlike the rest of the package (organized by layer: core / workflows / scripts), this feature is organized by feature, because it is a different kind of thing: an extensible registry of processors, each a tight trio of

  • a host-side spec (Processor),

  • a cluster-side run, and

  • a shared arg schema,

wired together by a registry and a shard driver. A built-in processor keeps all three in one module under processors/ (e.g. processors/optimize.py); downstream processors do the same in their own package and self-register.

Public surface:

class remote_handler.processing.Processor[source]

Bases: ABC

One processing step in the remote pipeline.

A Processor contributes only its own remote arguments and any files that must be staged for it – nothing about sharding or transport. Its name keys both the ordered steps list and the per-step args map in the shard input JSON, and must match a processor in the registry.

Subclassing is low-ceremony: set a class-level name and implement build_args(). registration_module defaults to the subclass’s own module (so a downstream processor defined alongside its run + register call resolves on the cluster with nothing else to declare); built-ins, whose run is always loaded, set it to None. A missing name is caught at class-definition time.

name: str

Registry key; must match a remote processor’s registered name.

registration_module: Optional[str] = None

Import path of the module whose import registers this step’s run in the cluster-side REGISTRY (via register(name, run)). None for built-in processors, which are already in the always-loaded registry. Defaults (via __init_subclass__) to the subclass’s own module.

abstractmethod build_args(savepath)[source]

Return this step’s remote args.

Parameters:

savepath (str) – Remote working directory, for resolving the paths of any files this processor stages (see shared_files()).

Return type:

dict

shared_files()[source]

Files staged once and shared across all shards (default: none).

Return type:

list

class remote_handler.processing.RemoteTrajectoryProcessor(traj_files, cluster_config, remote_fs, n_processors, shard_size, savepath, num_parallel, processors, *, stub=False, python_script_path=None, tag='proc', loop_time=30, jobname='proc', every=None, start=None, end=None, local_savepath=None, logfile='proc.log', collect_only=False, slurm_header_add='module load openblas')[source]

Bases: RemoteAtomsHandler

Run an ordered pipeline of Processor steps over a trajectory.

Shards the input trajectories, ships each shard a per-shard input JSON (the ordered steps + per-step args) plus its atoms batch and any shared files, runs the array job, then collects and reshapes the results. The trajectory is distributed once regardless of how many steps run.

Parameters:
  • traj_files (str) – Trajectory .extxyz file(s) to process.

  • cluster_config (ClusterConfig) – Target cluster configuration.

  • remote_fs (FileSystemHandlerBase) – Filesystem handler for the machine where jobs run.

  • n_processors (int) – Processors (or GPUs) requested per array task.

  • shard_size (Optional[int]) – Number of configurations per shard. None or a negative value (e.g. -1) processes all configs in one shard.

  • savepath (str) – Remote working directory for the array job.

  • num_parallel (int) – Maximum array tasks to run concurrently.

  • processors (list[Processor]) – Ordered processing steps to run on each shard.

  • stub (bool) – If True, the remote payload runs in mock mode.

  • python_script_path (Optional[PathLike]) – Remote payload; defaults to the shipped driver.py.

  • tag (str) – Output-file tag (drives collection).

  • loop_time (float) – Seconds between completion polls.

  • jobname (str) – SLURM job name.

  • every/start/end – Optional slice applied before sharding.

  • local_savepath (Optional[PathLike]) – Optional local directory to mirror results into.

  • logfile (str) – Per-task log filename.

  • collect_only (bool) – If True, skip staging and only collect prior results.

  • slurm_header_add (str) – Extra SLURM header lines (default loads OpenBLAS, which the processor payloads link against).

__init__(traj_files, cluster_config, remote_fs, n_processors, shard_size, savepath, num_parallel, processors, *, stub=False, python_script_path=None, tag='proc', loop_time=30, jobname='proc', every=None, start=None, end=None, local_savepath=None, logfile='proc.log', collect_only=False, slurm_header_add='module load openblas')[source]
prepare_individual_data()[source]

Build the per-shard input JSON + atoms batch for every shard.

run()[source]

Stage, submit, and collect+reshape the results.

class remote_handler.processing.RemoteOptimizationHandler(traj_files, cluster_config, remote_fs, n_processors, shard_size, savepath, num_parallel, pickle_file=None, optimization_backend='NNFF', fmax=0.1, steps=200, max_neighbors=60, max_neighbors_list=None, neighbor_offset=0, supercell_diag=(1, 1, 1), python_script_path=None, stub=False, loop_time=30, jobname='opt', every=None, start=None, end=None, local_savepath=None, logfile='opt.log', collect_only=False, tag='opt')[source]

Bases: RemoteTrajectoryProcessor

Optimize a sharded trajectory (a one-step OptimizeProcessor).

__init__(traj_files, cluster_config, remote_fs, n_processors, shard_size, savepath, num_parallel, pickle_file=None, optimization_backend='NNFF', fmax=0.1, steps=200, max_neighbors=60, max_neighbors_list=None, neighbor_offset=0, supercell_diag=(1, 1, 1), python_script_path=None, stub=False, loop_time=30, jobname='opt', every=None, start=None, end=None, local_savepath=None, logfile='opt.log', collect_only=False, tag='opt')[source]
class remote_handler.processing.OptimizeProcessor(pickle_file=None, backend='NNFF', fmax=0.1, steps=200, max_neighbors=60, max_neighbors_list=None, neighbor_offset=0, supercell_diag=(1, 1, 1))[source]

Bases: Processor

Relax each structure with an NNFF/MACE ensemble or an LJ calculator.

name: str = 'optimize'

Registry key; must match a remote processor’s registered name.

registration_module: Optional[str] = None

Import path of the module whose import registers this step’s run in the cluster-side REGISTRY (via register(name, run)). None for built-in processors, which are already in the always-loaded registry. Defaults (via __init_subclass__) to the subclass’s own module.

__init__(pickle_file=None, backend='NNFF', fmax=0.1, steps=200, max_neighbors=60, max_neighbors_list=None, neighbor_offset=0, supercell_diag=(1, 1, 1))[source]
build_args(savepath)[source]

Return this step’s remote args.

Parameters:

savepath (str) – Remote working directory, for resolving the paths of any files this processor stages (see shared_files()).

Return type:

dict

shared_files()[source]

Files staged once and shared across all shards (default: none).

Return type:

list

class remote_handler.processing.RDFProcessor(cutoff=5.0, nbins=200)[source]

Bases: Processor

Annotate structures with the radial distribution function.

name: str = 'rdf'

Registry key; must match a remote processor’s registered name.

registration_module: Optional[str] = None

Import path of the module whose import registers this step’s run in the cluster-side REGISTRY (via register(name, run)). None for built-in processors, which are already in the always-loaded registry. Defaults (via __init_subclass__) to the subclass’s own module.

__init__(cutoff=5.0, nbins=200)[source]
build_args(savepath)[source]

Return this step’s remote args.

Parameters:

savepath (str) – Remote working directory, for resolving the paths of any files this processor stages (see shared_files()).

Return type:

dict

class remote_handler.processing.SteinhardtProcessor(r_cut, *, l_values=(4, 6), r_cut_min=0.0)[source]

Bases: Processor

Annotate structures with Steinhardt bond-orientational order params.

name: str = 'steinhardt'

Registry key; must match a remote processor’s registered name.

registration_module: Optional[str] = None

Import path of the module whose import registers this step’s run in the cluster-side REGISTRY (via register(name, run)). None for built-in processors, which are already in the always-loaded registry. Defaults (via __init_subclass__) to the subclass’s own module.

__init__(r_cut, *, l_values=(4, 6), r_cut_min=0.0)[source]
build_args(savepath)[source]

Return this step’s remote args.

Parameters:

savepath (str) – Remote working directory, for resolving the paths of any files this processor stages (see shared_files()).

Return type:

dict

class remote_handler.processing.OptimizeArgs(backend, fmax, steps, pickle_file=None, max_neighbors=None, max_neighbors_list=None, neighbor_offset=None, supercell_diag=None)[source]

Bases: ScriptInput

Args for the optimize processor.

backend/fmax/steps are always required; the NNFF/MACE backends additionally need a pickle_file (the staged model) and carry the neighbour-bucket / supercell knobs. Fields left None are dropped by to_dict so an LJ payload stays minimal.

backend: str
fmax: float
steps: int
pickle_file: Optional[str] = None
max_neighbors: Optional[int] = None
max_neighbors_list: Optional[list] = None
neighbor_offset: Optional[int] = None
supercell_diag: Optional[list] = None
validate(root=None)[source]

Validate configuration parameters.

Override in subclasses to add domain-specific checks. Data-shape checks (types, ranges, required combinations) always run. Path-existence checks run only when root is given – pass the script’s calc dir so in-bundle paths can be resolved and verified on the remote.

Raises:

ScriptInputError – If any parameter is invalid

Return type:

None

__init__(backend, fmax, steps, pickle_file=None, max_neighbors=None, max_neighbors_list=None, neighbor_offset=None, supercell_diag=None)
class remote_handler.processing.RdfArgs(cutoff, nbins)[source]

Bases: ScriptInput

Args for the rdf processor.

cutoff: float
nbins: int
validate(root=None)[source]

Validate configuration parameters.

Override in subclasses to add domain-specific checks. Data-shape checks (types, ranges, required combinations) always run. Path-existence checks run only when root is given – pass the script’s calc dir so in-bundle paths can be resolved and verified on the remote.

Raises:

ScriptInputError – If any parameter is invalid

Return type:

None

__init__(cutoff, nbins)
class remote_handler.processing.SteinhardtArgs(l_values=list(), r_cut=0.0, r_cut_min=0.0)[source]

Bases: ScriptInput

Args for the steinhardt processor.

l_values: list
r_cut: float = 0.0
r_cut_min: float = 0.0
validate(root=None)[source]

Validate configuration parameters.

Override in subclasses to add domain-specific checks. Data-shape checks (types, ranges, required combinations) always run. Path-existence checks run only when root is given – pass the script’s calc dir so in-bundle paths can be resolved and verified on the remote.

Raises:

ScriptInputError – If any parameter is invalid

Return type:

None

__init__(l_values=<factory>, r_cut=0.0, r_cut_min=0.0)
class remote_handler.processing.ProcessTrajInput(tag, DATABASE, steps, args, STUB=False, registration_modules=list())[source]

Bases: ScriptInput

Input configuration for the trajectory-processing driver.

Drives a pipeline of processors over a trajectory shard. Rather than a fixed set of do_X flags, it carries an ordered list of processor steps and a per-step args map – so optimization and any structural analysis compose in one job, and adding a processor needs no schema change.

tag

Tag to prepend to output files

Type:

str

DATABASE

Path to input trajectory file

Type:

str

steps

Ordered processor names to run (e.g. ["optimize", "rdf"]); each must exist in the processor registry

Type:

list[str]

args

Map of processor name -> its argument dict

Type:

dict[str, Any]

STUB

If True, the remote payload runs in mock mode

Type:

bool

registration_modules

Import paths the driver imports (idempotently) before resolving steps, so downstream processors register their run in the registry. Empty for built-in-only pipelines.

Type:

list[str]

Example

>>> config = ProcessTrajInput.from_file(Path("input_process.json"))
>>> config.validate()
tag: str
DATABASE: str
steps: list[str]
args: dict[str, Any]
STUB: bool = False
registration_modules: list[str]
validate(root=None)[source]

Validate the coarse shape of a processor pipeline.

This checks only what a generic schema can: a trajectory is named, at least one step is requested, and args is a per-step map. It deliberately does not validate each step’s args – those contracts belong to the processors (including downstream ones), which this generic input model must not import. The driver enforces them per step via the registry’s validate_args right after importing the registration modules, so a malformed composed payload fails fast at job start.

Raises:

ScriptInputError – If any parameter is invalid

Return type:

None

__init__(tag, DATABASE, steps, args, STUB=False, registration_modules=<factory>)
remote_handler.processing.register(name, run, schema=None)[source]

Add (or override) a processor in the registry.

The extension point for downstream packages: a package that depends on both remote_handler and some heavier upstream can register its own custom processor here. Call this at module import time and define the matching host-side Processor subclass in the same module – its registration_module then defaults to that module, and the stock driver imports it before resolving steps, so nothing else is needed. Registration must be idempotent – re-importing the module simply re-registers the same run.

Parameters:
  • name – Registry key; must match the host-side Processor.name.

  • run – callable(atoms_list, args, calcpath) -> atoms_list.

  • schema – Optional ScriptInput subclass declaring this step’s arg contract. The driver validates the step’s args against it at job start (via from_dict(...).validate()), so a bad composed payload fails fast instead of deep inside a task. This is the same schema the host-side Processor.build_args fills, so the emit and check sides can’t drift. Omit for a permissive (unchecked) step.

remote_handler.processing.validate_args(name, args)[source]

Validate one step’s args against its processor’s schema, if any.

Round-trips args through the registered schema (schema.from_dict(args).validate()); raises ScriptInputError on a malformed payload. No-op when the processor registered no schema.

The Processor base – host-side spec for one pipeline step.

A Processor is the host half of a processing step: it declares only what to run, the remote arguments it needs, and any files to stage – nothing about sharding or transport (that is RemoteTrajectoryProcessor). Its cluster-side counterpart – the run function and the arg schema – lives in the same processor module under processors/ (built-ins) or in a downstream package (see register()).

class remote_handler.processing.base.Processor[source]

Bases: ABC

One processing step in the remote pipeline.

A Processor contributes only its own remote arguments and any files that must be staged for it – nothing about sharding or transport. Its name keys both the ordered steps list and the per-step args map in the shard input JSON, and must match a processor in the registry.

Subclassing is low-ceremony: set a class-level name and implement build_args(). registration_module defaults to the subclass’s own module (so a downstream processor defined alongside its run + register call resolves on the cluster with nothing else to declare); built-ins, whose run is always loaded, set it to None. A missing name is caught at class-definition time.

name: str

Registry key; must match a remote processor’s registered name.

registration_module: Optional[str] = None

Import path of the module whose import registers this step’s run in the cluster-side REGISTRY (via register(name, run)). None for built-in processors, which are already in the always-loaded registry. Defaults (via __init_subclass__) to the subclass’s own module.

abstractmethod build_args(savepath)[source]

Return this step’s remote args.

Parameters:

savepath (str) – Remote working directory, for resolving the paths of any files this processor stages (see shared_files()).

Return type:

dict

shared_files()[source]

Files staged once and shared across all shards (default: none).

Return type:

list

Remote per-shard trajectory processing – the data-movement layer.

A trajectory (set of .extxyz files) is sharded into batches; each batch is processed in its own array-job task on a remote cluster, and the results are collected and reshaped back into the original layout.

The design separates the two concerns that pulled against each other:

  • Data movement (shared): sharding, distributing the trajectory, and collecting/reshaping results – done once, in RemoteTrajectoryProcessor (and, beneath it, RemoteAtomsHandler).

  • Computation (composable): a list of Processor steps. The remote driver (driver.py) reads a shard once and runs the requested steps in order via the registry, so a single job can e.g. optimize then characterize the relaxed structures, with the trajectory distributed only once.

RemoteOptimizationHandler is a thin factory over the same core for the one common case whose processor has a wide constructor (the optimize step). Analysis has no dedicated handler: it is just RemoteTrajectoryProcessor with the processors you want, e.g. processors=[RDFProcessor(), SteinhardtProcessor()] – RDF is one processor among many, not a handler feature.

Downstream steps self-register: a Processor declares its registration_module, and the stock driver imports those modules on the cluster before resolving steps – so a downstream processor (e.g. a jaxrens-based Steinhardt) works with no custom driver.

class remote_handler.processing.handler.RemoteTrajectoryProcessor(traj_files, cluster_config, remote_fs, n_processors, shard_size, savepath, num_parallel, processors, *, stub=False, python_script_path=None, tag='proc', loop_time=30, jobname='proc', every=None, start=None, end=None, local_savepath=None, logfile='proc.log', collect_only=False, slurm_header_add='module load openblas')[source]

Bases: RemoteAtomsHandler

Run an ordered pipeline of Processor steps over a trajectory.

Shards the input trajectories, ships each shard a per-shard input JSON (the ordered steps + per-step args) plus its atoms batch and any shared files, runs the array job, then collects and reshapes the results. The trajectory is distributed once regardless of how many steps run.

Parameters:
  • traj_files (str) – Trajectory .extxyz file(s) to process.

  • cluster_config (ClusterConfig) – Target cluster configuration.

  • remote_fs (FileSystemHandlerBase) – Filesystem handler for the machine where jobs run.

  • n_processors (int) – Processors (or GPUs) requested per array task.

  • shard_size (Optional[int]) – Number of configurations per shard. None or a negative value (e.g. -1) processes all configs in one shard.

  • savepath (str) – Remote working directory for the array job.

  • num_parallel (int) – Maximum array tasks to run concurrently.

  • processors (list[Processor]) – Ordered processing steps to run on each shard.

  • stub (bool) – If True, the remote payload runs in mock mode.

  • python_script_path (Optional[PathLike]) – Remote payload; defaults to the shipped driver.py.

  • tag (str) – Output-file tag (drives collection).

  • loop_time (float) – Seconds between completion polls.

  • jobname (str) – SLURM job name.

  • every/start/end – Optional slice applied before sharding.

  • local_savepath (Optional[PathLike]) – Optional local directory to mirror results into.

  • logfile (str) – Per-task log filename.

  • collect_only (bool) – If True, skip staging and only collect prior results.

  • slurm_header_add (str) – Extra SLURM header lines (default loads OpenBLAS, which the processor payloads link against).

__init__(traj_files, cluster_config, remote_fs, n_processors, shard_size, savepath, num_parallel, processors, *, stub=False, python_script_path=None, tag='proc', loop_time=30, jobname='proc', every=None, start=None, end=None, local_savepath=None, logfile='proc.log', collect_only=False, slurm_header_add='module load openblas')[source]
prepare_individual_data()[source]

Build the per-shard input JSON + atoms batch for every shard.

run()[source]

Stage, submit, and collect+reshape the results.

class remote_handler.processing.handler.RemoteOptimizationHandler(traj_files, cluster_config, remote_fs, n_processors, shard_size, savepath, num_parallel, pickle_file=None, optimization_backend='NNFF', fmax=0.1, steps=200, max_neighbors=60, max_neighbors_list=None, neighbor_offset=0, supercell_diag=(1, 1, 1), python_script_path=None, stub=False, loop_time=30, jobname='opt', every=None, start=None, end=None, local_savepath=None, logfile='opt.log', collect_only=False, tag='opt')[source]

Bases: RemoteTrajectoryProcessor

Optimize a sharded trajectory (a one-step OptimizeProcessor).

__init__(traj_files, cluster_config, remote_fs, n_processors, shard_size, savepath, num_parallel, pickle_file=None, optimization_backend='NNFF', fmax=0.1, steps=200, max_neighbors=60, max_neighbors_list=None, neighbor_offset=0, supercell_diag=(1, 1, 1), python_script_path=None, stub=False, loop_time=30, jobname='opt', every=None, start=None, end=None, local_savepath=None, logfile='opt.log', collect_only=False, tag='opt')[source]

The cluster-side processor registry.

Maps a step name to its run callable and (optionally) its arg schema. The driver looks steps up here and runs them in order over a shard; validate_args enforces each step’s arg contract at job start. This module holds only the machinery – the built-ins register themselves when processing.processors is imported, and downstream packages call register() at their import time.

remote_handler.processing.registry.REGISTRY = {'optimize': <function run>, 'rdf': <function run>, 'steinhardt': <function run>}

Step name -> callable(atoms_list, args, calcpath) -> atoms_list.

remote_handler.processing.registry.register(name, run, schema=None)[source]

Add (or override) a processor in the registry.

The extension point for downstream packages: a package that depends on both remote_handler and some heavier upstream can register its own custom processor here. Call this at module import time and define the matching host-side Processor subclass in the same module – its registration_module then defaults to that module, and the stock driver imports it before resolving steps, so nothing else is needed. Registration must be idempotent – re-importing the module simply re-registers the same run.

Parameters:
  • name – Registry key; must match the host-side Processor.name.

  • run – callable(atoms_list, args, calcpath) -> atoms_list.

  • schema – Optional ScriptInput subclass declaring this step’s arg contract. The driver validates the step’s args against it at job start (via from_dict(...).validate()), so a bad composed payload fails fast instead of deep inside a task. This is the same schema the host-side Processor.build_args fills, so the emit and check sides can’t drift. Omit for a permissive (unchecked) step.

remote_handler.processing.registry.validate_args(name, args)[source]

Validate one step’s args against its processor’s schema, if any.

Round-trips args through the registered schema (schema.from_dict(args).validate()); raises ScriptInputError on a malformed payload. No-op when the processor registered no schema.

DFT Runner

Single-point ground-truth handlers (DFT and other ASE calculators).

All single-point evaluation on a remote cluster follows the same shape: shard the configurations one-per-job, ship each with a small JSON describing the calculator, run a remote payload that attaches an ASE calculator and writes a labelled dft_<DB>.extxyz + is_finished.info, then collect. The only thing that varies between VASP, ORCA, EMT, … is which calculator the payload builds and the settings it receives.

SinglePointHandler owns that shared machinery; VASPHandler and ORCAHandler are thin presets that only assemble their calculator config and default remote script. Their public signatures are unchanged.

remote_handler.workflows.dft_runner.resolve_incar_kwargs(incar_kwargs=None, incar_config_file=None)[source]

Resolve the VASP INCAR settings from an explicit dict and/or a YAML file.

The INCAR tags can be supplied as a dict (incar_kwargs) or read from a YAML file (incar_config_file):

  • incar_config_file only -> the YAML contents.

  • incar_kwargs only -> that dict, as-is (historical behaviour).

  • both -> the YAML as a base, with incar_kwargs overriding on top.

  • neither -> the built-in single-point r2SCAN defaults.

Return type:

dict

class remote_handler.workflows.dft_runner.SinglePointHandler(traj_files, cluster_config, remote_fs, savepath, num_parallel, python_script_path, calc_config, loop_time=30, jobname='DFT_Eval', every=None, start=None, end=None, local_savepath=None, logfile='dft.log', collect_only=False, tag='dft', n_processors=8, slurm_header_add='', environment_key=None, time_limit=None, memory=None)[source]

Bases: RemoteAtomsHandler

Run one ASE-calculator single-point per configuration as a job array.

Calculator-agnostic: it ships calc_config (the per-job input JSON) and runs python_script_path on the remote. Concrete calculators are expressed as presets that fill in calc_config and the default script (see VASPHandler, ORCAHandler).

Parameters:
  • traj_files (list[Union[str, PathLike]]) – Trajectory file(s) with the configurations to evaluate.

  • cluster_config (ClusterConfig) – Target cluster configuration.

  • remote_fs (FileSystemHandlerBase) – Filesystem handler for the machine running the evaluation.

  • savepath (str) – Remote root path for the computation.

  • num_parallel (int) – Number of array jobs to run in parallel.

  • python_script_path (PathLike) – Remote payload that builds the calculator and writes dft_<DB>.extxyz + is_finished.info.

  • calc_config (dict) – Calculator settings written into each job’s input JSON.

  • loop_time (float) – Minutes between polls for completion.

  • jobname (str) – SLURM job name.

  • every (Optional[int]) – Take every every-th frame from the trajectories.

  • start (Optional[int]) – First frame index to take.

  • end (Optional[int]) – Last frame index to take.

  • local_savepath (Optional[PathLike]) – Local path the results are collected to.

  • logfile (str) – Log file name.

  • collect_only (bool) – If True, only collect results (no submission).

  • tag (str) – Tag prepended to collected trajectory filenames.

  • n_processors (int) – Processors requested per job.

  • slurm_header_add (str) – Legacy per-call SLURM header lines. If given, it takes precedence over the cluster’s environment[environment_key] (a DeprecationWarning fires when both are set); the two are never combined.

  • environment_key (Optional[str]) – Key into cluster_config.environment for this application’s cluster setup (e.g. "vasp"). None injects nothing – the historical behaviour.

  • time_limit (Optional[str]) – SLURM --time value (e.g. "0-02:00:00") to cap each job – useful to kill hanging DFT runs. None (default) emits no --time directive, so the job runs to the partition maximum.

  • memory (Optional[str]) – SLURM --mem value (e.g. "16G", "2000M", or MB as a bare number) requested per job. None (default) emits no --mem directive, so the job gets the partition default.

__init__(traj_files, cluster_config, remote_fs, savepath, num_parallel, python_script_path, calc_config, loop_time=30, jobname='DFT_Eval', every=None, start=None, end=None, local_savepath=None, logfile='dft.log', collect_only=False, tag='dft', n_processors=8, slurm_header_add='', environment_key=None, time_limit=None, memory=None)[source]
prepare_individual_data()[source]

Write one input JSON + one structure file per array task.

run()[source]

Allocate inputs, submit the array, and collect results.

class remote_handler.workflows.dft_runner.VASPHandler(traj_files, cluster_config, remote_fs, savepath, num_parallel, loop_time=30, jobname='DFT_Eval', every=None, start=None, end=None, local_savepath=None, logfile='dft.log', collect_only=False, tag='dft', python_script_path=None, stub=False, launcher='mpiexec -np', slurm_header_add='', vasp_binary='vasp_std', n_processors=8, incar_kwargs=None, incar_config_file=None, time_limit=None, memory=None)[source]

Bases: SinglePointHandler

VASP single-point preset of SinglePointHandler.

Builds the VASP calc_config (INCAR tags + launch command) and defaults to the shipped scripts/dft_singlepoint.py payload. Public signature is unchanged from the historical handler.

Parameters:
  • traj_files (list[Union[str, PathLike]]) – Trajectory file(s) with configurations to evaluate.

  • cluster_config (ClusterConfig) – Target cluster configuration.

  • remote_fs (FileSystemHandlerBase) – Filesystem handler for the evaluation machine.

  • savepath (str) – Remote root path for the computation.

  • num_parallel (int) – Number of array jobs to run in parallel.

  • loop_time (float) – Minutes between polls for completion.

  • jobname (str) – SLURM job name.

  • every (Optional[int]) – Take every every-th frame from the trajectories.

  • start (Optional[int]) – First frame index to take.

  • end (Optional[int]) – Last frame index to take.

  • local_savepath (Optional[PathLike]) – Local path the results are collected to.

  • logfile (str) – Log file name.

  • collect_only (bool) – If True, only collect results (no submission).

  • tag (str) – Tag prepended to collected trajectory filenames.

  • python_script_path (Optional[str]) – Remote payload; defaults to the shipped dft_singlepoint.py.

  • stub (bool) – Accepted for backward compatibility; stubbing is handled by VASPEvaluator, not the handler.

  • launcher (str) – MPI launch command prefix (e.g. "mpiexec -np").

  • slurm_header_add (str) – Extra SLURM header lines.

  • vasp_binary (str) – Name of the VASP executable.

  • n_processors (int) – Processors requested per job.

  • incar_kwargs (Optional[dict]) – VASP INCAR tags; defaults to a single-point r2SCAN set.

  • incar_config_file (Optional[PathLike]) – Optional path to a YAML file of INCAR tags, used instead of (or as a base for) incar_kwargs – see resolve_incar_kwargs().

__init__(traj_files, cluster_config, remote_fs, savepath, num_parallel, loop_time=30, jobname='DFT_Eval', every=None, start=None, end=None, local_savepath=None, logfile='dft.log', collect_only=False, tag='dft', python_script_path=None, stub=False, launcher='mpiexec -np', slurm_header_add='', vasp_binary='vasp_std', n_processors=8, incar_kwargs=None, incar_config_file=None, time_limit=None, memory=None)[source]
class remote_handler.workflows.dft_runner.ORCAHandler(traj_files, remote_fs, cluster_config, savepath, num_parallel, loop_time=30, jobname='DFT_Eval', every=None, start=None, end=None, local_savepath=None, logfile='orca.log', collect_only=False, tag='orca', python_script_path=None, slurm_header_add='', orca_binary='/opt/ohpc/pub/dft/orca_6_1_0/orca', n_processors=8, orcasimpleinput='wB97X 6-31G(d) ENGRAD', time_limit=None, memory=None)[source]

Bases: SinglePointHandler

ORCA single-point preset of SinglePointHandler.

Builds the ORCA calc_config and defaults to the shipped scripts/orca_singlepoint.py payload. Keeps its historical (traj_files, remote_fs, cluster_config, ...) argument order (remote_fs and cluster_config swapped relative to VASPHandler) for backward compatibility.

Parameters:
  • traj_files (list[Union[str, PathLike]]) – Trajectory file(s) with configurations to evaluate.

  • remote_fs (FileSystemHandlerBase) – Filesystem handler for the evaluation machine.

  • cluster_config (ClusterConfig) – Target cluster configuration.

  • savepath (str) – Remote root path for the computation.

  • num_parallel (int) – Number of array jobs to run in parallel.

  • loop_time (float) – Minutes between polls for completion.

  • jobname (str) – SLURM job name.

  • every (Optional[int]) – Take every every-th frame from the trajectories.

  • start (Optional[int]) – First frame index to take.

  • end (Optional[int]) – Last frame index to take.

  • local_savepath (Optional[PathLike]) – Local path the results are collected to.

  • logfile (str) – Log file name.

  • collect_only (bool) – If True, only collect results (no submission).

  • tag (str) – Tag prepended to collected trajectory filenames.

  • python_script_path (Optional[str]) – Remote payload; defaults to the shipped orca_singlepoint.py.

  • slurm_header_add (str) – Extra SLURM header lines.

  • orca_binary (str) – Full path to the ORCA executable.

  • n_processors (int) – Processors requested per job.

  • orcasimpleinput (str) – ORCA simple-input line (functional, basis, method).

__init__(traj_files, remote_fs, cluster_config, savepath, num_parallel, loop_time=30, jobname='DFT_Eval', every=None, start=None, end=None, local_savepath=None, logfile='orca.log', collect_only=False, tag='orca', python_script_path=None, slurm_header_add='', orca_binary='/opt/ohpc/pub/dft/orca_6_1_0/orca', n_processors=8, orcasimpleinput='wB97X 6-31G(d) ENGRAD', time_limit=None, memory=None)[source]

Workflows

Active Learning

See Active Learning Loops for the conceptual walkthrough of the actor interfaces and the staged handler documented below.

Active Learning Workflow Components.

This module provides workflow components for active learning pipelines:

  • Evaluators: Ground truth evaluation (e.g., DFT with VASP)

  • Samplers: Configuration sampling (concrete samplers live in downstream project repos; remote_handler provides only the Sampler interface)

  • Trainers: Model training (e.g., MACE models)

Required Dependencies:

  • ase: Atomic simulation environment (atoms handling)

  • numpy: Numerical operations

Each component can run in stub mode for testing without actual execution.

class remote_handler.workflows.AseCalculatorEvaluator(singlepoint_script, remote_fs, cluster_config, num_parallel, calc_config, remote_savepath=None, loop_time=30, required_fraction=0.5, n_processors=8, stub=False, slurm_header_add='', time_limit=None, collect_only=False, reattach_max_wait=None)[source]

Bases: DetachableTaskMixin, GroundTruthEvaluator

Single-point ground-truth evaluation with any ASE calculator.

Calculator-agnostic: it ships calc_config (the per-job input JSON) and runs singlepoint_script on the remote, which builds the calculator, computes energy + forces, and writes a labelled dft_<DB>.extxyz. Concrete calculators are presets that assemble calc_config (see VASPEvaluator, ORCAEvaluator).

Parameters:
  • singlepoint_script (PathLike) – Remote payload that builds the calculator.

  • remote_fs (FileSystemHandlerBase) – Filesystem handler for the evaluation machine.

  • cluster_config (ClusterConfig) – Target cluster configuration.

  • num_parallel (int) – Number of parallel jobs to queue.

  • calc_config (dict) – Calculator settings written into each job’s input JSON.

  • remote_savepath (Optional[PathLike]) – Remote path for the calculation files.

  • loop_time (float) – Seconds between polls for completion.

  • required_fraction (float) – Fraction of jobs that must succeed to proceed.

  • n_processors (int) – CPU cores per job.

  • stub (bool) – If True, produce mock outputs without running anything.

  • slurm_header_add (str) – Extra SLURM header lines (appended after any cluster-declared environment setup for this calculator).

  • time_limit (Optional[str]) – SLURM --time value (e.g. "0-02:00:00") capping each job. None (default) emits no --time, so the job runs to the partition maximum.

  • collect_only (bool) – If True, update reconstructs the array submitted by an earlier, collect_only=False call (from the manifest written beside <calcdir>/dft/results, via RemoteAtomsHandler.from_manifest) instead of allocating/submitting a new one, and get_evaluated_configs skips the (already-done) submission. evaluator_input is not read in this mode. Use this to collect a detached evaluation run from a fresh process.

  • reattach_max_wait (Optional[float]) – Only used when collect_only: how long (in seconds) to wait for the reattached job to finish before giving up. None (default) waits forever.

__init__(singlepoint_script, remote_fs, cluster_config, num_parallel, calc_config, remote_savepath=None, loop_time=30, required_fraction=0.5, n_processors=8, stub=False, slurm_header_add='', time_limit=None, collect_only=False, reattach_max_wait=None)[source]
apply_schedule(kwargs)[source]

Set scheduled values as attributes; rebuild calc_config when one of them is baked into it (e.g. VASP’s incar_kwargs), so the new value reaches the job.

Return type:

None

update(calcdir, evaluator_input, **kwargs)[source]

Prepare the evaluator for a new iteration.

Parameters:
  • calcdir (Path) – Directory for this AL iteration.

  • evaluator_input (Union[Path, list[Path], None]) – Path(s) to unlabelled configs to evaluate. Not read when collect_only – a second process reconstructing an already-submitted array from its manifest needs none of the original input, so None is expected there.

  • **kwargs – Additional parameters.

Return type:

None

get_evaluated_configs()[source]

Run the evaluation and collect the labelled configurations.

Return type:

Path

Returns:

Path to the .extxyz of evaluated configurations.

Raises:

TaskError – If fewer than required_fraction jobs succeed (or, when collect_only, if that doesn’t happen within reattach_max_wait).

class remote_handler.workflows.VASPEvaluator(remote_fs, cluster_config, num_parallel, singlepoint_script=None, incar_kwargs=None, remote_savepath=None, launcher='mpirun -n', stub=False, loop_time=30, required_fraction=0.5, n_processors=8, slurm_header_add='', incar_config_file=None, time_limit=None, collect_only=False, reattach_max_wait=None)[source]

Bases: AseCalculatorEvaluator

VASP DFT preset of AseCalculatorEvaluator.

Parameters:
  • remote_fs (FileSystemHandlerBase) – Filesystem handler for the evaluation machine.

  • cluster_config (ClusterConfig) – Target cluster configuration.

  • num_parallel (int) – Number of parallel SLURM jobs to queue.

  • singlepoint_script (Optional[PathLike]) – Remote payload; defaults to the shipped dft_singlepoint.py.

  • incar_kwargs (Optional[dict]) – VASP INCAR tags (optional if incar_config_file is given).

  • remote_savepath (Optional[PathLike]) – Remote path for the calculation files.

  • launcher (str) – VASP launch prefix (e.g. "mpirun -n").

  • stub (bool) – If True, produce mock outputs without running VASP.

  • loop_time (float) – Seconds between polls for completion.

  • required_fraction (float) – Fraction of jobs that must succeed.

  • n_processors (int) – CPU cores per VASP job.

  • slurm_header_add (str) – Legacy per-call SLURM header lines. If given it takes precedence over the cluster’s environment["vasp"] (and emits a DeprecationWarning when both are set). Prefer putting the VASP module load and VASP_PP_PATH in that cluster JSON entry.

  • incar_config_file (Optional[PathLike]) – Optional path to a YAML file of INCAR tags, used instead of (or as a base for) incar_kwargs.

  • collect_only (bool) – If True, update reconstructs the array submitted by an earlier, collect_only=False call instead of allocating/submitting a new one. See AseCalculatorEvaluator’s docstring.

  • reattach_max_wait (Optional[float]) – Only used when collect_only: how long (in seconds) to wait for the reattached job to finish before giving up. None (default) waits forever.

__init__(remote_fs, cluster_config, num_parallel, singlepoint_script=None, incar_kwargs=None, remote_savepath=None, launcher='mpirun -n', stub=False, loop_time=30, required_fraction=0.5, n_processors=8, slurm_header_add='', incar_config_file=None, time_limit=None, collect_only=False, reattach_max_wait=None)[source]
property vasp_handler

Backward-compatible alias for the underlying handler.

class remote_handler.workflows.ORCAEvaluator(cluster_config, remote_fs, num_parallel, orcasimpleinput, singlepoint_script=None, remote_savepath=None, loop_time=30, required_fraction=0.8, n_processors=2, orca_binary='/opt/ohpc/pub/dft/orca_6_1_0/orca', stub=False, slurm_header_add='', time_limit=None, collect_only=False, reattach_max_wait=None)[source]

Bases: AseCalculatorEvaluator

ORCA DFT preset of AseCalculatorEvaluator.

Parameters:
  • cluster_config (ClusterConfig) – Target cluster configuration.

  • remote_fs (FileSystemHandlerBase) – Filesystem handler for the evaluation machine.

  • num_parallel (int) – Number of parallel SLURM jobs to queue.

  • orcasimpleinput (str) – ORCA simple-input line (functional, basis, method).

  • singlepoint_script (Optional[PathLike]) – Remote payload; defaults to the shipped orca_singlepoint.py.

  • remote_savepath (Optional[PathLike]) – Remote path for the calculation files.

  • loop_time (float) – Seconds between polls for completion.

  • required_fraction (float) – Fraction of jobs that must succeed.

  • n_processors (int) – CPU cores per ORCA job.

  • orca_binary (str) – Full path to the ORCA executable.

  • stub (bool) – If True, produce mock outputs without running ORCA.

  • slurm_header_add (str) – Legacy per-call SLURM header lines. If given it takes precedence over the cluster’s environment["orca"] (and emits a DeprecationWarning when both are set). Prefer putting the ORCA module load in that cluster JSON entry.

  • collect_only (bool) – If True, update reconstructs the array submitted by an earlier, collect_only=False call instead of allocating/submitting a new one. See AseCalculatorEvaluator’s docstring.

  • reattach_max_wait (Optional[float]) – Only used when collect_only: how long (in seconds) to wait for the reattached job to finish before giving up. None (default) waits forever.

__init__(cluster_config, remote_fs, num_parallel, orcasimpleinput, singlepoint_script=None, remote_savepath=None, loop_time=30, required_fraction=0.8, n_processors=2, orca_binary='/opt/ohpc/pub/dft/orca_6_1_0/orca', stub=False, slurm_header_add='', time_limit=None, collect_only=False, reattach_max_wait=None)[source]
property orca_handler

Backward-compatible alias for the underlying handler.

class remote_handler.workflows.EMTEvaluator(remote_fs, cluster_config, num_parallel, singlepoint_script=None, calculator_kwargs=None, remote_savepath=None, loop_time=30, required_fraction=0.5, n_processors=1, stub=False, slurm_header_add='', time_limit=None, collect_only=False, reattach_max_wait=None)[source]

Bases: AseCalculatorEvaluator

Cheap EMT ground-truth preset (pure ASE, no external binary).

Uses the generic ase_singlepoint.py payload with ASE’s EMT calculator. EMT supports only a handful of elements (Ni, Cu, Pd, Ag, Pt, Au, Al, H, C, N, O), but needs no licensed software – ideal for examples and CI runs over the direct executor, where VASP/ORCA cannot run.

Parameters:
  • remote_fs (FileSystemHandlerBase) – Filesystem handler for the evaluation machine.

  • cluster_config (ClusterConfig) – Target cluster configuration.

  • num_parallel (int) – Number of parallel jobs to queue.

  • singlepoint_script (Optional[PathLike]) – Remote payload; defaults to the shipped ase_singlepoint.py.

  • calculator_kwargs (Optional[dict]) – Keyword arguments forwarded to EMT(...).

  • remote_savepath (Optional[PathLike]) – Remote path for the calculation files.

  • loop_time (float) – Seconds between polls for completion.

  • required_fraction (float) – Fraction of jobs that must succeed.

  • n_processors (int) – CPU cores per job.

  • stub (bool) – If True, produce mock outputs without running anything.

  • slurm_header_add (str) – Extra SLURM header lines.

  • collect_only (bool) – If True, update reconstructs the array submitted by an earlier, collect_only=False call instead of allocating/submitting a new one. See AseCalculatorEvaluator’s docstring.

  • reattach_max_wait (Optional[float]) – Only used when collect_only: how long (in seconds) to wait for the reattached job to finish before giving up. None (default) waits forever.

__init__(remote_fs, cluster_config, num_parallel, singlepoint_script=None, calculator_kwargs=None, remote_savepath=None, loop_time=30, required_fraction=0.5, n_processors=1, stub=False, slurm_header_add='', time_limit=None, collect_only=False, reattach_max_wait=None)[source]
class remote_handler.workflows.MaceFinetuningTrainer(remote_fs, cluster_config, config_file, foundation_model, training_script=None, remote_mace_train_runner=None, num_models=5, validation_fraction=0.1, remote_savepath=None, loop_time=30, stub=False, convert_to_jax=False, n_processors=1, jax_output_format='pkl', collect_only=False, reattach_max_wait=None)[source]

Bases: _MaceArrayTrainer

Trainer for finetuning MACE models from a foundation model.

Like MaceModelTrainer but stages a pretrained foundation model as an extra shared resource. The optional torch -> mace-jax conversion is inherited from the shared base and works the same way here.

Parameters:
  • remote_fs (FileSystemHandlerBase) – FileSystemHandlerBase for the machine where training runs

  • config_file (PathLike) – Path to MACE YAML config file

  • foundation_model (PathLike) – Path to the pretrained foundation model file

  • training_script (Optional[PathLike]) – Remote payload; defaults to the shipped mace/mace_finetuning.py.

  • remote_mace_train_runner (Optional[PathLike]) – Path to MACE run_train.py on the remote machine. Optional – if omitted, it is resolved automatically by probing the remote conda env (requires mace installed there).

  • num_models (int) – Number of models to train per generation

  • validation_fraction (float) – Fraction for train/validation split

  • remote_savepath (Optional[PathLike]) – Path on remote machine for calculation files

  • loop_time (float) – Interval (seconds) to poll for job completion

  • stub (bool) – If True, creates mock model outputs without training

  • convert_to_jax (bool) – If True, convert each trained torch model to a mace-jax bundle in the same job and return those paths from get_trained_model. The training (cluster) environment must then have both the torch MACE stack and mace-jax.

  • jax_output_format (str) – Bundle format when convert_to_jax – "pkl" (default; an opaque single-file pickle) or "bundle" (a directory with config.json + params.msgpack, the canonical inspectable format mace-jax’s loader / jaxrens consume).

  • collect_only (bool) – If True, update reconstructs the array task submitted by an earlier, collect_only=False call (from the manifest written beside <calcdir>/train/results) instead of allocating/submitting a new one, and get_trained_model skips the (already-done) submission. trainer_input is not read in this mode. Use this to collect a detached MACE training run from a fresh process.

  • reattach_max_wait (Optional[float]) – Only used when collect_only: how long (in seconds) to wait for the reattached job to finish before giving up. None (default) waits forever.

__init__(remote_fs, cluster_config, config_file, foundation_model, training_script=None, remote_mace_train_runner=None, num_models=5, validation_fraction=0.1, remote_savepath=None, loop_time=30, stub=False, convert_to_jax=False, n_processors=1, jax_output_format='pkl', collect_only=False, reattach_max_wait=None)[source]
class remote_handler.workflows.MaceModelTrainer(remote_fs, cluster_config, config_file, training_script=None, remote_mace_train_runner=None, num_models=5, validation_fraction=0.1, remote_savepath=None, loop_time=30, stub=False, n_processors=1, convert_to_jax=False, jax_output_format='pkl', collect_only=False, reattach_max_wait=None)[source]

Bases: _MaceArrayTrainer

Trainer for MACE models using array script tasks.

Trains multiple MACE models in parallel using different random seeds. Supports stub mode for testing without actual training.

Parameters:
  • remote_fs (FileSystemHandlerBase) – FileSystemHandlerBase for the machine where training runs

  • config_file (PathLike) – Path to MACE YAML config file

  • training_script (Optional[PathLike]) – Remote payload; defaults to the shipped mace/mace_training.py.

  • remote_mace_train_runner (Optional[PathLike]) – Path to MACE run_train.py on the remote machine. Optional – if omitted, it is resolved automatically by probing the remote conda env (requires mace installed there).

  • num_models (int) – Number of models to train per generation

  • validation_fraction (float) – Fraction for train/validation split

  • remote_savepath (Optional[PathLike]) – Path on remote machine for calculation files

  • loop_time (float) – Interval (seconds) to poll for job completion

  • stub (bool) – If True, creates mock model outputs without training

  • convert_to_jax (bool) – If True, convert each trained torch model to a mace-jax bundle in the same job and return those paths from get_trained_model. The training (cluster) environment must then have both the torch MACE stack and mace-jax.

  • jax_output_format (str) – Bundle format when convert_to_jax – "pkl" (default; an opaque single-file pickle) or "bundle" (a directory with config.json + params.msgpack, the canonical inspectable format mace-jax’s loader / jaxrens consume).

  • collect_only (bool) – If True, update reconstructs the array task submitted by an earlier, collect_only=False call (from the manifest written beside <calcdir>/train/results) instead of allocating/submitting a new one, and get_trained_model skips the (already-done) submission. trainer_input is not read in this mode. Use this to collect a detached MACE training run from a fresh process.

  • reattach_max_wait (Optional[float]) – Only used when collect_only: how long (in seconds) to wait for the reattached job to finish before giving up. None (default) waits forever.

class remote_handler.workflows.NeuralilILTrainer(remote_fs, cluster_config, training_script=None, remote_savepath=None, training_kwargs=None, stub=False, loop_time=30, config_file=None, collect_only=False, reattach_max_wait=None)[source]

Bases: DetachableTaskMixin, ModelTrainer

Trainer for NeuralIL models using JAXNEST framework.

Trains NeuralIL models with custom configuration. Supports stub mode for testing without actual training.

Hyperparameters resolve in three layers (later overrides earlier): built-in defaults < config_file (a YAML file you author) < training_kwargs (an explicit dict). All optional – with none given the built-in defaults are used.

Parameters:
  • training_script (Optional[PathLike]) – Remote payload; defaults to the shipped neuralil/neuralil_training.py.

  • remote_fs (FileSystemHandlerBase) – FileSystemHandlerBase for the machine where training runs

  • remote_savepath (Optional[PathLike]) – Path on remote machine for calculation files

  • training_kwargs (dict) – Explicit hyperparameter overrides (highest precedence).

  • stub (bool) – If True, creates mock model outputs without training

  • loop_time (float) – Interval (seconds) to poll for job completion

  • config_file (Optional[PathLike]) – Optional path to a YAML file of hyperparameters, layered on the built-in defaults (mirrors MaceModelTrainer’s config_file). Overridden by anything in training_kwargs.

  • collect_only (bool) – If True, update reconstructs the task submitted by an earlier, collect_only=False call (from the manifest written beside <calcdir>/training/results) instead of allocating/submitting a new one, and get_trained_model skips the (already-done) submission. trainer_input is not read in this mode. Use this to collect a detached NeuralIL training run from a fresh process.

  • reattach_max_wait (Optional[float]) – Only used when collect_only: how long (in seconds) to wait for the reattached job to finish before giving up. None (default) waits forever.

default_training_kwargs: dict = {'core_widths': [128, 64, 32], 'embed_d': 1, 'energy_weight': 0.5, 'high_energy_penalty': None, 'high_energy_penalty_relative': 5.0, 'learning_rate_kwargs': {'fin_learning_rate': 1e-05, 'max_learning_rate': 0.01, 'min_learning_rate': 0.001}, 'log_cosh_parameter_energy': 0.2, 'log_cosh_parameter_forces': 2.0, 'morse': False, 'n_batch': 32, 'n_ensemble': 30, 'n_epochs': 100, 'n_eval_batch': 64, 'n_max': 6, 'optimizer_type': 'VeLO', 'r_cut': 4.0, 'save_reduced': 5, 'seed': None, 'stub': False, 'supercell_diag': [3, 3, 3], 'training_fraction': 0.75}
__init__(remote_fs, cluster_config, training_script=None, remote_savepath=None, training_kwargs=None, stub=False, loop_time=30, config_file=None, collect_only=False, reattach_max_wait=None)[source]
unknown_schedule_keys(kwargs)[source]

Schedule keys may be attributes (config_file, training_kwargs, …) or single hyperparameters (n_epochs).

Return type:

list[str]

apply_schedule(kwargs)[source]

Apply scheduled attributes and hyperparameters.

config_file, training_kwargs and stub re-layer the merged hyperparameters (a scheduled training_kwargs replaces the explicit overrides); single hyperparameter keys then go on top.

Return type:

None

update(calcdir, trainer_input, **kwargs)[source]

Prepare trainer for a new iteration.

Parameters:
  • calcdir (PathLike) – Directory for this AL iteration

  • trainer_input (Union[Path, list[PathLike], None]) – Path(s) to database files with training data. Not read when collect_only – see MaceModelTrainer.

  • **kwargs – Additional parameters

Return type:

None

get_trained_model()[source]

Run training and return model file path.

Return type:

PathLike

Returns:

Path to trained model file

Raises:

TaskError – If training doesn’t complete successfully (or, when collect_only, if that doesn’t happen within reattach_max_wait).

class remote_handler.workflows.StagedActiveLearningHandler(stages, calchome, num_iterations=5, entry_stage=None, exit_stage=None, on_stage_complete=None)[source]

Bases: object

Generic, stage-list active learning loop with crash resume.

See the module docstring for the data-flow and resume model.

Parameters:
  • stages (list[Stage]) – Ordered pipeline of Stage objects (length >= 1).

  • calchome (PathLike) – Working directory for the loop.

  • num_iterations (int) – Number of iterations to run.

  • entry_stage (Optional[str]) – Name of the stage where iteration 0 starts (defaults to the first stage). Stages before it are skipped on the first iteration only.

  • exit_stage (Optional[str]) – Name of the stage where the final iteration stops (defaults to the last stage). Stages after it are skipped on the last iteration only.

  • on_stage_complete (Optional[list[Callable[[StageCompleted], None]]]) – Optional hooks, each called with a StageCompleted after every stage step whose outputs were recorded (see the module docstring’s Hooks).

Use from_actors() for a drop-in mapping of the original ActiveLearningHandler arguments.

__init__(stages, calchome, num_iterations=5, entry_stage=None, exit_stage=None, on_stage_complete=None)[source]
run()[source]

Run all plan items not already recorded as complete.

Return type:

None

classmethod from_actors(sampler, evaluator, trainer, *, calchome, selector=None, selector_reference_from=None, initial_selector_reference=None, num_iterations=5, cycle_entry_point='sampler', cycle_exit_point='sampler', initial_trainer_out=None, initial_sampler_out=None, initial_evaluator_out=None, sampler_schedule=None, evaluator_schedule=None, trainer_schedule=None, selector_schedule=None, combine_sampler_outputs=False, combine_evaluator_outputs=True, combine_trainer_outputs=False, sampler_output_extension='extxyz', evaluator_output_extension='extxyz', trainer_output_extension='pkl', selector_output_extension='extxyz', on_stage_complete=None)[source]

Build a handler from the classic three-actor arguments.

Mirrors ActiveLearningHandler’s parameters so existing scripts can switch with minimal changes, and optionally inserts a selector stage between the sampler and the evaluator.

cycle_entry_point / cycle_exit_point accept the legacy spellings "sampler", "evaluation" and "training".

For novelty-based selection, set selector_reference_from to a stage name (typically "evaluator"): the selector then receives that stage’s accumulated outputs from all previous iterations as a reference and switches to novelty mode (see QUESTSSelector). initial_selector_reference optionally seeds the reference (e.g. the starting training set) so novelty is active from the first iteration; otherwise iteration 0 falls back to diversity.

on_stage_complete is forwarded to the handler unchanged.

Return type:

StagedActiveLearningHandler

class remote_handler.workflows.Stage(name, actor, combine=False, schedule=None, output_extension='extxyz', initial_input=None, extra_inputs=dict())[source]

Bases: object

A single actor in the active learning pipeline.

Parameters:
  • name (str) – Unique stage name; also used for output dirs and progress keys.

  • actor (object) – The actor object (update + an output getter).

  • combine (bool) – If true, this stage’s consumer receives the stage’s outputs from all completed iterations (plus the consumer’s seed) instead of only the latest.

  • schedule (Optional[Schedule]) – Optional per-iteration kwargs source for the actor. Before each update its values are applied to the actor (set as attributes, or via the actor’s apply_schedule hook) and also passed to update as keyword arguments. Keys that name no actor attribute (and that the actor does not declare via unknown_schedule_keys) only reach update and raise a ScheduleKeyWarning at construction.

  • output_extension (str) – Extension for the stage’s collected output files.

  • initial_input (Union[Path, list[Path], None]) – Seed data fed into this stage before its producer has run. Required for the entry stage of a fresh run.

  • extra_inputs (dict[str, InputSource]) – Optional named secondary input streams (see InputSource). Each is resolved to a list of paths and passed to update as a keyword argument of the same name. Keys must not collide with the stage’s schedule kwargs.

name: str
actor: object
combine: bool = False
schedule: Optional[Schedule] = None
output_extension: str = 'extxyz'
initial_input: Union[Path, list[Path], None] = None
extra_inputs: dict[str, InputSource]
__init__(name, actor, combine=False, schedule=None, output_extension='extxyz', initial_input=None, extra_inputs=<factory>)
class remote_handler.workflows.InputSource(stage, accumulate=True, include_current=False, initial=None)[source]

Bases: object

A secondary input stream pulled from another stage’s outputs.

The primary input of a stage always follows the ring (its predecessor’s output). An InputSource declares an additional, named stream sourced from an arbitrary stage – e.g. the accumulated evaluator outputs handed to a selector as a reference for novelty scoring. The resolved paths are passed to the actor’s update as a keyword argument named after the dict key in Stage.extra_inputs.

Parameters:
  • stage (str) – Name of the producer stage to pull outputs from.

  • accumulate (bool) – If true, gather that stage’s outputs from all eligible iterations; otherwise only the most recent one.

  • include_current (bool) – If true, also consider the producer’s output from the current iteration. Defaults to false, so a stage pulls only from previous iterations (the producer typically runs later in the ring and has no current-iteration output yet).

  • initial (Union[Path, list[Path], None]) – Optional seed data used before the producer has run (e.g. an initial training set as the cold-start reference).

stage: str
accumulate: bool = True
include_current: bool = False
initial: Union[Path, list[Path], None] = None
__init__(stage, accumulate=True, include_current=False, initial=None)
class remote_handler.workflows.Selector[source]

Bases: ABC

A first-class configuration selector actor.

Peer to Sampler, GroundTruthEvaluator and ModelTrainer: it picks which of a pool of candidate configurations are passed forward to the ground-truth evaluation step, as its own element of the active learning loop rather than a sub-step of sampling. The legacy ActiveLearningHandler does not use this actor; it is consumed by the stage-based StagedActiveLearningHandler.

For the common case of a pure, host-side selection strategy, wrap a ConfigSelector (see selectors.py) in SelectorActor instead of implementing this ABC directly. Implement Selector when selection needs its own execution (e.g. running a heavy descriptor computation as a remote job).

abstractmethod update(calcdir, selector_input, **kwargs)[source]

Run the selection logic for the current iteration.

Parameters:
  • calcdir (Path) – The directory in calchome (see ActiveLearningHandler) of the current iteration. This is passed here such that the Selector can eventually write into it.

  • selector_input (Path | list[Path]) – Path or list of Paths to files holding the pool of candidate configurations to choose from. For example one or more .extxyz files produced by the Sampler.

  • **kwargs – Optional parameters returned from a schedule to modify the selection logic (see also Schedule), e.g. the number of configurations to select per iteration.

Return type:

None

abstractmethod get_selected_configs()[source]

Function returns the path(s) to the selected configurations for the upcoming GroundTruthEvaluator step.

Return type:

Path | list[Path]

pending_manifest(calcdir)

Default pending_manifest implementation: reattach unsupported.

Path to a manifest from a previous, interrupted attempt at this iteration – if this actor can detect one – None otherwise.

Used by ActiveLearningHandler/StagedActiveLearningHandler to reattach to an already-submitted job after the driving process (not necessarily the job itself) dies – a dropped SSH session, a killed local process, a closed laptop – instead of blindly resubmitting a duplicate while the original may still be running (or already finished) on the cluster. An actor built on remote_handler.core.tasks.DetachableTaskMixin typically overrides this with something like self.manifest_path(calcdir / "train" / "results"), matching its own update()’s results_dir convention – see _MaceArrayTrainer for the pattern.

This default (unsupported, always None) keeps the hook fully backward compatible: any existing actor – including every concrete Sampler, which lives outside this package in downstream repos – automatically inherits it and is simply never reattached to, exactly today’s behaviour. It is intentionally not @abstractmethod.

Return type:

Optional[Path]

class remote_handler.workflows.SelectorActor(selector, output_filename='selected.extxyz')[source]

Bases: Selector

Adapt a ConfigSelector strategy into a Selector actor.

Turns the pure select(configs) -> list[Atoms] interface into the update/get_selected_configs actor contract so a selector can sit between the sampler and the evaluator as a first-class stage. Each input file is treated as one group (e.g. one trajectory), so grouping-aware selectors such as LastFrameSelector keep working; flat selectors flatten automatically.

Parameters:
  • selector (ConfigSelector) – The selection strategy to apply.

  • output_filename (str) – Name of the written extxyz file inside the stage’s calcdir.

__init__(selector, output_filename='selected.extxyz')[source]
unknown_schedule_keys(kwargs)[source]

Schedule keys may name attributes of the wrapped selector (e.g. n_configs) or of this actor.

Return type:

list[str]

apply_schedule(kwargs)[source]

Set scheduled values on the wrapped selector, falling back to this actor for keys the selector does not have.

Return type:

None

update(calcdir, actor_input, reference=None, **kwargs)[source]

Run the selection logic for the current iteration.

Parameters:
  • calcdir (Path) – The directory in calchome (see ActiveLearningHandler) of the current iteration. This is passed here such that the Selector can eventually write into it.

  • selector_input – Path or list of Paths to files holding the pool of candidate configurations to choose from. For example one or more .extxyz files produced by the Sampler.

  • **kwargs – Optional parameters returned from a schedule to modify the selection logic (see also Schedule), e.g. the number of configurations to select per iteration.

Return type:

None

get_selected_configs()[source]

Function returns the path(s) to the selected configurations for the upcoming GroundTruthEvaluator step.

Return type:

Path

class remote_handler.workflows.RemoteSelector(selector_type, selector_kwargs, cluster_config, remote_fs, output_filename='selected.extxyz', remote_savepath=None, loop_time=30.0, stub=False, jobname='select_configs')[source]

Bases: Selector

Run a ConfigSelector strategy as a single remote SLURM job.

Peer to SelectorActor, which runs the same ConfigSelector.select() call in-process on whatever host drives the loop. Use RemoteSelector instead when selection is heavy enough (or needs a package only available in a cluster env) to warrant its own job – it ships the candidate pool (+ optional reference) and the selector’s parameters to cluster_config, runs scripts/selection/select_configs.py there via a SingleScriptTask, and collects the written extxyz back. Mirrors the pattern used by samplers.CMAESSampler for a one-shot remote job.

Parameters:
  • selector_type (str) – Name of a ConfigSelector subclass in remote_handler.workflows.selectors (e.g. “QUESTSSelector”).

  • selector_kwargs (dict) – Keyword arguments forwarded to the selector’s constructor (must be JSON-plain values).

  • cluster_config (ClusterConfig) – Cluster to submit the selection job to.

  • remote_fs (FileSystemHandlerBase) – Filesystem handler used to ship files to/from that cluster (a LocalFileSystem when the driving process already runs on the cluster’s login node, as with VASPEvaluator).

  • output_filename (str) – Name of the extxyz file the remote script writes.

  • remote_savepath (Optional[PathLike]) – Remote scratch root for the job (defaults to the executor’s own default when None).

  • loop_time (float) – Seconds between job-completion polls.

  • stub (bool) – When True, run the selector in-process instead of submitting a job (for dry-running the loop’s wiring without a cluster).

  • jobname (str) – SLURM job name.

__init__(selector_type, selector_kwargs, cluster_config, remote_fs, output_filename='selected.extxyz', remote_savepath=None, loop_time=30.0, stub=False, jobname='select_configs')[source]
unknown_schedule_keys(kwargs)[source]

Schedule keys are selector constructor arguments: update merges them over selector_kwargs each iteration.

Return type:

list[str]

apply_schedule(kwargs)[source]

No-op: the scheduled values reach the selector through update’s keyword arguments, not through attributes.

Return type:

None

update(calcdir, actor_input, reference=None, **kwargs)[source]

Run the selection logic for the current iteration.

Parameters:
  • calcdir (Path) – The directory in calchome (see ActiveLearningHandler) of the current iteration. This is passed here such that the Selector can eventually write into it.

  • selector_input – Path or list of Paths to files holding the pool of candidate configurations to choose from. For example one or more .extxyz files produced by the Sampler.

  • **kwargs – Optional parameters returned from a schedule to modify the selection logic (see also Schedule), e.g. the number of configurations to select per iteration.

Return type:

None

get_selected_configs()[source]

Function returns the path(s) to the selected configurations for the upcoming GroundTruthEvaluator step.

Return type:

Path

class remote_handler.workflows.active_learning_base.Sampler[source]

Bases: ABC

abstractmethod update(calcdir, sampler_input, **kwargs)[source]

Function updating the sampling logic for the current iteration. This in general can include file/directory creation or movement, as well as changes to the logic of the sampling itself, like e.g. parameters for a nested sampling run.

Parameters:
  • calcdir (Path) – The directory in calchome (see ActiveLearningHandler) of the current iteration. This is passed here such that the Sampler can eventually write into it.

  • sampler_input (Path | list[Path]) – Path or list of paths to files needed to run Sampler. For example this could contain one or more paths to MLFF model-files for the Sampler to run MD and/or perform ensemble evaluations with.

  • **kwargs – Optional parameters returned from a schedule to modify the sampling logic (see also Schedule)

Return type:

None

abstractmethod get_sampled_configs()[source]

Function returns a JsonDict object containing necessary information for upcoming GroundTruthEvaluator step.

Return type:

Path | list[Path]

pending_manifest(calcdir)

Default pending_manifest implementation: reattach unsupported.

Path to a manifest from a previous, interrupted attempt at this iteration – if this actor can detect one – None otherwise.

Used by ActiveLearningHandler/StagedActiveLearningHandler to reattach to an already-submitted job after the driving process (not necessarily the job itself) dies – a dropped SSH session, a killed local process, a closed laptop – instead of blindly resubmitting a duplicate while the original may still be running (or already finished) on the cluster. An actor built on remote_handler.core.tasks.DetachableTaskMixin typically overrides this with something like self.manifest_path(calcdir / "train" / "results"), matching its own update()’s results_dir convention – see _MaceArrayTrainer for the pattern.

This default (unsupported, always None) keeps the hook fully backward compatible: any existing actor – including every concrete Sampler, which lives outside this package in downstream repos – automatically inherits it and is simply never reattached to, exactly today’s behaviour. It is intentionally not @abstractmethod.

Return type:

Optional[Path]

class remote_handler.workflows.active_learning_base.GroundTruthEvaluator[source]

Bases: ABC

abstractmethod update(calcdir, evaluator_input, **kwargs)[source]

Function updating the ground truth evaluation logic for the current iteration. This in general can include file/directory creation or movement, as well as changes to the logic of the groun truth evaluation itself, like e.g. parameters for DFT.

Parameters:
  • calcdir (Path) – The directory in calchome (see ActiveLearningHandler) of the current iteration. This is passed here such that the GroundTruthEvaluator can eventually write into it.

  • evaluator_input (Path | list[Path]) – Path or list of Paths to files needed for running GroundTruthEvaluator. For example this could point to one or more .extxyz files with unlabelled configurations for the GroundTruthEvaluator to run DFT on.

  • **kwargs – Optional parameters returned from a schedule to modify the labelling logic (see also Schedule)

Return type:

None

abstractmethod get_evaluated_configs()[source]

Function returns a JsonDict object containing necessary information for upcoming ModelTrainer step.

Return type:

Path | list[Path]

pending_manifest(calcdir)

Default pending_manifest implementation: reattach unsupported.

Path to a manifest from a previous, interrupted attempt at this iteration – if this actor can detect one – None otherwise.

Used by ActiveLearningHandler/StagedActiveLearningHandler to reattach to an already-submitted job after the driving process (not necessarily the job itself) dies – a dropped SSH session, a killed local process, a closed laptop – instead of blindly resubmitting a duplicate while the original may still be running (or already finished) on the cluster. An actor built on remote_handler.core.tasks.DetachableTaskMixin typically overrides this with something like self.manifest_path(calcdir / "train" / "results"), matching its own update()’s results_dir convention – see _MaceArrayTrainer for the pattern.

This default (unsupported, always None) keeps the hook fully backward compatible: any existing actor – including every concrete Sampler, which lives outside this package in downstream repos – automatically inherits it and is simply never reattached to, exactly today’s behaviour. It is intentionally not @abstractmethod.

Return type:

Optional[Path]

class remote_handler.workflows.active_learning_base.ModelTrainer[source]

Bases: ABC

abstractmethod update(calcdir, trainer_input, **kwargs)[source]

Function updating the training logic for the current iteration.

Parameters:
  • calcdir (Path) – The directory in calchome (see ActiveLearningHandler) of the current iteration. This is passed here such that the ModelTrainer can eventually write into it.

  • trainer_input (Path | list[Path]) – Path or list of Paths to files needed for running ModelTrainer. For example this could point to one or more .extxyz files with DFT-evaluated configurations to use for the next training iteration.

  • **kwargs – Optional parameters returned from a schedule to modify the labelling logic (see also Schedule)

Return type:

None

abstractmethod get_trained_model()[source]

Function returns a JsonDict object containing necessary information for upcoming Sampler step

Return type:

Path | list[Path]

pending_manifest(calcdir)

Default pending_manifest implementation: reattach unsupported.

Path to a manifest from a previous, interrupted attempt at this iteration – if this actor can detect one – None otherwise.

Used by ActiveLearningHandler/StagedActiveLearningHandler to reattach to an already-submitted job after the driving process (not necessarily the job itself) dies – a dropped SSH session, a killed local process, a closed laptop – instead of blindly resubmitting a duplicate while the original may still be running (or already finished) on the cluster. An actor built on remote_handler.core.tasks.DetachableTaskMixin typically overrides this with something like self.manifest_path(calcdir / "train" / "results"), matching its own update()’s results_dir convention – see _MaceArrayTrainer for the pattern.

This default (unsupported, always None) keeps the hook fully backward compatible: any existing actor – including every concrete Sampler, which lives outside this package in downstream repos – automatically inherits it and is simply never reattached to, exactly today’s behaviour. It is intentionally not @abstractmethod.

Return type:

Optional[Path]

class remote_handler.workflows.active_learning_base.Selector[source]

Bases: ABC

A first-class configuration selector actor.

Peer to Sampler, GroundTruthEvaluator and ModelTrainer: it picks which of a pool of candidate configurations are passed forward to the ground-truth evaluation step, as its own element of the active learning loop rather than a sub-step of sampling. The legacy ActiveLearningHandler does not use this actor; it is consumed by the stage-based StagedActiveLearningHandler.

For the common case of a pure, host-side selection strategy, wrap a ConfigSelector (see selectors.py) in SelectorActor instead of implementing this ABC directly. Implement Selector when selection needs its own execution (e.g. running a heavy descriptor computation as a remote job).

abstractmethod update(calcdir, selector_input, **kwargs)[source]

Run the selection logic for the current iteration.

Parameters:
  • calcdir (Path) – The directory in calchome (see ActiveLearningHandler) of the current iteration. This is passed here such that the Selector can eventually write into it.

  • selector_input (Path | list[Path]) – Path or list of Paths to files holding the pool of candidate configurations to choose from. For example one or more .extxyz files produced by the Sampler.

  • **kwargs – Optional parameters returned from a schedule to modify the selection logic (see also Schedule), e.g. the number of configurations to select per iteration.

Return type:

None

abstractmethod get_selected_configs()[source]

Function returns the path(s) to the selected configurations for the upcoming GroundTruthEvaluator step.

Return type:

Path | list[Path]

pending_manifest(calcdir)

Default pending_manifest implementation: reattach unsupported.

Path to a manifest from a previous, interrupted attempt at this iteration – if this actor can detect one – None otherwise.

Used by ActiveLearningHandler/StagedActiveLearningHandler to reattach to an already-submitted job after the driving process (not necessarily the job itself) dies – a dropped SSH session, a killed local process, a closed laptop – instead of blindly resubmitting a duplicate while the original may still be running (or already finished) on the cluster. An actor built on remote_handler.core.tasks.DetachableTaskMixin typically overrides this with something like self.manifest_path(calcdir / "train" / "results"), matching its own update()’s results_dir convention – see _MaceArrayTrainer for the pattern.

This default (unsupported, always None) keeps the hook fully backward compatible: any existing actor – including every concrete Sampler, which lives outside this package in downstream repos – automatically inherits it and is simply never reattached to, exactly today’s behaviour. It is intentionally not @abstractmethod.

Return type:

Optional[Path]

remote_handler.workflows.active_learning_base.append_or_extend(item, append_list)[source]

Appends item to append_list if item is not a list. If item is a list, appends each individual entry of item to append_list instead.

remote_handler.workflows.active_learning_base.process_progress(progress, num_iterations, combine_sampler_outputs, combine_evaluator_outputs, combine_trainer_outputs)[source]

Parses the contents of a dumped AL_progress.json file and returns the quantities necessary for resuming a active learning loop with ActiveLearningHandler.

Return type:

tuple[int, list[Path], list[Path], list[Path], list[dict]]

class remote_handler.workflows.active_learning_base.Schedule(num_iterations)[source]

Bases: ABC

Utility class to parametrize schedules for active learning cycles. We enforce that the schedule needs to provide the same parameters for each iteration (their values can change of course). This makes it much easier to check and avoids potential failures.

Parameters:

num_iterations (int) – Number of iterations that should be run with this schedule.

__init__(num_iterations)[source]
visualize(column_width=20)[source]

Visualizes the parameter that change during the defined schedule. It is recommended to check this before actually starting an active learning run to see whether you actually implemented what you wanted.

Parameters:

column_width (int) – Width of the column in which parameter is printed to stdout.

Return type:

None

Example

For a schedule modifying the parameters ‘n_walkers’, ‘gpu_n_batch’ and ‘MC_cell_P’ of a nested sampling run, the output of this would look like the following:

n_walkers gpu_n_batch MC_cell_P 200 200 3 7 11 15 300 400 2 4 6 8 10 12 14 16 400 600 2 4 6 8 10 12 14 16

check()[source]

Checks whether at each iteration the returned parameters are the same.

Return type:

None

test(kwargs_consumer)[source]

Eventually, Schedule will be used in ActiveLearningBase to feed some additional kwargs usually into a Sampler.update. This function can be used to test your schedule before actually running the active learning loop. You need to pass a kwargs_consumer, which is a function that can check the kwargs you pass for validity. While potentially being a small additional effort to implement such a kwargs_consumer it can easily prevent your active loop from crashing during the loop.

Example

If the Sampler instance handles a nested sampling simulation, at each iteration a dictionary is updated by Sampler.update and parsed by the nested sampling code. This parser checks the parameters for validity and can be casted into a kwargs_consumer.

Return type:

None

abstractmethod get_kwargs(iteration_idx)[source]

Here you have to encode the logic of your schedule.

Example

For a nested sampling active learning workflow, a simple schedule could look like the following:

def get_kwargs(self, iteration_idx: int):
if iteration_idx == 0:
kwargs = {

“n_walkers”: 400, “gpu_n_batch”: 200, “MC_cell_P”: “3 7 11 15”,

}

if iteration_idx > 0:
kwargs = {

“n_walkers”: 400, “gpu_n_batch”: 400, “MC_cell_P”: “2 4 6 8 10 12 14 16”,

}

return kwargs

Return type:

dict

remote_handler.workflows.active_learning_base.validate_schedule_kwargs(actor, kwargs)[source]

Warn about schedule keys that name nothing actor can take.

By default a key is known if it names an existing attribute of actor – that is what apply_schedule_kwargs() sets. An actor whose scheduled values live elsewhere (e.g. in a wrapped strategy object) defines unknown_schedule_keys(kwargs) -> list[str] instead.

Unknown keys are not an error: they still reach update as keyword arguments, which is right for an actor that reads them there. But they are also how a misspelt key shows up, so each triggers a ScheduleKeyWarning (make it an error with warnings.simplefilter("error", ScheduleKeyWarning)). The handlers call this once, at construction.

Return type:

None

remote_handler.workflows.active_learning_base.set_schedule_attributes(actor, kwargs)[source]

Set each schedule value whose key names an existing attribute of actor; leave the other keys to update’s keyword arguments.

Return type:

None

remote_handler.workflows.active_learning_base.apply_schedule_kwargs(actor, kwargs)[source]

Apply one iteration’s schedule values to actor before update.

Defaults to set_schedule_attributes(). An actor that derives state from a scheduled parameter once (so a plain setattr would not reach the job) defines an apply_schedule(kwargs) method, which is called instead.

The handlers still forward the same values to update as keyword arguments, so actors that consume them there keep working.

Return type:

None

class remote_handler.workflows.active_learning_base.ActiveLearningHandler(sampler, evaluator, trainer, calchome, num_iterations=5, cycle_entry_point='sampler', cycle_exit_point='sampler', initial_trainer_out=None, initial_sampler_out=None, initial_evaluator_out=None, sampler_schedule=None, evaluator_schedule=None, trainer_schedule=None, combine_sampler_outputs=False, combine_evaluator_outputs=True, combine_trainer_outputs=False, sampler_output_extension='extxyz', evaluator_output_extension='extxyz', trainer_output_extension='pkl')[source]

Bases: ABC

Implementation of the core functionality of an active learning loop consisting of three actors: A sampler, a ground truth evaluator and a model trainer. ActiveLearningHandler handles the bookkeeping of created files and passes required files to the corresponding actors. It offers functionality to resume broken runs by caching the current progress and at which point to enter/exit the cycle.

Deprecated since version Use: StagedActiveLearningHandler (remote_handler.workflows.staged_active_learning) instead. It supports the same three-actor shape via StagedActiveLearningHandler.from_actors(...), adds a first-class Selector stage, and generalizes to an arbitrary stage list. ActiveLearningHandler will be removed in a future release; instantiating it now raises a DeprecationWarning.

Parameters:
  • sampler (Sampler) – A Sampler instance for sampling new configurations.

  • evaluator (GroundTruthEvaluator) – A GroundTruthEvaluator instance for running DFT.

  • trainer (ModelTrainer) – A ModelTrainer instance for retraining your MLFF model.

  • calchome (PathLike) – The working directory for the active learning loop.

  • num_iterations (int) – Number of active learning iterations to perform.

  • cycle_entry_point (Literal['sampler', 'evaluation', 'training']) – Defines the actor where your loop starts. Can either be ‘sampler’, ‘evaluation’ or ‘training’

  • cycle_exit_point (Literal['sampler', 'evaluation', 'training']) – Defines the actor where your loop ends. Can either be ‘sampler’, ‘evaluation’ or ‘training’

  • initial_trainer_out (Union[Path, list[Path], None]) – Any input similar to the outputs of the used ModelTrainer which should be used by the Sampler. May for example be the path(s) to one or several model files that should be used in the sampling step. Required when starting from scratch with cycle_entry_point=’sampler’, however will also be used if combine_trainer_outputs=True.

  • initial_sampler_out (Union[Path, list[Path], None]) – Any input similar to the outputs of the used Sampler which should be used by the GroundTruthEvaluator. May for example be the path(s) to one or several .extxyz files that should be evaluated in the evaluation step. Required when starting from scratch with cycle_entry_point=’evaluation’, however will also be used if combine_sampler_outputs=True.

  • initial_evaluator_out (Union[Path, list[Path], None]) – Any input similar to the outputs of the used GroundTruthEvaluator which should be used by the ModelTrainer. May for example be the path(s) to one or several .extxyz files that should be used in the training step. Required when starting from scratch with cycle_entry_point=’training’, however will also be used if combine_evaluator_outputs=True.

  • sampler_schedule (Optional[Schedule]) – A Schedule instance encoding a schedule for the sampler

  • evaluator_schedule (Optional[Schedule]) – A Schedule instance encoding a schedule for the evaluator

  • trainer_schedule (Optional[Schedule]) – A Schedule instance encoding a schedule for the trainer

  • combine_sampler_outputs (bool) – If true, the outputs of all previous sampling steps (as well as initial_sampler_out) will be passed to the evaluator. Otherwise only the outputs of the most recent sampling step (or initial_sampler_out if starting from scratch at the evaluation step) will be passed.

  • combine_evaluator_outputs (bool) – If true, the outputs of all previous evaluation steps (as well as initial_evaluator_out) will be passed to the trainer. Otherwise only the outputs of the most recent evaluation step (or initial_evaluator_out if starting from scratch at the training step) will be passed.

  • combine_trainer_outputs (bool) – If true, the outputs of all previous training steps (as well as initial_trainer_out) will be passed to the sampler. Otherwise only the outputs of the most recent training step (or initial_trainer_out if starting from scratch at the training step) will be passed.

  • sampler_output_extension (str) – File extension for the Sampler’s output files.

  • evaluator_output_extension (str) – File extension for the GroundTruthEvaluator’s output files.

  • trainer_output_extension (str) – File extension for the ModelTrainer’s output files.

Examples

In general ActiveLearningHandler will create a folder structure like the following:

calchome ├── 0 │ ├── sampler │ ├── dft │ └── training ├── 1 │ ├── sampler │ ├── dft │ └── training ├── … ├── evaluated_configs │ ├── evaluated_0.extxyz │ ├── evaluated_1.extxyz │ ├── … ├── sampled_configs │ ├── sampled_0.extxyz │ ├── sampled_1.extxyz │ ├── … ├── trained_models │ ├── model_0.pkl │ ├── model_1.pkl │ ├── … ├── AL_progress.json └── al_loop.py

Here, AL_progress.json contains the bookkeeping. During each iteration, it updates a dictionary that contains information on the progress of the loop. Once a full loop is finished, it could look like this:

{

‘steps’: [0, 0, 0], ‘sampler_output’: [PATH_TO_SAMPLES], ‘evaluator_output’: [PATH_TO_DB], ‘trainer_output’: [PATH_TO_MODEL1, PATH_TO_MODEL2, …]

}

where ‘steps’ indicate which actor still needs to be run (hence its 0 if it was already successfully run). Hence, if e.g. only the sampler finished successfully so far, the entry for the current iteration in AL_progress.json would look like this:

{

‘steps’: [0, 1, 1], ‘sampler_output’: [PATH_TO_SAMPLES],

}

This logic allows the ActiveLearningHandler to easily resume runs that crashed during some part of the loop.

__init__(sampler, evaluator, trainer, calchome, num_iterations=5, cycle_entry_point='sampler', cycle_exit_point='sampler', initial_trainer_out=None, initial_sampler_out=None, initial_evaluator_out=None, sampler_schedule=None, evaluator_schedule=None, trainer_schedule=None, combine_sampler_outputs=False, combine_evaluator_outputs=True, combine_trainer_outputs=False, sampler_output_extension='extxyz', evaluator_output_extension='extxyz', trainer_output_extension='pkl')[source]
move_file_to_home(file)[source]

Moves a file from an external path into the AL home directory

Parameters:

file (Path) – path of file which should be moved to AL home

Returns:

Path to moved file

update_progress_file()[source]

Updates the AL_progress.json file.

Return type:

None

sample(**kwargs)[source]

Runs the Sampler, requiring self.sampler_in and updating self.evaluator_in

Parameters:

**kwargs – kwargs passed to the update function of sampler.

Return type:

None

evaluate(**kwargs)[source]

Runs the GroundTruthEvaluator, requiring self.evaluator_in and updating self.trainer_in

Parameters:

**kwargs – kwargs passed to the update function of evaluator.

Return type:

None

retrain(**kwargs)[source]

Runs the ModelTrainer, requiring self.trainer_in and updating self.sampler_in

Parameters:

**kwargs – kwargs passed to the update function of trainer.

Return type:

None

single_iteration()[source]

Runs a single active learning iteration. For each iteration it creates a new calcdir in calchome. If provided, schedules are applied to the individual actors.

Return type:

None

run()[source]

Runs the active learning cycle. In case a crashed run is restarted, it only runs the remaining iterations until num_iterations is reached.

Return type:

None

Stage-based active learning handler (alternative implementation).

This is an alternative to ActiveLearningHandler in active_learning_base.py. The original handler hardcodes the three-actor (sampler / evaluator / trainer) loop: its bookkeeping is a fixed [sample, eval, train] done-flag triple and every actor’s config is tripled by hand in __init__. Adding a fourth actor (e.g. a configuration selector between sampling and evaluation) means widening that triple and extending the hand-enumerated resume logic.

This module models the loop instead as an ordered list of uniform Stage objects, each wrapping an actor that satisfies the ALActor contract (update(calcdir, actor_input, **kwargs) plus an output getter). The loop, the file bookkeeping and the crash-resume logic are all generic over the stage list, so adding the selector is just inserting one Stage – no changes to the orchestration code.

The original ActiveLearningHandler is left completely untouched; both implementations coexist.

Data flow

The stages form a ring: stage N consumes the output of stage N-1 in the same iteration, and the first stage consumes the last stage’s output from the previous iteration. A stage’s combine flag is a producer-side setting: when true, that stage’s consumer receives the stage’s outputs from all completed iterations (plus the consumer’s seed), rather than only the most recent one. This mirrors the combine_*_outputs semantics of the original handler.

Each stage may carry an initial_input seed – the data fed into it before its producer has run (e.g. the initial model handed to the sampler on iteration 0). The entry stage of a fresh run must have a seed.

Beyond the ring, a stage may declare extra_inputs – named secondary streams pulled from any other stage’s outputs (see InputSource), optionally accumulated across iterations. This turns the ring into a small DAG and is what enables, for example, novelty selection: a selector receives the evaluator’s accumulated outputs from all previous iterations as a reference and scores candidates by how novel they are relative to the already-labelled data.

Resume

Progress is tracked as a cursor, not an enumerated flag combination: the handler precomputes a deterministic plan of (iteration, stage) work items from num_iterations and the entry/exit stages, then records each completed item’s outputs in AL_progress.json. Resuming re-runs only the plan items not yet recorded. entry_stage/exit_stage are fixed at the first run and persisted; num_iterations may be increased on a later run to extend the loop.

Hooks

on_stage_complete callables are side channels outside the data flow (e.g. submitting a dashboard render): each is called with a StageCompleted event once a stage’s outputs are recorded. They produce nothing the loop consumes, are not recorded in the progress file (so a resume does not re-fire them for steps already done), and an exception in one is logged and swallowed – a hook never stops the loop.

remote_handler.workflows.staged_active_learning.resolve_actor_output(actor)[source]

Return an actor’s output by trying the known getter names.

Parameters:

actor (object) – Any stage actor.

Return type:

Path | list[Path]

Returns:

The path(s) produced by the actor.

Raises:

WorkflowError – If the actor exposes none of the known getters.

class remote_handler.workflows.staged_active_learning.SelectorActor(selector, output_filename='selected.extxyz')[source]

Bases: Selector

Adapt a ConfigSelector strategy into a Selector actor.

Turns the pure select(configs) -> list[Atoms] interface into the update/get_selected_configs actor contract so a selector can sit between the sampler and the evaluator as a first-class stage. Each input file is treated as one group (e.g. one trajectory), so grouping-aware selectors such as LastFrameSelector keep working; flat selectors flatten automatically.

Parameters:
  • selector (ConfigSelector) – The selection strategy to apply.

  • output_filename (str) – Name of the written extxyz file inside the stage’s calcdir.

__init__(selector, output_filename='selected.extxyz')[source]
unknown_schedule_keys(kwargs)[source]

Schedule keys may name attributes of the wrapped selector (e.g. n_configs) or of this actor.

Return type:

list[str]

apply_schedule(kwargs)[source]

Set scheduled values on the wrapped selector, falling back to this actor for keys the selector does not have.

Return type:

None

update(calcdir, actor_input, reference=None, **kwargs)[source]

Run the selection logic for the current iteration.

Parameters:
  • calcdir (Path) – The directory in calchome (see ActiveLearningHandler) of the current iteration. This is passed here such that the Selector can eventually write into it.

  • selector_input – Path or list of Paths to files holding the pool of candidate configurations to choose from. For example one or more .extxyz files produced by the Sampler.

  • **kwargs – Optional parameters returned from a schedule to modify the selection logic (see also Schedule), e.g. the number of configurations to select per iteration.

Return type:

None

get_selected_configs()[source]

Function returns the path(s) to the selected configurations for the upcoming GroundTruthEvaluator step.

Return type:

Path

class remote_handler.workflows.staged_active_learning.RemoteSelector(selector_type, selector_kwargs, cluster_config, remote_fs, output_filename='selected.extxyz', remote_savepath=None, loop_time=30.0, stub=False, jobname='select_configs')[source]

Bases: Selector

Run a ConfigSelector strategy as a single remote SLURM job.

Peer to SelectorActor, which runs the same ConfigSelector.select() call in-process on whatever host drives the loop. Use RemoteSelector instead when selection is heavy enough (or needs a package only available in a cluster env) to warrant its own job – it ships the candidate pool (+ optional reference) and the selector’s parameters to cluster_config, runs scripts/selection/select_configs.py there via a SingleScriptTask, and collects the written extxyz back. Mirrors the pattern used by samplers.CMAESSampler for a one-shot remote job.

Parameters:
  • selector_type (str) – Name of a ConfigSelector subclass in remote_handler.workflows.selectors (e.g. “QUESTSSelector”).

  • selector_kwargs (dict) – Keyword arguments forwarded to the selector’s constructor (must be JSON-plain values).

  • cluster_config (ClusterConfig) – Cluster to submit the selection job to.

  • remote_fs (FileSystemHandlerBase) – Filesystem handler used to ship files to/from that cluster (a LocalFileSystem when the driving process already runs on the cluster’s login node, as with VASPEvaluator).

  • output_filename (str) – Name of the extxyz file the remote script writes.

  • remote_savepath (Optional[PathLike]) – Remote scratch root for the job (defaults to the executor’s own default when None).

  • loop_time (float) – Seconds between job-completion polls.

  • stub (bool) – When True, run the selector in-process instead of submitting a job (for dry-running the loop’s wiring without a cluster).

  • jobname (str) – SLURM job name.

__init__(selector_type, selector_kwargs, cluster_config, remote_fs, output_filename='selected.extxyz', remote_savepath=None, loop_time=30.0, stub=False, jobname='select_configs')[source]
unknown_schedule_keys(kwargs)[source]

Schedule keys are selector constructor arguments: update merges them over selector_kwargs each iteration.

Return type:

list[str]

apply_schedule(kwargs)[source]

No-op: the scheduled values reach the selector through update’s keyword arguments, not through attributes.

Return type:

None

update(calcdir, actor_input, reference=None, **kwargs)[source]

Run the selection logic for the current iteration.

Parameters:
  • calcdir (Path) – The directory in calchome (see ActiveLearningHandler) of the current iteration. This is passed here such that the Selector can eventually write into it.

  • selector_input – Path or list of Paths to files holding the pool of candidate configurations to choose from. For example one or more .extxyz files produced by the Sampler.

  • **kwargs – Optional parameters returned from a schedule to modify the selection logic (see also Schedule), e.g. the number of configurations to select per iteration.

Return type:

None

get_selected_configs()[source]

Function returns the path(s) to the selected configurations for the upcoming GroundTruthEvaluator step.

Return type:

Path

class remote_handler.workflows.staged_active_learning.InputSource(stage, accumulate=True, include_current=False, initial=None)[source]

Bases: object

A secondary input stream pulled from another stage’s outputs.

The primary input of a stage always follows the ring (its predecessor’s output). An InputSource declares an additional, named stream sourced from an arbitrary stage – e.g. the accumulated evaluator outputs handed to a selector as a reference for novelty scoring. The resolved paths are passed to the actor’s update as a keyword argument named after the dict key in Stage.extra_inputs.

Parameters:
  • stage (str) – Name of the producer stage to pull outputs from.

  • accumulate (bool) – If true, gather that stage’s outputs from all eligible iterations; otherwise only the most recent one.

  • include_current (bool) – If true, also consider the producer’s output from the current iteration. Defaults to false, so a stage pulls only from previous iterations (the producer typically runs later in the ring and has no current-iteration output yet).

  • initial (Union[Path, list[Path], None]) – Optional seed data used before the producer has run (e.g. an initial training set as the cold-start reference).

stage: str
accumulate: bool = True
include_current: bool = False
initial: Union[Path, list[Path], None] = None
__init__(stage, accumulate=True, include_current=False, initial=None)
class remote_handler.workflows.staged_active_learning.Stage(name, actor, combine=False, schedule=None, output_extension='extxyz', initial_input=None, extra_inputs=dict())[source]

Bases: object

A single actor in the active learning pipeline.

Parameters:
  • name (str) – Unique stage name; also used for output dirs and progress keys.

  • actor (object) – The actor object (update + an output getter).

  • combine (bool) – If true, this stage’s consumer receives the stage’s outputs from all completed iterations (plus the consumer’s seed) instead of only the latest.

  • schedule (Optional[Schedule]) – Optional per-iteration kwargs source for the actor. Before each update its values are applied to the actor (set as attributes, or via the actor’s apply_schedule hook) and also passed to update as keyword arguments. Keys that name no actor attribute (and that the actor does not declare via unknown_schedule_keys) only reach update and raise a ScheduleKeyWarning at construction.

  • output_extension (str) – Extension for the stage’s collected output files.

  • initial_input (Union[Path, list[Path], None]) – Seed data fed into this stage before its producer has run. Required for the entry stage of a fresh run.

  • extra_inputs (dict[str, InputSource]) – Optional named secondary input streams (see InputSource). Each is resolved to a list of paths and passed to update as a keyword argument of the same name. Keys must not collide with the stage’s schedule kwargs.

name: str
actor: object
combine: bool = False
schedule: Optional[Schedule] = None
output_extension: str = 'extxyz'
initial_input: Union[Path, list[Path], None] = None
extra_inputs: dict[str, InputSource]
__init__(name, actor, combine=False, schedule=None, output_extension='extxyz', initial_input=None, extra_inputs=<factory>)
class remote_handler.workflows.staged_active_learning.StageCompleted(stage, iteration, calchome, outputs, is_last)[source]

Bases: object

Event passed to on_stage_complete hooks.

stage

Name of the stage that just finished.

Type:

str

iteration

Its iteration index.

Type:

int

calchome

The loop’s working directory.

Type:

Path

outputs

The stage’s recorded outputs for this iteration, as absolute paths (the copies under <stage>_output/).

Type:

tuple[Path, ...]

is_last

True for the final step of the loop’s plan.

Type:

bool

stage: str
iteration: int
calchome: Path
outputs: tuple[Path, ...]
is_last: bool
__init__(stage, iteration, calchome, outputs, is_last)
class remote_handler.workflows.staged_active_learning.StagedActiveLearningHandler(stages, calchome, num_iterations=5, entry_stage=None, exit_stage=None, on_stage_complete=None)[source]

Bases: object

Generic, stage-list active learning loop with crash resume.

See the module docstring for the data-flow and resume model.

Parameters:
  • stages (list[Stage]) – Ordered pipeline of Stage objects (length >= 1).

  • calchome (PathLike) – Working directory for the loop.

  • num_iterations (int) – Number of iterations to run.

  • entry_stage (Optional[str]) – Name of the stage where iteration 0 starts (defaults to the first stage). Stages before it are skipped on the first iteration only.

  • exit_stage (Optional[str]) – Name of the stage where the final iteration stops (defaults to the last stage). Stages after it are skipped on the last iteration only.

  • on_stage_complete (Optional[list[Callable[[StageCompleted], None]]]) – Optional hooks, each called with a StageCompleted after every stage step whose outputs were recorded (see the module docstring’s Hooks).

Use from_actors() for a drop-in mapping of the original ActiveLearningHandler arguments.

__init__(stages, calchome, num_iterations=5, entry_stage=None, exit_stage=None, on_stage_complete=None)[source]
outputs: dict[str, dict[int, list[str]]]
seeds: dict[str, list[str]]
extra_seeds: dict[tuple[str, str], list[str]]
stage_output_dirs: dict[str, Path]
run()[source]

Run all plan items not already recorded as complete.

Return type:

None

classmethod from_actors(sampler, evaluator, trainer, *, calchome, selector=None, selector_reference_from=None, initial_selector_reference=None, num_iterations=5, cycle_entry_point='sampler', cycle_exit_point='sampler', initial_trainer_out=None, initial_sampler_out=None, initial_evaluator_out=None, sampler_schedule=None, evaluator_schedule=None, trainer_schedule=None, selector_schedule=None, combine_sampler_outputs=False, combine_evaluator_outputs=True, combine_trainer_outputs=False, sampler_output_extension='extxyz', evaluator_output_extension='extxyz', trainer_output_extension='pkl', selector_output_extension='extxyz', on_stage_complete=None)[source]

Build a handler from the classic three-actor arguments.

Mirrors ActiveLearningHandler’s parameters so existing scripts can switch with minimal changes, and optionally inserts a selector stage between the sampler and the evaluator.

cycle_entry_point / cycle_exit_point accept the legacy spellings "sampler", "evaluation" and "training".

For novelty-based selection, set selector_reference_from to a stage name (typically "evaluator"): the selector then receives that stage’s accumulated outputs from all previous iterations as a reference and switches to novelty mode (see QUESTSSelector). initial_selector_reference optionally seeds the reference (e.g. the starting training set) so novelty is active from the first iteration; otherwise iteration 0 falls back to diversity.

on_stage_complete is forwarded to the handler unchanged.

Return type:

StagedActiveLearningHandler

Selectors

Configuration selectors for active learning sampling workflows.

Selectors determine which configurations from a pool of candidates are passed forward to the ground-truth evaluation step.

The select method accepts either:
  • list[Atoms] — a flat list of configurations

  • list[list[Atoms]] — grouped configurations (e.g., one inner list per trajectory/replica)

Selectors that care about grouping (e.g., LastFrameSelector) use the nested structure. Selectors that don’t (e.g., StrideSelector) flatten it automatically.

Example

>>> from remote_handler.workflows.selectors import StrideSelector
>>> selector = StrideSelector(n_configs=20)
>>> # pass the selector to your sampler, e.g. sampler(..., selector=...)
>>> from remote_handler.workflows.selectors import QUESTSSelector
>>> selector = QUESTSSelector(n_configs=20, method="msc")
>>> # With novelty relative to existing training data:
>>> selector = QUESTSSelector(n_configs=20, reference=train_atoms)
class remote_handler.workflows.selectors.ConfigSelector[source]

Bases: ABC

Abstract base class for configuration selection strategies.

A ConfigSelector receives configurations (flat or grouped) and returns a flat list of selected Atoms.

abstractmethod select(configs, reference=None)[source]

Select configurations from a pool of candidates.

Parameters:
  • configs (Union[list[Atoms], list[list[Atoms]]]) – Pool of candidate configurations, either as a flat list[Atoms] or grouped list[list[Atoms]] (e.g., one inner list per trajectory).

  • reference (list[Atoms] | None) – Optional auxiliary set this selection scores against (e.g. the already-labelled data, for novelty). Selectors that don’t use a reference ignore it. Passed as an argument – not set via a mutator – so it composes cleanly (PipelineSelector forwards it to its members).

Return type:

list[Atoms]

Returns:

Flat list of selected configurations.

class remote_handler.workflows.selectors.LastFrameSelector[source]

Bases: ConfigSelector

Select the last frame from each group.

When given grouped input (list[list[Atoms]]), returns the last element of each inner list — e.g., the final frame from each trajectory/replica.

When given a flat list, returns it unchanged (assumes each element is already a “last frame”).

select(configs, reference=None)[source]

Select configurations from a pool of candidates.

Parameters:
  • configs (Union[list[Atoms], list[list[Atoms]]]) – Pool of candidate configurations, either as a flat list[Atoms] or grouped list[list[Atoms]] (e.g., one inner list per trajectory).

  • reference (list[Atoms] | None) – Optional auxiliary set this selection scores against (e.g. the already-labelled data, for novelty). Selectors that don’t use a reference ignore it. Passed as an argument – not set via a mutator – so it composes cleanly (PipelineSelector forwards it to its members).

Return type:

list[Atoms]

Returns:

Flat list of selected configurations.

class remote_handler.workflows.selectors.StrideSelector(n_configs)[source]

Bases: ConfigSelector

Select configurations at evenly spaced (strided) intervals.

Picks n_configs evenly spaced configurations from the (flattened) input – i.e. every stride-th frame, with the stride chosen so the selection spans the whole pool. This is deterministic, not random subsampling; useful for thinning long trajectories without bias.

Parameters:

n_configs (int) – Number of configurations to select.

__init__(n_configs)[source]
select(configs, reference=None)[source]

Select configurations from a pool of candidates.

Parameters:
  • configs (Union[list[Atoms], list[list[Atoms]]]) – Pool of candidate configurations, either as a flat list[Atoms] or grouped list[list[Atoms]] (e.g., one inner list per trajectory).

  • reference (list[Atoms] | None) – Optional auxiliary set this selection scores against (e.g. the already-labelled data, for novelty). Selectors that don’t use a reference ignore it. Passed as an argument – not set via a mutator – so it composes cleanly (PipelineSelector forwards it to its members).

Return type:

list[Atoms]

Returns:

Flat list of selected configurations.

class remote_handler.workflows.selectors.UniformSelector(n_configs)[source]

Bases: StrideSelector

Deprecated alias for StrideSelector.

The old name read as uniform-random sampling, but the behaviour is deterministic evenly-spaced (strided) selection. Kept for backward compatibility; instantiating it emits a DeprecationWarning.

__init__(n_configs)[source]
class remote_handler.workflows.selectors.RandomSelector(n_configs)[source]

Bases: ConfigSelector

Select configurations at random with an equal probability.

When given grouped input (list[list[Atoms]]), returns a random sample of n_configs from each inner list (e.g., one random frame from each trajectory/replica).

When given a flat list, returns a random sample of n_configs from it.

__init__(n_configs)[source]
select(configs, reference=None)[source]

Select configurations from a pool of candidates.

Parameters:
  • configs (Union[list[Atoms], list[list[Atoms]]]) – Pool of candidate configurations, either as a flat list[Atoms] or grouped list[list[Atoms]] (e.g., one inner list per trajectory).

  • reference (list[Atoms] | None) – Optional auxiliary set this selection scores against (e.g. the already-labelled data, for novelty). Selectors that don’t use a reference ignore it. Passed as an argument – not set via a mutator – so it composes cleanly (PipelineSelector forwards it to its members).

Return type:

list[Atoms]

Returns:

Flat list of selected configurations.

class remote_handler.workflows.selectors.UncertaintySelector(n_configs=None, energy_key='energy_uncertainty', forces_key='forces_uncertainty', energy_weight=1.0, forces_weight=1.0, threshold=None)[source]

Bases: ConfigSelector

Select configurations with highest uncertainty.

Reads uncertainty values that are expected to already be stored in the Atoms objects (e.g., computed by a committee model during the simulation). Selects the n_configs frames with highest combined uncertainty score.

The score is computed as:

score = energy_weight * normalized_energy_uncertainty
      + forces_weight * normalized_forces_uncertainty

where normalization maps each component to [0, 1] across all candidates.

Parameters:
  • n_configs (int | None) – Maximum number of configurations to select. Can be None when threshold is set (pure threshold mode).

  • energy_key (str | None) – Key in atoms.info for per-structure energy uncertainty. Set to None to ignore energy uncertainty.

  • forces_key (str | None) – Key in atoms.arrays for per-atom force uncertainty (shape (n_atoms, 3)). Set to None to ignore force uncertainty.

  • energy_weight (float) – Weight for energy uncertainty in combined score.

  • forces_weight (float) – Weight for force uncertainty in combined score.

  • threshold (float | None) – Minimum uncertainty score for selection. When set, only configs with score above this value are selected. Can be combined with n_configs to cap the count.

__init__(n_configs=None, energy_key='energy_uncertainty', forces_key='forces_uncertainty', energy_weight=1.0, forces_weight=1.0, threshold=None)[source]
select(configs, reference=None)[source]

Select configurations from a pool of candidates.

Parameters:
  • configs (Union[list[Atoms], list[list[Atoms]]]) – Pool of candidate configurations, either as a flat list[Atoms] or grouped list[list[Atoms]] (e.g., one inner list per trajectory).

  • reference (list[Atoms] | None) – Optional auxiliary set this selection scores against (e.g. the already-labelled data, for novelty). Selectors that don’t use a reference ignore it. Passed as an argument – not set via a mutator – so it composes cleanly (PipelineSelector forwards it to its members).

Return type:

list[Atoms]

Returns:

Flat list of selected configurations.

class remote_handler.workflows.selectors.ForceFilterSelector(force_threshold)[source]

Bases: ConfigSelector

Select configurations based on force magnitude threshold.

Filters out configurations where the maximum atomic force exceeds a specified threshold. Useful for removing high-energy or unstable structures from the candidate pool.

Parameters:

force_threshold (float) – Maximum allowed force magnitude (in eV/Å).

__init__(force_threshold)[source]
select(configs, reference=None)[source]

Select configurations from a pool of candidates.

Parameters:
  • configs (Union[list[Atoms], list[list[Atoms]]]) – Pool of candidate configurations, either as a flat list[Atoms] or grouped list[list[Atoms]] (e.g., one inner list per trajectory).

  • reference (list[Atoms] | None) – Optional auxiliary set this selection scores against (e.g. the already-labelled data, for novelty). Selectors that don’t use a reference ignore it. Passed as an argument – not set via a mutator – so it composes cleanly (PipelineSelector forwards it to its members).

Return type:

list[Atoms]

Returns:

Flat list of selected configurations.

class remote_handler.workflows.selectors.UniformForceSelector(n_configs, n_bins=10, force_n_configs=False)[source]

Bases: ConfigSelector

Select configurations uniformly across force magnitude bins.

Divides the range of average force magnitudes into bins and selects an equal number of configurations from each bin. This ensures a diverse representation of configurations across different force regimes.

Parameters:
  • n_configs (int) – Total number of configurations to select.

  • n_bins (int) – Number of bins to divide the force magnitude range into.

__init__(n_configs, n_bins=10, force_n_configs=False)[source]
select(configs, reference=None)[source]

Select configurations from a pool of candidates.

Parameters:
  • configs (Union[list[Atoms], list[list[Atoms]]]) – Pool of candidate configurations, either as a flat list[Atoms] or grouped list[list[Atoms]] (e.g., one inner list per trajectory).

  • reference (list[Atoms] | None) – Optional auxiliary set this selection scores against (e.g. the already-labelled data, for novelty). Selectors that don’t use a reference ignore it. Passed as an argument – not set via a mutator – so it composes cleanly (PipelineSelector forwards it to its members).

Return type:

list[Atoms]

Returns:

Flat list of selected configurations.

class remote_handler.workflows.selectors.QUESTSSelector(n_configs, method='msc', reference=None, k=32, cutoff=5.0, bandwidth=None, pca_output=None)[source]

Bases: ConfigSelector

Select configurations using QUESTS information entropy.

Uses model-free structural descriptors and information theory to select the most informative configurations. Two modes:

Diversity mode (no reference): Uses DatasetCompressor to select a structurally diverse subset from the candidates. The method parameter controls the selection strategy (MSC, FPS, etc.).

Novelty mode (with reference): Uses delta_entropy to score each candidate by how novel its atomic environments are relative to a reference dataset (e.g., existing training data). Selects the n_configs candidates with highest mean novelty score.

Requires the quests package (pip install quests).

Parameters:
  • n_configs (int) – Number of configurations to select.

  • method (str) – Selection method for diversity mode. One of "msc" (Maximum Structure Coverage, recommended), "fps" (Farthest Point Sampling), "random", "k_means". Ignored in novelty mode.

  • reference (list[Atoms] | None) – Default reference dataset for novelty mode. Usually supplied per-call via select(configs, reference=...) instead (which takes precedence), so a stage can pass the accumulated labelled data each iteration without mutating the selector.

  • k (int) – Number of nearest neighbors for QUESTS descriptor.

  • cutoff (float) – Cutoff radius in Angstroms for descriptor.

  • bandwidth (float | None) – Kernel bandwidth for entropy estimation. If None, estimated automatically from the volume per atom.

  • pca_output (Path | str | None) – If set, save a JSON file with PCA-projected descriptor data for visualization. Contains per-structure 2D coordinates, selection status, and explained variance.

__init__(n_configs, method='msc', reference=None, k=32, cutoff=5.0, bandwidth=None, pca_output=None)[source]
select(configs, reference=None)[source]

Select configurations from a pool of candidates.

Parameters:
  • configs (Union[list[Atoms], list[list[Atoms]]]) – Pool of candidate configurations, either as a flat list[Atoms] or grouped list[list[Atoms]] (e.g., one inner list per trajectory).

  • reference (list[Atoms] | None) – Optional auxiliary set this selection scores against (e.g. the already-labelled data, for novelty). Selectors that don’t use a reference ignore it. Passed as an argument – not set via a mutator – so it composes cleanly (PipelineSelector forwards it to its members).

Return type:

list[Atoms]

Returns:

Flat list of selected configurations.

class remote_handler.workflows.selectors.PipelineSelector(selectors)[source]

Bases: ConfigSelector

Chain multiple selectors sequentially.

Each selector’s output becomes the next selector’s input. Grouped input is only preserved for the first stage — subsequent stages receive flat lists (since selectors return list[Atoms]).

Example:

>>> pipeline = PipelineSelector([
...     UncertaintySelector(n_configs=100),
...     QUESTSSelector(n_configs=20, method="msc"),
... ])
>>> selected = pipeline.select(configs)  # 20 diverse high-uncertainty configs
Parameters:

selectors (list[ConfigSelector]) – Ordered list of selectors to apply.

__init__(selectors)[source]
select(configs, reference=None)[source]

Select configurations from a pool of candidates.

Parameters:
  • configs (Union[list[Atoms], list[list[Atoms]]]) – Pool of candidate configurations, either as a flat list[Atoms] or grouped list[list[Atoms]] (e.g., one inner list per trajectory).

  • reference (list[Atoms] | None) – Optional auxiliary set this selection scores against (e.g. the already-labelled data, for novelty). Selectors that don’t use a reference ignore it. Passed as an argument – not set via a mutator – so it composes cleanly (PipelineSelector forwards it to its members).

Return type:

list[Atoms]

Returns:

Flat list of selected configurations.

Evaluators

Ground-truth evaluators for active-learning workflows.

An evaluator labels sampled configurations with ground truth (energy + forces) by running a single-point calculation per configuration on a remote machine. Every calculator follows the same shape, so the shared machinery lives in AseCalculatorEvaluator; VASPEvaluator and ORCAEvaluator are thin presets that only assemble their calculator config. Most evaluators support stub=True to dry-run the loop without real compute.

class remote_handler.workflows.evaluators.AseCalculatorEvaluator(singlepoint_script, remote_fs, cluster_config, num_parallel, calc_config, remote_savepath=None, loop_time=30, required_fraction=0.5, n_processors=8, stub=False, slurm_header_add='', time_limit=None, collect_only=False, reattach_max_wait=None)[source]

Bases: DetachableTaskMixin, GroundTruthEvaluator

Single-point ground-truth evaluation with any ASE calculator.

Calculator-agnostic: it ships calc_config (the per-job input JSON) and runs singlepoint_script on the remote, which builds the calculator, computes energy + forces, and writes a labelled dft_<DB>.extxyz. Concrete calculators are presets that assemble calc_config (see VASPEvaluator, ORCAEvaluator).

Parameters:
  • singlepoint_script (PathLike) – Remote payload that builds the calculator.

  • remote_fs (FileSystemHandlerBase) – Filesystem handler for the evaluation machine.

  • cluster_config (ClusterConfig) – Target cluster configuration.

  • num_parallel (int) – Number of parallel jobs to queue.

  • calc_config (dict) – Calculator settings written into each job’s input JSON.

  • remote_savepath (Optional[PathLike]) – Remote path for the calculation files.

  • loop_time (float) – Seconds between polls for completion.

  • required_fraction (float) – Fraction of jobs that must succeed to proceed.

  • n_processors (int) – CPU cores per job.

  • stub (bool) – If True, produce mock outputs without running anything.

  • slurm_header_add (str) – Extra SLURM header lines (appended after any cluster-declared environment setup for this calculator).

  • time_limit (Optional[str]) – SLURM --time value (e.g. "0-02:00:00") capping each job. None (default) emits no --time, so the job runs to the partition maximum.

  • collect_only (bool) – If True, update reconstructs the array submitted by an earlier, collect_only=False call (from the manifest written beside <calcdir>/dft/results, via RemoteAtomsHandler.from_manifest) instead of allocating/submitting a new one, and get_evaluated_configs skips the (already-done) submission. evaluator_input is not read in this mode. Use this to collect a detached evaluation run from a fresh process.

  • reattach_max_wait (Optional[float]) – Only used when collect_only: how long (in seconds) to wait for the reattached job to finish before giving up. None (default) waits forever.

__init__(singlepoint_script, remote_fs, cluster_config, num_parallel, calc_config, remote_savepath=None, loop_time=30, required_fraction=0.5, n_processors=8, stub=False, slurm_header_add='', time_limit=None, collect_only=False, reattach_max_wait=None)[source]
apply_schedule(kwargs)[source]

Set scheduled values as attributes; rebuild calc_config when one of them is baked into it (e.g. VASP’s incar_kwargs), so the new value reaches the job.

Return type:

None

update(calcdir, evaluator_input, **kwargs)[source]

Prepare the evaluator for a new iteration.

Parameters:
  • calcdir (Path) – Directory for this AL iteration.

  • evaluator_input (Union[Path, list[Path], None]) – Path(s) to unlabelled configs to evaluate. Not read when collect_only – a second process reconstructing an already-submitted array from its manifest needs none of the original input, so None is expected there.

  • **kwargs – Additional parameters.

Return type:

None

get_evaluated_configs()[source]

Run the evaluation and collect the labelled configurations.

Return type:

Path

Returns:

Path to the .extxyz of evaluated configurations.

Raises:

TaskError – If fewer than required_fraction jobs succeed (or, when collect_only, if that doesn’t happen within reattach_max_wait).

class remote_handler.workflows.evaluators.VASPEvaluator(remote_fs, cluster_config, num_parallel, singlepoint_script=None, incar_kwargs=None, remote_savepath=None, launcher='mpirun -n', stub=False, loop_time=30, required_fraction=0.5, n_processors=8, slurm_header_add='', incar_config_file=None, time_limit=None, collect_only=False, reattach_max_wait=None)[source]

Bases: AseCalculatorEvaluator

VASP DFT preset of AseCalculatorEvaluator.

Parameters:
  • remote_fs (FileSystemHandlerBase) – Filesystem handler for the evaluation machine.

  • cluster_config (ClusterConfig) – Target cluster configuration.

  • num_parallel (int) – Number of parallel SLURM jobs to queue.

  • singlepoint_script (Optional[PathLike]) – Remote payload; defaults to the shipped dft_singlepoint.py.

  • incar_kwargs (Optional[dict]) – VASP INCAR tags (optional if incar_config_file is given).

  • remote_savepath (Optional[PathLike]) – Remote path for the calculation files.

  • launcher (str) – VASP launch prefix (e.g. "mpirun -n").

  • stub (bool) – If True, produce mock outputs without running VASP.

  • loop_time (float) – Seconds between polls for completion.

  • required_fraction (float) – Fraction of jobs that must succeed.

  • n_processors (int) – CPU cores per VASP job.

  • slurm_header_add (str) – Legacy per-call SLURM header lines. If given it takes precedence over the cluster’s environment["vasp"] (and emits a DeprecationWarning when both are set). Prefer putting the VASP module load and VASP_PP_PATH in that cluster JSON entry.

  • incar_config_file (Optional[PathLike]) – Optional path to a YAML file of INCAR tags, used instead of (or as a base for) incar_kwargs.

  • collect_only (bool) – If True, update reconstructs the array submitted by an earlier, collect_only=False call instead of allocating/submitting a new one. See AseCalculatorEvaluator’s docstring.

  • reattach_max_wait (Optional[float]) – Only used when collect_only: how long (in seconds) to wait for the reattached job to finish before giving up. None (default) waits forever.

__init__(remote_fs, cluster_config, num_parallel, singlepoint_script=None, incar_kwargs=None, remote_savepath=None, launcher='mpirun -n', stub=False, loop_time=30, required_fraction=0.5, n_processors=8, slurm_header_add='', incar_config_file=None, time_limit=None, collect_only=False, reattach_max_wait=None)[source]
property vasp_handler

Backward-compatible alias for the underlying handler.

class remote_handler.workflows.evaluators.ORCAEvaluator(cluster_config, remote_fs, num_parallel, orcasimpleinput, singlepoint_script=None, remote_savepath=None, loop_time=30, required_fraction=0.8, n_processors=2, orca_binary='/opt/ohpc/pub/dft/orca_6_1_0/orca', stub=False, slurm_header_add='', time_limit=None, collect_only=False, reattach_max_wait=None)[source]

Bases: AseCalculatorEvaluator

ORCA DFT preset of AseCalculatorEvaluator.

Parameters:
  • cluster_config (ClusterConfig) – Target cluster configuration.

  • remote_fs (FileSystemHandlerBase) – Filesystem handler for the evaluation machine.

  • num_parallel (int) – Number of parallel SLURM jobs to queue.

  • orcasimpleinput (str) – ORCA simple-input line (functional, basis, method).

  • singlepoint_script (Optional[PathLike]) – Remote payload; defaults to the shipped orca_singlepoint.py.

  • remote_savepath (Optional[PathLike]) – Remote path for the calculation files.

  • loop_time (float) – Seconds between polls for completion.

  • required_fraction (float) – Fraction of jobs that must succeed.

  • n_processors (int) – CPU cores per ORCA job.

  • orca_binary (str) – Full path to the ORCA executable.

  • stub (bool) – If True, produce mock outputs without running ORCA.

  • slurm_header_add (str) – Legacy per-call SLURM header lines. If given it takes precedence over the cluster’s environment["orca"] (and emits a DeprecationWarning when both are set). Prefer putting the ORCA module load in that cluster JSON entry.

  • collect_only (bool) – If True, update reconstructs the array submitted by an earlier, collect_only=False call instead of allocating/submitting a new one. See AseCalculatorEvaluator’s docstring.

  • reattach_max_wait (Optional[float]) – Only used when collect_only: how long (in seconds) to wait for the reattached job to finish before giving up. None (default) waits forever.

__init__(cluster_config, remote_fs, num_parallel, orcasimpleinput, singlepoint_script=None, remote_savepath=None, loop_time=30, required_fraction=0.8, n_processors=2, orca_binary='/opt/ohpc/pub/dft/orca_6_1_0/orca', stub=False, slurm_header_add='', time_limit=None, collect_only=False, reattach_max_wait=None)[source]
property orca_handler

Backward-compatible alias for the underlying handler.

class remote_handler.workflows.evaluators.EMTEvaluator(remote_fs, cluster_config, num_parallel, singlepoint_script=None, calculator_kwargs=None, remote_savepath=None, loop_time=30, required_fraction=0.5, n_processors=1, stub=False, slurm_header_add='', time_limit=None, collect_only=False, reattach_max_wait=None)[source]

Bases: AseCalculatorEvaluator

Cheap EMT ground-truth preset (pure ASE, no external binary).

Uses the generic ase_singlepoint.py payload with ASE’s EMT calculator. EMT supports only a handful of elements (Ni, Cu, Pd, Ag, Pt, Au, Al, H, C, N, O), but needs no licensed software – ideal for examples and CI runs over the direct executor, where VASP/ORCA cannot run.

Parameters:
  • remote_fs (FileSystemHandlerBase) – Filesystem handler for the evaluation machine.

  • cluster_config (ClusterConfig) – Target cluster configuration.

  • num_parallel (int) – Number of parallel jobs to queue.

  • singlepoint_script (Optional[PathLike]) – Remote payload; defaults to the shipped ase_singlepoint.py.

  • calculator_kwargs (Optional[dict]) – Keyword arguments forwarded to EMT(...).

  • remote_savepath (Optional[PathLike]) – Remote path for the calculation files.

  • loop_time (float) – Seconds between polls for completion.

  • required_fraction (float) – Fraction of jobs that must succeed.

  • n_processors (int) – CPU cores per job.

  • stub (bool) – If True, produce mock outputs without running anything.

  • slurm_header_add (str) – Extra SLURM header lines.

  • collect_only (bool) – If True, update reconstructs the array submitted by an earlier, collect_only=False call instead of allocating/submitting a new one. See AseCalculatorEvaluator’s docstring.

  • reattach_max_wait (Optional[float]) – Only used when collect_only: how long (in seconds) to wait for the reattached job to finish before giving up. None (default) waits forever.

__init__(remote_fs, cluster_config, num_parallel, singlepoint_script=None, calculator_kwargs=None, remote_savepath=None, loop_time=30, required_fraction=0.5, n_processors=1, stub=False, slurm_header_add='', time_limit=None, collect_only=False, reattach_max_wait=None)[source]

Trainers

Trainers for Active Learning Workflows.

Trainers fit machine learning models to evaluated configurations.

class remote_handler.workflows.trainers.MaceModelTrainer(remote_fs, cluster_config, config_file, training_script=None, remote_mace_train_runner=None, num_models=5, validation_fraction=0.1, remote_savepath=None, loop_time=30, stub=False, n_processors=1, convert_to_jax=False, jax_output_format='pkl', collect_only=False, reattach_max_wait=None)[source]

Bases: _MaceArrayTrainer

Trainer for MACE models using array script tasks.

Trains multiple MACE models in parallel using different random seeds. Supports stub mode for testing without actual training.

Parameters:
  • remote_fs (FileSystemHandlerBase) – FileSystemHandlerBase for the machine where training runs

  • config_file (PathLike) – Path to MACE YAML config file

  • training_script (Optional[PathLike]) – Remote payload; defaults to the shipped mace/mace_training.py.

  • remote_mace_train_runner (Optional[PathLike]) – Path to MACE run_train.py on the remote machine. Optional – if omitted, it is resolved automatically by probing the remote conda env (requires mace installed there).

  • num_models (int) – Number of models to train per generation

  • validation_fraction (float) – Fraction for train/validation split

  • remote_savepath (Optional[PathLike]) – Path on remote machine for calculation files

  • loop_time (float) – Interval (seconds) to poll for job completion

  • stub (bool) – If True, creates mock model outputs without training

  • convert_to_jax (bool) – If True, convert each trained torch model to a mace-jax bundle in the same job and return those paths from get_trained_model. The training (cluster) environment must then have both the torch MACE stack and mace-jax.

  • jax_output_format (str) – Bundle format when convert_to_jax – "pkl" (default; an opaque single-file pickle) or "bundle" (a directory with config.json + params.msgpack, the canonical inspectable format mace-jax’s loader / jaxrens consume).

  • collect_only (bool) – If True, update reconstructs the array task submitted by an earlier, collect_only=False call (from the manifest written beside <calcdir>/train/results) instead of allocating/submitting a new one, and get_trained_model skips the (already-done) submission. trainer_input is not read in this mode. Use this to collect a detached MACE training run from a fresh process.

  • reattach_max_wait (Optional[float]) – Only used when collect_only: how long (in seconds) to wait for the reattached job to finish before giving up. None (default) waits forever.

class remote_handler.workflows.trainers.MaceFinetuningTrainer(remote_fs, cluster_config, config_file, foundation_model, training_script=None, remote_mace_train_runner=None, num_models=5, validation_fraction=0.1, remote_savepath=None, loop_time=30, stub=False, convert_to_jax=False, n_processors=1, jax_output_format='pkl', collect_only=False, reattach_max_wait=None)[source]

Bases: _MaceArrayTrainer

Trainer for finetuning MACE models from a foundation model.

Like MaceModelTrainer but stages a pretrained foundation model as an extra shared resource. The optional torch -> mace-jax conversion is inherited from the shared base and works the same way here.

Parameters:
  • remote_fs (FileSystemHandlerBase) – FileSystemHandlerBase for the machine where training runs

  • config_file (PathLike) – Path to MACE YAML config file

  • foundation_model (PathLike) – Path to the pretrained foundation model file

  • training_script (Optional[PathLike]) – Remote payload; defaults to the shipped mace/mace_finetuning.py.

  • remote_mace_train_runner (Optional[PathLike]) – Path to MACE run_train.py on the remote machine. Optional – if omitted, it is resolved automatically by probing the remote conda env (requires mace installed there).

  • num_models (int) – Number of models to train per generation

  • validation_fraction (float) – Fraction for train/validation split

  • remote_savepath (Optional[PathLike]) – Path on remote machine for calculation files

  • loop_time (float) – Interval (seconds) to poll for job completion

  • stub (bool) – If True, creates mock model outputs without training

  • convert_to_jax (bool) – If True, convert each trained torch model to a mace-jax bundle in the same job and return those paths from get_trained_model. The training (cluster) environment must then have both the torch MACE stack and mace-jax.

  • jax_output_format (str) – Bundle format when convert_to_jax – "pkl" (default; an opaque single-file pickle) or "bundle" (a directory with config.json + params.msgpack, the canonical inspectable format mace-jax’s loader / jaxrens consume).

  • collect_only (bool) – If True, update reconstructs the array task submitted by an earlier, collect_only=False call (from the manifest written beside <calcdir>/train/results) instead of allocating/submitting a new one, and get_trained_model skips the (already-done) submission. trainer_input is not read in this mode. Use this to collect a detached MACE training run from a fresh process.

  • reattach_max_wait (Optional[float]) – Only used when collect_only: how long (in seconds) to wait for the reattached job to finish before giving up. None (default) waits forever.

__init__(remote_fs, cluster_config, config_file, foundation_model, training_script=None, remote_mace_train_runner=None, num_models=5, validation_fraction=0.1, remote_savepath=None, loop_time=30, stub=False, convert_to_jax=False, n_processors=1, jax_output_format='pkl', collect_only=False, reattach_max_wait=None)[source]
class remote_handler.workflows.trainers.AceModelTrainer(remote_fs, cluster_config, config_file, training_script=None, remote_train_runner=None, num_models=5, validation_fraction=0.1, remote_savepath=None, loop_time=30, stub=False, n_processors=1, collect_only=False, reattach_max_wait=None, keep_best=None, num_parallel=None)[source]

Bases: _AceArrayTrainer

Trainer for ACE (Atomic Cluster Expansion) models, fit with pacemaker (https://github.com/ICAMS/python-ace) using array script tasks.

Trains multiple ACE potentials in parallel using different random seeds, mirroring MaceModelTrainer. Supports stub mode for testing without actual training. pacemaker (the python-ace/pyace package) is typically installed via conda-forge or built from source, since it ships compiled C++ extensions – see the ace optional-dependency extra.

Parameters:
  • remote_fs (FileSystemHandlerBase) – FileSystemHandlerBase for the machine where training runs

  • config_file (PathLike) – Path to a YAML config with pacemaker’s potential/ fit/backend sections (no data/seed needed there – those are injected per job)

  • training_script (Optional[PathLike]) – Remote payload; defaults to the shipped ace/ace_training.py.

  • remote_train_runner (Optional[PathLike]) – Path to the pacemaker executable on the remote machine. Optional – if omitted, it is resolved automatically by probing the remote conda env’s PATH.

  • num_models (int) – Number of models to train per generation

  • validation_fraction (float) – Fraction of data pacemaker splits off as its own internal test set

  • keep_best (Optional[int]) – If given, hand on only this many of the num_models members: those with the lowest final test loss (pacemaker’s test_metrics.txt), best first. Each member’s test set is its own random split, so the ranking is a coarse outlier filter, not a precise comparison.

  • num_parallel (Optional[int]) – Array tasks running at once (default: min(num_models, 5)).

  • remote_savepath (Optional[PathLike]) – Path on remote machine for calculation files

  • loop_time (float) – Interval (seconds) to poll for job completion

  • stub (bool) – If True, creates mock model outputs without training

  • collect_only (bool) – If True, update reconstructs the array task submitted by an earlier, collect_only=False call (from the manifest written beside <calcdir>/train/results) instead of allocating/submitting a new one, and get_trained_model skips the (already-done) submission. trainer_input is not read in this mode. Use this to collect a detached ACE training run from a fresh process.

  • reattach_max_wait (Optional[float]) – Only used when collect_only: how long (in seconds) to wait for the reattached job to finish before giving up. None (default) waits forever.

class remote_handler.workflows.trainers.GraceModelTrainer(remote_fs, cluster_config, config_file, training_script=None, remote_train_runner=None, num_models=5, validation_fraction=0.1, remote_savepath=None, loop_time=30, stub=False, n_processors=1, collect_only=False, reattach_max_wait=None, keep_best=None, num_parallel=None)[source]

Bases: _GraceArrayTrainer

Trainer for GRACE (Graph Atomic Cluster Expansion) models, fit with gracemaker (https://github.com/ICAMS/grace-tensorpotential) using array script tasks.

Trains multiple GRACE potentials in parallel using different random seeds, mirroring MaceModelTrainer. Supports stub mode for testing without actual training. gracemaker is installed via the grace optional-dependency extra (the tensorpotential package).

Parameters:
  • remote_fs (FileSystemHandlerBase) – FileSystemHandlerBase for the machine where training runs

  • config_file (PathLike) – Path to a YAML config with gracemaker’s cutoff/ potential/fit sections (no data/seed needed there – those are injected per job)

  • training_script (Optional[PathLike]) – Remote payload; defaults to the shipped grace/grace_training.py.

  • remote_train_runner (Optional[PathLike]) – Path to the gracemaker executable on the remote machine. Optional – if omitted, it is resolved automatically by probing the remote conda env’s PATH.

  • num_models (int) – Number of models to train per generation

  • validation_fraction (float) – Fraction of data gracemaker splits off as its own internal test set

  • remote_savepath (Optional[PathLike]) – Path on remote machine for calculation files

  • loop_time (float) – Interval (seconds) to poll for job completion

  • stub (bool) – If True, creates mock model outputs without training

  • collect_only (bool) – If True, update reconstructs the array task submitted by an earlier, collect_only=False call (from the manifest written beside <calcdir>/train/results) instead of allocating/submitting a new one, and get_trained_model skips the (already-done) submission. trainer_input is not read in this mode. Use this to collect a detached GRACE training run from a fresh process.

  • reattach_max_wait (Optional[float]) – Only used when collect_only: how long (in seconds) to wait for the reattached job to finish before giving up. None (default) waits forever.

class remote_handler.workflows.trainers.NeuralilILTrainer(remote_fs, cluster_config, training_script=None, remote_savepath=None, training_kwargs=None, stub=False, loop_time=30, config_file=None, collect_only=False, reattach_max_wait=None)[source]

Bases: DetachableTaskMixin, ModelTrainer

Trainer for NeuralIL models using JAXNEST framework.

Trains NeuralIL models with custom configuration. Supports stub mode for testing without actual training.

Hyperparameters resolve in three layers (later overrides earlier): built-in defaults < config_file (a YAML file you author) < training_kwargs (an explicit dict). All optional – with none given the built-in defaults are used.

Parameters:
  • training_script (Optional[PathLike]) – Remote payload; defaults to the shipped neuralil/neuralil_training.py.

  • remote_fs (FileSystemHandlerBase) – FileSystemHandlerBase for the machine where training runs

  • remote_savepath (Optional[PathLike]) – Path on remote machine for calculation files

  • training_kwargs (dict) – Explicit hyperparameter overrides (highest precedence).

  • stub (bool) – If True, creates mock model outputs without training

  • loop_time (float) – Interval (seconds) to poll for job completion

  • config_file (Optional[PathLike]) – Optional path to a YAML file of hyperparameters, layered on the built-in defaults (mirrors MaceModelTrainer’s config_file). Overridden by anything in training_kwargs.

  • collect_only (bool) – If True, update reconstructs the task submitted by an earlier, collect_only=False call (from the manifest written beside <calcdir>/training/results) instead of allocating/submitting a new one, and get_trained_model skips the (already-done) submission. trainer_input is not read in this mode. Use this to collect a detached NeuralIL training run from a fresh process.

  • reattach_max_wait (Optional[float]) – Only used when collect_only: how long (in seconds) to wait for the reattached job to finish before giving up. None (default) waits forever.

default_training_kwargs: dict = {'core_widths': [128, 64, 32], 'embed_d': 1, 'energy_weight': 0.5, 'high_energy_penalty': None, 'high_energy_penalty_relative': 5.0, 'learning_rate_kwargs': {'fin_learning_rate': 1e-05, 'max_learning_rate': 0.01, 'min_learning_rate': 0.001}, 'log_cosh_parameter_energy': 0.2, 'log_cosh_parameter_forces': 2.0, 'morse': False, 'n_batch': 32, 'n_ensemble': 30, 'n_epochs': 100, 'n_eval_batch': 64, 'n_max': 6, 'optimizer_type': 'VeLO', 'r_cut': 4.0, 'save_reduced': 5, 'seed': None, 'stub': False, 'supercell_diag': [3, 3, 3], 'training_fraction': 0.75}
__init__(remote_fs, cluster_config, training_script=None, remote_savepath=None, training_kwargs=None, stub=False, loop_time=30, config_file=None, collect_only=False, reattach_max_wait=None)[source]
unknown_schedule_keys(kwargs)[source]

Schedule keys may be attributes (config_file, training_kwargs, …) or single hyperparameters (n_epochs).

Return type:

list[str]

apply_schedule(kwargs)[source]

Apply scheduled attributes and hyperparameters.

config_file, training_kwargs and stub re-layer the merged hyperparameters (a scheduled training_kwargs replaces the explicit overrides); single hyperparameter keys then go on top.

Return type:

None

update(calcdir, trainer_input, **kwargs)[source]

Prepare trainer for a new iteration.

Parameters:
  • calcdir (PathLike) – Directory for this AL iteration

  • trainer_input (Union[Path, list[PathLike], None]) – Path(s) to database files with training data. Not read when collect_only – see MaceModelTrainer.

  • **kwargs – Additional parameters

Return type:

None

get_trained_model()[source]

Run training and return model file path.

Return type:

PathLike

Returns:

Path to trained model file

Raises:

TaskError – If training doesn’t complete successfully (or, when collect_only, if that doesn’t happen within reattach_max_wait).