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_handlerif set, else~/.config/remote_handler. Read at call time so it honours a monkeypatched environment in tests.- Return type:
- remote_handler.config.get_persistent_config_file()[source]
Path to the persistent global config JSON (may not exist).
- Return type:
- 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:
objectCentralized configuration for remote_handler.
Each field is documented inline below.
- test_cluster: Optional[str] = None
Name (without
.json) of the per-cluster config used as the target for theremotetest tier.Nonefalls back toremote.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:
- 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:
- 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:
- 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:
- 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)
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:
- 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:
Example
>>> config = RemoteHandlerConfig(config_dir=Path("/invalid")) >>> config.validate() # Raises ConfigurationError
- to_dict()[source]
Convert configuration to dictionary.
- Return type:
- 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_dirdefaults to the persistent config directory when neither the file nor the environment set it, so per-cluster JSONs live next toconfig.jsonwith no prior setup.- Return type:
- Returns:
Merged RemoteHandlerConfig.
- __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:
- 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:
Example
>>> # For testing >>> test_config = RemoteHandlerConfig(config_dir=Path("/tmp/test")) >>> set_config(test_config)
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:
objectConfiguration 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/templateare only consulted by the SLURM backend.- Parameters:
remote_machine (
str) – SSH alias or hostname of the remote machinepartition (
str) – SLURM partition name to submit jobs to (SLURM backend only)conda_env (
str) – Name of the conda environment to activate on the remoteconda_env_dir (
Optional[str]) – Directory on the remote where the named environments live, for setups that store envs outside the conda install’senvs/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 savedtemplate (
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 expiredstep ssh logincert), 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 subprocesssshcall, so a hung ssh (e.g. blocked on an interactive QR/MFA prompt after the credential expired) fails withTimeoutExpiredinstead of parking the driver forever. Applies regardless ofresilient_connection;Nonedisables 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 remotetarprocess over the same SSH connection – far faster for many small files, at the cost of needingtaron the remote (it falls back to"sftp"whentaris missing).slurm_header_add (
str) – Cluster-intrinsic SLURM header lines prepended to the header of every job on this cluster, before any per-callslurm_header_addan actor passes. Use it for setup that is a property of the machine rather than of the job – e.g. datalab’sexport TMPDIR=$HOME/tmp(its/tmpis 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,sourceof an env script,exportof paths likeVASP_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 asslurm_header_addis appended after it. Empty by default.
Example
>>> config = ClusterConfig.from_file("my_cluster.json") >>> print(config.remote_machine) 'my-hpc-cluster'
- property connection_policy: ConnectionPolicy
Build the
ConnectionPolicydescribed by this config.
- remote_fs(**kwargs)[source]
Open a
RemoteFileSystemto this cluster under its policy.Prefer this over constructing
RemoteFileSystemby hand: it can’t forgetconnection_policyortransfer, so the initial connect and every SFTP op honourresilient_connectionand directory downloads use the configured transfer mode.kwargsare forwarded; explicit values win.- Return type:
- 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:
- 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>.jsonin the resolved config directory – whereremote_handler configure cluster <name>writes it – and loads it. A trailing.jsoninnameis accepted and ignored, so bothfrom_name("lugus")andfrom_name("lugus.json")work.- Parameters:
name (
str) – Registered cluster name (the<name>.jsonstem).- Return type:
- 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>.jsonstems (excluding the globalconfig.json) thatfrom_name()accepts. Returns an empty list when nothing is configured.
- 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:
- classmethod from_dict(config_dict)[source]
Create a ClusterConfig from a dictionary.
- Parameters:
config_dict (
dict) – Dictionary containing cluster configuration- Return type:
- 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" ... })
- __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:
ABCClass 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]
- is_finished()[source]
Non-blocking completion poll (see
Executor.is_finished).Thin wrapper over
check_status(); requires the job to have been submitted orExecutor.attach-ed first.- Return type:
- 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]
- 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,ArrayExecutorClass 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]
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 aTypeError).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:
ABCInterface 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.- abstractmethod put(local, remote)[source]
Copy a file or directory from the local machine to a remote machine.
- abstractmethod makedirs(path, exist_ok=False)[source]
Create a directory at the specified path, including any necessary parent directories.
- abstractmethod write_str_to_file(string, filepath)[source]
Write a string to a file at the specified file path.
- abstractmethod write_dict_to_json(filepath, param_dict)[source]
Write a dictionary to a JSON file at the specified file path.
- abstractmethod read_ase(filepath, **kwargs)[source]
Read an ASE Atoms object from a file at the specified file path.
- abstractmethod write_ase(filepath, atoms_list, **kwargs)[source]
Write a list of ASE Atoms objects to a file at the specified file path.
- abstractmethod create_tempdir()[source]
Create a temporary directory and return its path.
- Return type:
- 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:
- class remote_handler.core.file_handler.LocalFileSystem[source]
Bases:
FileSystemHandlerBaseLocalFileSystem is a concrete implementation of FileSystemHandlerBase for handling file operations on the local filesystem.
- 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:
- 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:
- 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:
- makedirs(path, exist_ok=False)[source]
Create a directory at the specified path, including any necessary parent directories.
- 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:
- get_dir(src_dir, dst_dir)[source]
Recursively copy local directory to another location on the local filesystem. An existing
dst_diris completed (files are overwritten), matching the incrementalRemoteFileSystem.get_dir. :param src_dir: Local directory path :type src_dir:PathLike:param dst_dir: Local target path :type dst_dir:PathLike- Return type:
- 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:
- 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:
- 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:
- 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:
- create_tempdir()[source]
Create a temporary directory on the local filesystem and return its path.
- Return type:
- 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. RaisesCommandTimeoutErrorif it runs longer thantimeoutseconds (Nonewaits indefinitely).- Return type:
- 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_policyis enabled (opt-in, off by default), the operation escalates toresilience.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:
FileSystemHandlerBaseRemoteFileSystem 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) – Howget_dir()moves files:"sftp"(default) or"tar". SeeClusterConfig.
- __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:
- rmtree(remotepath)[source]
Recursively delete a directory on the remote system via SFTP.
Symlinks are removed, never followed, so a link pointing outside
remotepathcannot cause anything there to be deleted. If the connection drops midway, the reconnect retry relists and continues with what is left.
- 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
.partsibling and renamed when complete, so a dropped connection never leaves a truncated file under its final name. A missingremote_diris 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 remotetarover the same SSH connection; if the remote has notarit falls back to the"sftp"path.
- write_str_to_file(string, filepath)[source]
Write a string to a file at the specified file path on the remote system.
- 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:
- 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.
- 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:
- 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:
- create_tempdir()[source]
Create a temporary directory on the remote filesystem and return its path.
- Return type:
- 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
sshsubprocess, no dependency on the default~/.ssh/config). Detached launches (nohup ... &) return at once because the foreground statement exits immediately.Raises
CommandTimeoutErrorif the command has not exited withintimeoutseconds (Nonewaits indefinitely). The channel is closed then; the remote process may keep running.- Return type:
Task Management
- remote_handler.core.tasks.finalize_manifest_kwargs(cls, base_kwargs, extra)[source]
Merge manifest-derived kwargs with caller-supplied
extraoverrides.Used by
from_manifest()classmethods to build the final constructor call – shared across modules (ArrayScriptTask/SingleScriptTaskhere,RemoteAtomsHandlerinatoms_handler.py), so it is public rather than module-private. Anyextrakey that is not a real parameter ofcls.__init__is a typo and raises loudly; anything else (including a stale key that ends up inbase_kwargs) is silently dropped rather than raising a confusingTypeErrorfrom the constructor call.- Return type:
- 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/SingleScriptTaskhere,RemoteAtomsHandlerinatoms_handler.py): attachestask.executorto the manifest’s job soexecutor.is_finished()can tell whether the job is still running – whichDetachableTaskMixin.wait_if_neededneeds to avoid collecting a reattached array before all its tasks are done. SLURM needs the recordedjob_id;directneeds no handle (it polls a sentinel file). A SLURM manifest without ajob_idis left unattached, andwait_if_neededfalls back to polling markers.- Return type:
- class remote_handler.core.tasks.RemoteTask(logfile, savepath, remote_fs, jobname='job', collect_only=False)[source]
Bases:
ABCThis 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 simplesubprocess.run(...)call, but can also include more elaborate slurm handling viaremote_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 printedsavepath (
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.
- 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:
RemoteTaskThis 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 machinecluster_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),submitpersists 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 withTaskHandle.from_fileto poll and collect the job from another process.- Return type:
- 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 runallocate_data()itself (e.g. a workflow actor that allocates as part ofupdate()and only wants to detach at submit time).Suppresses
submit’s own manifest write and writes exactly once here instead, so thelocal_path/write_remotearguments are honored (and the remote copy is not written twice).- Return type:
- 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:
- 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, sofinish_check()/collect_results()can be called on it in a fresh process.script_file/input_fileare never read incollect_onlymode, so they are leftNone.- Parameters:
manifest_path (
PathLike) – Local*.manifest.jsonfile written bywrite_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 validSingleScriptTaskparameters.
- Return type:
- class remote_handler.core.tasks.Writeable(content, filename, remote_fs)[source]
Bases:
ABCThis 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.
- remote_fs: FileSystemHandlerBase
- __init__(content, filename, remote_fs)
- class remote_handler.core.tasks.FileAllocator(remote_fs, rootpath)[source]
Bases:
objectHandles 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 operationsrootpath (
PathLike) – Root directory on remote where files are allocated
- copy_path(local_path)[source]
Copy a local file or directory tree to remote rootpath.
Like
copy_file(), but iflocal_pathis a directory (e.g. a mace-jax model bundle ofconfig.json+params.msgpack) it is uploaded recursively viaput_dirrather than the single-fileput. A plain file is handled exactly ascopy_filewould.
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.
- class remote_handler.core.tasks.ResultCollector(remote_fs, local_fs)[source]
Bases:
objectHandles 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:
remote_fs (
FileSystemHandlerBase) – FileSystemHandlerBase instance for remote operationslocal_fs (
FileSystemHandlerBase) – FileSystemHandlerBase instance for local operations
- 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 machinelocal_path (
PathLike) – Path where directory should be copied on local machinemove (
bool) – If True, handle existing local_path by moving it aside; if False, delete it. Ignored whenresumeis set.resume (
bool) – Keep an existing local_path and only fetch what is missing or incomplete (get_dirskips files whose size already matches) – e.g. to finish an interrupted collect.
- Return type:
- 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:
RemoteTaskThis 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 machinecluster_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),submitpersists 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 whenindividual_ressourcesis empty (e.g. reconstructing acollect_onlytask viafrom_manifest(), where no allocation happens); inferred fromindividual_ressourcesotherwise. 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_tasksrather than stored, so it works equally whether this task just allocated its own directories or was reconstructed viafrom_manifest()without allocating at all – as long ascalcdirresolves to the same directory both times (guaranteed by reusing the manifest’s resolvedremote_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(); recordsnum_array_tasksso the array executor is rebuilt correctly.- Return type:
- 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 whenallocate_data()has already run (e.g. a trainer that allocates duringupdate()and only wants to detach at submit time).- Return type:
- detach(local_path=None, write_remote=True)[source]
Allocate, start the array job, persist manifest, return at once.
See
SingleScriptTask.detach().- Return type:
- 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, andnum_array_tasks), without re-allocating or re-submitting, sofinish_check()/collect_results()can be called on it in a fresh process.- Parameters:
manifest_path (
PathLike) – Local*.manifest.jsonfile written bywrite_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 validArrayScriptTaskparameters.
- Return type:
- class remote_handler.core.tasks.DetachableTaskMixin[source]
Bases:
objectShared “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, aGroundTruthEvaluator, or a downstreamSampler(concrete samplers live outside this package, in downstream repos, so this needs to be public) – needs the samecollect_onlymode 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 (seeremote_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_onlyandself.remote_fsin its own__init__– those stay declared per-class (they belong in each actor’s own constructor signature/ docstring, same asn_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) andbuild_or_resume_single_task()(SingleScriptTask, one job). Both funnel throughbuild_or_resume_task(), identical apart from which class’sfrom_manifestgets 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_onlymode – seeNeuralilILTrainer’spickle_filename, computed fromcalcdiralone up front, precisely soget_trained_model()does not depend on the closure having run.- remote_fs: FileSystemHandlerBase
- iteration_dir(calcdir)[source]
This iteration’s working directory,
calcdir / _iteration_subdir.Computed from
calcdiralone (never from instance state likeself.results_dir), so it gives the same answer whether called fromupdate()while building this iteration’s task, or frompending_manifest()beforeupdate()has ever run – which is the whole point of the latter.- Return type:
- results_dir_for(calcdir)[source]
This iteration’s
results_dir, i.e. where this actor’s task is built withlocal_savepath=and wheremanifest_path()then looks for a manifest. Single source of truth for bothupdate()(which assigns its result toself.results_dir) andpending_manifest().- Return type:
- pending_manifest(calcdir)[source]
Default
pending_manifestfor any actor that sets_iteration_subdir– overrides theSampler/GroundTruthEvaluator/ModelTrainerABCs’ own default (alwaysNone) via normal MRO resolution, since this mixin is listed first (class Foo(DetachableTaskMixin, ModelTrainer)). SeeModelTrainer.pending_manifestfor the full rationale.Returns
None(reattach unsupported, the ABC default) rather than raising when_iteration_subdirisn’t set, unlikeiteration_dir()– an actor that hasn’t wired this up yet should just not support reattach, not crash the whole loop.
- manifest_path(results_dir)[source]
Where
write_manifest/detachputs this task’s manifest.A fixed naming convention (
<results_dir>.manifest.json, matchingRemoteTask._save_manifest’s own default) rather than a constructor argument – so a latercollect_only=Truecall can find it fromresults_diralone, without the caller having to remember/pass a manifest path explicitly.- Return type:
- 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): callsbuild_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 insidebuild_taskso every caller gets it uniformly, the same way it’s skipped uniformly below.collect_only=True: reconstructs the task an earlier,collect_only=Falsecall already submitted, viatask_cls.from_manifestatmanifest_path(), with no allocation and no re-submit.build_taskis 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) –ArrayScriptTaskorSingleScriptTask– 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 notcollect_only.**from_manifest_extra – Extra constructor overrides for the
collect_onlypath (e.g.python_script_file); ignored otherwise.
- Return type:
- build_or_resume_array_task(results_dir, build_task, **from_manifest_extra)[source]
build_or_resume_task()for anArrayScriptTask.- Return type:
- build_or_resume_single_task(results_dir, build_task, **from_manifest_extra)[source]
build_or_resume_task()for aSingleScriptTask.- Return type:
- submit_if_needed(task)[source]
Submit
task, unless it was already submitted in another process.- Return type:
- 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_checkdefaults totask.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()(viasubmit_if_needed, called before this) already blocked – via the executor’s own queue-/sentinel-based wait – until the job left the queue. So a singlefinish_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_manifestre-attaches the executor to the recorded job (seeattach_from_manifest()), so this pollstask.executor.is_finished()– the queue, not the success markers – everypoll_intervalseconds (default:task.loop_timeif present, else 30.0) until the job is done ormax_waitseconds have elapsed (None, the default, means wait forever – matchingConnectionPolicy’s convention). Only then isfinish_check()applied, once, exactly as on the fresh path. Pollingfinish_check()directly would be wrong for a fraction-based check: a reattached array would be collected as soon asrequired_fractionof 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 pollingfinish_check()itself and logs a warning.- Parameters:
error_message (
Optional[str]) – Used verbatim as the exception message whenfinish_check()fails (on either path); also the prefix of the message raised whencollect_onlypolling exceedsmax_wait. Defaults to a generic message naming the task type.- Raises:
TaskError – If the job never finishes within
max_wait, or iffinish_check()fails once the job is done.- Return type:
SLURM Utilities
- remote_handler.core.slurm_utils.validate_slurm_available(ssh_command, target, policy)[source]
Probe that
sbatchis available on the target system.Runs
which sbatchthrough the same resilient wrapper assubmit_job()/ the status checks: with an enabledpolicyan expired/lost credential pauses-and-retries here instead of crashing, andpolicy.command_timeoutstill bounds a hung ssh.- Parameters:
ssh_command – The
ssh <alias>prefix, orNoneto 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 sbatchtruly absent exits 1 on the remote, whereas ssh’s own connect/auth failure exits 255.DependencyError –
sbatchis 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:
- 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:
- 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.
- 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 withslurm_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:
squeuealso fails when the controller is briefly unresponsive (e.g.Socket timed out on send/recv operation), which says nothing about the job. Only afterretriesfurther failures,retry_waitseconds apart, is the error raised.- Parameters:
- Returns:
False if the job is still running, True if it has finished.
- Return type:
- class remote_handler.core.slurm_utils.LoggingFileSystemLoader(searchpath, encoding='utf-8', followlinks=False)[source]
Bases:
FileSystemLoaderCustom Jinja2 file system loader that logs which template files are loaded.
- 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:
- 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:
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:
ArrayScriptTaskCoordinates 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.Noneskips the shard manager entirely (no reading, no sharding) – only used byfrom_manifest(), wherenum_array_tasksis supplied directly instead, exactly the wayArrayScriptTask(num_array_tasks=...)lets acollect_onlyreconstruction skipindividual_ressources. Never passNonedirectly; 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.Noneor 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, thesavepathshould 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 resolvedsavepath, cluster config, filesystem, andnum_array_tasks), without re-reading or re-sharding the original trajectory files – which a plainRemoteAtomsHandler(traj_files=..., collect_only=True, ...)reconstruction would still do today, purely to recomputenum_array_tasks, even though a collect call never uses the shards themselves.Because
traj_files=Noneskips the shard manager entirely (see__init__), the returned handler has noshard_managerand cannot do trajectory-shape-aware collection (collect(),regroup(),redistribute(),collect_and_harvest(),recompute_failed()). It supports exactly whatArrayScriptTaskitself offers:finish_check()and the generic, per-jobcollect_results()– which is allAseCalculatorEvaluatoractually uses (it scansresults_dir/calcdirsitself rather than callingcollect()/regroup()).- Parameters:
manifest_path (
PathLike) – Local*.manifest.jsonfile written bywrite_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 byredistribute, which is unavailable here regardless).**extra – Additional/overriding constructor kwargs; must be valid
RemoteAtomsHandlerparameters.
- Return type:
- 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 viafrom_manifest()(shard_manager=None), so a reconstructed collect-only handler supports the exact samefinish_check(required_fraction)call a freshly-built one does, with no special-casing needed by callers likeAseCalculatorEvaluator.
- 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.
- 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.
- 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.
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.
- 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:
- 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:
objectManages 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.Noneor 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).
- 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
infodict, 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
Noneor a negative value processes the whole set as one shard.- Parameters:
local_fs (
FileSystemHandlerBase) – Filesystem handler for reading trajectory files.- Return type:
- 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:
- 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:
- 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, anda 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:
RemoteTrajectoryProcessor– run an ordered list of processors over a sharded trajectory;RemoteOptimizationHandler– thin factory for the optimize step.Processor– base for a host-side spec;OptimizeProcessor,RDFProcessor,SteinhardtProcessor– the built-ins.register()– the downstream extension point.
- class remote_handler.processing.Processor[source]
Bases:
ABCOne processing step in the remote pipeline.
A
Processorcontributes only its own remote arguments and any files that must be staged for it – nothing about sharding or transport. Itsnamekeys both the orderedstepslist and the per-stepargsmap in the shard input JSON, and must match a processor in the registry.Subclassing is low-ceremony: set a class-level
nameand implementbuild_args().registration_moduledefaults to the subclass’s own module (so a downstream processor defined alongside itsrun+registercall resolves on the cluster with nothing else to declare); built-ins, whoserunis always loaded, set it toNone. A missingnameis caught at class-definition time.- registration_module: Optional[str] = None
Import path of the module whose import registers this step’s
runin the cluster-sideREGISTRY(viaregister(name, run)).Nonefor 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 (seeshared_files()).- Return type:
Files staged once and shared across all shards (default: none).
- Return type:
- 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:
RemoteAtomsHandlerRun an ordered pipeline of
Processorsteps over a trajectory.Shards the input trajectories, ships each shard a per-shard input JSON (the ordered
steps+ per-stepargs) 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.extxyzfile(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.Noneor 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 shippeddriver.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]
- 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:
RemoteTrajectoryProcessorOptimize 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:
ProcessorRelax each structure with an NNFF/MACE ensemble or an LJ calculator.
- registration_module: Optional[str] = None
Import path of the module whose import registers this step’s
runin the cluster-sideREGISTRY(viaregister(name, run)).Nonefor 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 (seeshared_files()).- Return type:
Files staged once and shared across all shards (default: none).
- Return type:
- class remote_handler.processing.RDFProcessor(cutoff=5.0, nbins=200)[source]
Bases:
ProcessorAnnotate structures with the radial distribution function.
- registration_module: Optional[str] = None
Import path of the module whose import registers this step’s
runin the cluster-sideREGISTRY(viaregister(name, run)).Nonefor built-in processors, which are already in the always-loaded registry. Defaults (via__init_subclass__) to the subclass’s own module.
- class remote_handler.processing.SteinhardtProcessor(r_cut, *, l_values=(4, 6), r_cut_min=0.0)[source]
Bases:
ProcessorAnnotate structures with Steinhardt bond-orientational order params.
- registration_module: Optional[str] = None
Import path of the module whose import registers this step’s
runin the cluster-sideREGISTRY(viaregister(name, run)).Nonefor built-in processors, which are already in the always-loaded registry. Defaults (via__init_subclass__) to the subclass’s own module.
- 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:
ScriptInputArgs for the
optimizeprocessor.backend/fmax/stepsare always required; the NNFF/MACE backends additionally need apickle_file(the staged model) and carry the neighbour-bucket / supercell knobs. Fields leftNoneare dropped byto_dictso an LJ payload stays minimal.- 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
rootis 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:
- __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:
ScriptInputArgs for the
rdfprocessor.- 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
rootis 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:
- __init__(cutoff, nbins)
- class remote_handler.processing.SteinhardtArgs(l_values=list(), r_cut=0.0, r_cut_min=0.0)[source]
Bases:
ScriptInputArgs for the
steinhardtprocessor.- 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
rootis 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:
- __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:
ScriptInputInput configuration for the trajectory-processing driver.
Drives a pipeline of processors over a trajectory shard. Rather than a fixed set of
do_Xflags, it carries an ordered list of processorstepsand a per-stepargsmap – so optimization and any structural analysis compose in one job, and adding a processor needs no schema change.- steps
Ordered processor names to run (e.g.
["optimize", "rdf"]); each must exist in the processor registry
- registration_modules
Import paths the driver imports (idempotently) before resolving
steps, so downstream processors register theirrunin the registry. Empty for built-in-only pipelines.
Example
>>> config = ProcessTrajInput.from_file(Path("input_process.json")) >>> config.validate()
- 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
argsis 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’svalidate_argsright after importing the registration modules, so a malformed composed payload fails fast at job start.- Raises:
ScriptInputError – If any parameter is invalid
- Return type:
- __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
Processorsubclass in the same module – itsregistration_modulethen 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 samerun.- Parameters:
name – Registry key; must match the host-side
Processor.name.run –
callable(atoms_list, args, calcpath) -> atoms_list.schema – Optional
ScriptInputsubclass declaring this step’s arg contract. The driver validates the step’s args against it at job start (viafrom_dict(...).validate()), so a bad composed payload fails fast instead of deep inside a task. This is the same schema the host-sideProcessor.build_argsfills, 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
argsthrough the registered schema (schema.from_dict(args).validate()); raisesScriptInputErroron 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:
ABCOne processing step in the remote pipeline.
A
Processorcontributes only its own remote arguments and any files that must be staged for it – nothing about sharding or transport. Itsnamekeys both the orderedstepslist and the per-stepargsmap in the shard input JSON, and must match a processor in the registry.Subclassing is low-ceremony: set a class-level
nameand implementbuild_args().registration_moduledefaults to the subclass’s own module (so a downstream processor defined alongside itsrun+registercall resolves on the cluster with nothing else to declare); built-ins, whoserunis always loaded, set it toNone. A missingnameis caught at class-definition time.- registration_module: Optional[str] = None
Import path of the module whose import registers this step’s
runin the cluster-sideREGISTRY(viaregister(name, run)).Nonefor 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 (seeshared_files()).- Return type:
Files staged once and shared across all shards (default: none).
- Return type:
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
Processorsteps. 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:
RemoteAtomsHandlerRun an ordered pipeline of
Processorsteps over a trajectory.Shards the input trajectories, ships each shard a per-shard input JSON (the ordered
steps+ per-stepargs) 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.extxyzfile(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.Noneor 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 shippeddriver.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]
- 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:
RemoteTrajectoryProcessorOptimize 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
Processorsubclass in the same module – itsregistration_modulethen 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 samerun.- Parameters:
name – Registry key; must match the host-side
Processor.name.run –
callable(atoms_list, args, calcpath) -> atoms_list.schema – Optional
ScriptInputsubclass declaring this step’s arg contract. The driver validates the step’s args against it at job start (viafrom_dict(...).validate()), so a bad composed payload fails fast instead of deep inside a task. This is the same schema the host-sideProcessor.build_argsfills, 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
argsthrough the registered schema (schema.from_dict(args).validate()); raisesScriptInputErroron 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_fileonly -> the YAML contents.incar_kwargsonly -> that dict, as-is (historical behaviour).both -> the YAML as a base, with
incar_kwargsoverriding on top.neither -> the built-in single-point r2SCAN defaults.
- Return type:
- 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:
RemoteAtomsHandlerRun one ASE-calculator single-point per configuration as a job array.
Calculator-agnostic: it ships
calc_config(the per-job input JSON) and runspython_script_pathon the remote. Concrete calculators are expressed as presets that fill incalc_configand the default script (seeVASPHandler,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 writesdft_<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 everyevery-th frame from the trajectories.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’senvironment[environment_key](aDeprecationWarningfires when both are set); the two are never combined.environment_key (
Optional[str]) – Key intocluster_config.environmentfor this application’s cluster setup (e.g."vasp").Noneinjects nothing – the historical behaviour.time_limit (
Optional[str]) – SLURM--timevalue (e.g."0-02:00:00") to cap each job – useful to kill hanging DFT runs.None(default) emits no--timedirective, so the job runs to the partition maximum.memory (
Optional[str]) – SLURM--memvalue (e.g."16G","2000M", or MB as a bare number) requested per job.None(default) emits no--memdirective, 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]
- 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:
SinglePointHandlerVASP single-point preset of
SinglePointHandler.Builds the VASP
calc_config(INCAR tags + launch command) and defaults to the shippedscripts/dft_singlepoint.pypayload. 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 everyevery-th frame from the trajectories.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 shippeddft_singlepoint.py.stub (
bool) – Accepted for backward compatibility; stubbing is handled byVASPEvaluator, 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– seeresolve_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:
SinglePointHandlerORCA single-point preset of
SinglePointHandler.Builds the ORCA
calc_configand defaults to the shippedscripts/orca_singlepoint.pypayload. Keeps its historical(traj_files, remote_fs, cluster_config, ...)argument order (remote_fsandcluster_configswapped relative toVASPHandler) 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 everyevery-th frame from the trajectories.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 shippedorca_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
Samplerinterface)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,GroundTruthEvaluatorSingle-point ground-truth evaluation with any ASE calculator.
Calculator-agnostic: it ships
calc_config(the per-job input JSON) and runssinglepoint_scripton the remote, which builds the calculator, computes energy + forces, and writes a labelleddft_<DB>.extxyz. Concrete calculators are presets that assemblecalc_config(seeVASPEvaluator,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-declaredenvironmentsetup for this calculator).time_limit (
Optional[str]) – SLURM--timevalue (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,updatereconstructs the array submitted by an earlier,collect_only=Falsecall (from the manifest written beside<calcdir>/dft/results, viaRemoteAtomsHandler.from_manifest) instead of allocating/submitting a new one, andget_evaluated_configsskips the (already-done) submission.evaluator_inputis not read in this mode. Use this to collect a detached evaluation run from a fresh process.reattach_max_wait (
Optional[float]) – Only used whencollect_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_configwhen one of them is baked into it (e.g. VASP’sincar_kwargs), so the new value reaches the job.- Return type:
- 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 whencollect_only– a second process reconstructing an already-submitted array from its manifest needs none of the original input, soNoneis expected there.**kwargs – Additional parameters.
- Return type:
- get_evaluated_configs()[source]
Run the evaluation and collect the labelled configurations.
- Return type:
- Returns:
Path to the
.extxyzof evaluated configurations.- Raises:
TaskError – If fewer than
required_fractionjobs succeed (or, whencollect_only, if that doesn’t happen withinreattach_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:
AseCalculatorEvaluatorVASP 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 shippeddft_singlepoint.py.incar_kwargs (
Optional[dict]) – VASP INCAR tags (optional ifincar_config_fileis 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’senvironment["vasp"](and emits a DeprecationWarning when both are set). Prefer putting the VASP module load andVASP_PP_PATHin 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,updatereconstructs the array submitted by an earlier,collect_only=Falsecall instead of allocating/submitting a new one. SeeAseCalculatorEvaluator’s docstring.reattach_max_wait (
Optional[float]) – Only used whencollect_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:
AseCalculatorEvaluatorORCA 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 shippedorca_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’senvironment["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,updatereconstructs the array submitted by an earlier,collect_only=Falsecall instead of allocating/submitting a new one. SeeAseCalculatorEvaluator’s docstring.reattach_max_wait (
Optional[float]) – Only used whencollect_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:
AseCalculatorEvaluatorCheap EMT ground-truth preset (pure ASE, no external binary).
Uses the generic
ase_singlepoint.pypayload 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 thedirectexecutor, 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 shippedase_singlepoint.py.calculator_kwargs (
Optional[dict]) – Keyword arguments forwarded toEMT(...).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,updatereconstructs the array submitted by an earlier,collect_only=Falsecall instead of allocating/submitting a new one. SeeAseCalculatorEvaluator’s docstring.reattach_max_wait (
Optional[float]) – Only used whencollect_only: how long (in seconds) to wait for the reattached job to finish before giving up.None(default) waits forever.
- 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:
_MaceArrayTrainerTrainer 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 runsconfig_file (
PathLike) – Path to MACE YAML config filefoundation_model (
PathLike) – Path to the pretrained foundation model filetraining_script (
Optional[PathLike]) – Remote payload; defaults to the shippedmace/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 generationvalidation_fraction (
float) – Fraction for train/validation splitremote_savepath (
Optional[PathLike]) – Path on remote machine for calculation filesloop_time (
float) – Interval (seconds) to poll for job completionstub (
bool) – If True, creates mock model outputs without trainingconvert_to_jax (
bool) – If True, convert each trained torch model to a mace-jax bundle in the same job and return those paths fromget_trained_model. The training (cluster) environment must then have both the torch MACE stack andmace-jax.jax_output_format (
str) – Bundle format whenconvert_to_jax–"pkl"(default; an opaque single-file pickle) or"bundle"(a directory withconfig.json+params.msgpack, the canonical inspectable format mace-jax’s loader / jaxrens consume).collect_only (
bool) – If True,updatereconstructs the array task submitted by an earlier,collect_only=Falsecall (from the manifest written beside<calcdir>/train/results) instead of allocating/submitting a new one, andget_trained_modelskips the (already-done) submission.trainer_inputis 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 whencollect_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:
_MaceArrayTrainerTrainer 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 runsconfig_file (
PathLike) – Path to MACE YAML config filetraining_script (
Optional[PathLike]) – Remote payload; defaults to the shippedmace/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 generationvalidation_fraction (
float) – Fraction for train/validation splitremote_savepath (
Optional[PathLike]) – Path on remote machine for calculation filesloop_time (
float) – Interval (seconds) to poll for job completionstub (
bool) – If True, creates mock model outputs without trainingconvert_to_jax (
bool) – If True, convert each trained torch model to a mace-jax bundle in the same job and return those paths fromget_trained_model. The training (cluster) environment must then have both the torch MACE stack andmace-jax.jax_output_format (
str) – Bundle format whenconvert_to_jax–"pkl"(default; an opaque single-file pickle) or"bundle"(a directory withconfig.json+params.msgpack, the canonical inspectable format mace-jax’s loader / jaxrens consume).collect_only (
bool) – If True,updatereconstructs the array task submitted by an earlier,collect_only=Falsecall (from the manifest written beside<calcdir>/train/results) instead of allocating/submitting a new one, andget_trained_modelskips the (already-done) submission.trainer_inputis 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 whencollect_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,ModelTrainerTrainer 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 shippedneuralil/neuralil_training.py.remote_fs (
FileSystemHandlerBase) – FileSystemHandlerBase for the machine where training runsremote_savepath (
Optional[PathLike]) – Path on remote machine for calculation filestraining_kwargs (
dict) – Explicit hyperparameter overrides (highest precedence).stub (
bool) – If True, creates mock model outputs without trainingloop_time (
float) – Interval (seconds) to poll for job completionconfig_file (
Optional[PathLike]) – Optional path to a YAML file of hyperparameters, layered on the built-in defaults (mirrorsMaceModelTrainer’sconfig_file). Overridden by anything intraining_kwargs.collect_only (
bool) – If True,updatereconstructs the task submitted by an earlier,collect_only=Falsecall (from the manifest written beside<calcdir>/training/results) instead of allocating/submitting a new one, andget_trained_modelskips the (already-done) submission.trainer_inputis 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 whencollect_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).
- apply_schedule(kwargs)[source]
Apply scheduled attributes and hyperparameters.
config_file,training_kwargsandstubre-layer the merged hyperparameters (a scheduledtraining_kwargsreplaces the explicit overrides); single hyperparameter keys then go on top.- Return type:
- class remote_handler.workflows.StagedActiveLearningHandler(stages, calchome, num_iterations=5, entry_stage=None, exit_stage=None, on_stage_complete=None)[source]
Bases:
objectGeneric, 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 ofStageobjects (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 aStageCompletedafter every stage step whose outputs were recorded (see the module docstring’s Hooks).
Use
from_actors()for a drop-in mapping of the originalActiveLearningHandlerarguments.- __init__(stages, calchome, num_iterations=5, entry_stage=None, exit_stage=None, on_stage_complete=None)[source]
- 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 aselectorstage between the sampler and the evaluator.cycle_entry_point/cycle_exit_pointaccept the legacy spellings"sampler","evaluation"and"training".For novelty-based selection, set
selector_reference_fromto a stage name (typically"evaluator"): the selector then receives that stage’s accumulated outputs from all previous iterations as areferenceand switches to novelty mode (seeQUESTSSelector).initial_selector_referenceoptionally 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_completeis forwarded to the handler unchanged.- Return type:
- class remote_handler.workflows.Stage(name, actor, combine=False, schedule=None, output_extension='extxyz', initial_input=None, extra_inputs=dict())[source]
Bases:
objectA 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 eachupdateits values are applied to the actor (set as attributes, or via the actor’sapply_schedulehook) and also passed toupdateas keyword arguments. Keys that name no actor attribute (and that the actor does not declare viaunknown_schedule_keys) only reachupdateand raise aScheduleKeyWarningat 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 (seeInputSource). Each is resolved to a list of paths and passed toupdateas a keyword argument of the same name. Keys must not collide with the stage’s schedule kwargs.
- 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:
objectA secondary input stream pulled from another stage’s outputs.
The primary input of a stage always follows the ring (its predecessor’s output). An
InputSourcedeclares 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’supdateas a keyword argument named after the dict key inStage.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).
- __init__(stage, accumulate=True, include_current=False, initial=None)
- class remote_handler.workflows.Selector[source]
Bases:
ABCA 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:
- abstractmethod get_selected_configs()[source]
Function returns the path(s) to the selected configurations for the upcoming GroundTruthEvaluator step.
- pending_manifest(calcdir)
Default
pending_manifestimplementation: reattach unsupported.Path to a manifest from a previous, interrupted attempt at this iteration – if this actor can detect one –
Noneotherwise.Used by
ActiveLearningHandler/StagedActiveLearningHandlerto 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 onremote_handler.core.tasks.DetachableTaskMixintypically overrides this with something likeself.manifest_path(calcdir / "train" / "results"), matching its ownupdate()’sresults_dirconvention – see_MaceArrayTrainerfor the pattern.This default (unsupported, always
None) keeps the hook fully backward compatible: any existing actor – including every concreteSampler, 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.
- class remote_handler.workflows.SelectorActor(selector, output_filename='selected.extxyz')[source]
Bases:
SelectorAdapt a
ConfigSelectorstrategy into a Selector actor.Turns the pure
select(configs) -> list[Atoms]interface into theupdate/get_selected_configsactor 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 asLastFrameSelectorkeep 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.
- unknown_schedule_keys(kwargs)[source]
Schedule keys may name attributes of the wrapped selector (e.g.
n_configs) or of this actor.
- 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:
- 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:
- 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:
SelectorRun 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:
updatemerges them overselector_kwargseach iteration.
- apply_schedule(kwargs)[source]
No-op: the scheduled values reach the selector through
update’s keyword arguments, not through attributes.- Return type:
- 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:
- 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:
- abstractmethod get_sampled_configs()[source]
Function returns a JsonDict object containing necessary information for upcoming GroundTruthEvaluator step.
- pending_manifest(calcdir)
Default
pending_manifestimplementation: reattach unsupported.Path to a manifest from a previous, interrupted attempt at this iteration – if this actor can detect one –
Noneotherwise.Used by
ActiveLearningHandler/StagedActiveLearningHandlerto 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 onremote_handler.core.tasks.DetachableTaskMixintypically overrides this with something likeself.manifest_path(calcdir / "train" / "results"), matching its ownupdate()’sresults_dirconvention – see_MaceArrayTrainerfor the pattern.This default (unsupported, always
None) keeps the hook fully backward compatible: any existing actor – including every concreteSampler, 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.
- 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:
- abstractmethod get_evaluated_configs()[source]
Function returns a JsonDict object containing necessary information for upcoming ModelTrainer step.
- pending_manifest(calcdir)
Default
pending_manifestimplementation: reattach unsupported.Path to a manifest from a previous, interrupted attempt at this iteration – if this actor can detect one –
Noneotherwise.Used by
ActiveLearningHandler/StagedActiveLearningHandlerto 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 onremote_handler.core.tasks.DetachableTaskMixintypically overrides this with something likeself.manifest_path(calcdir / "train" / "results"), matching its ownupdate()’sresults_dirconvention – see_MaceArrayTrainerfor the pattern.This default (unsupported, always
None) keeps the hook fully backward compatible: any existing actor – including every concreteSampler, 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.
- 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:
- abstractmethod get_trained_model()[source]
Function returns a JsonDict object containing necessary information for upcoming Sampler step
- pending_manifest(calcdir)
Default
pending_manifestimplementation: reattach unsupported.Path to a manifest from a previous, interrupted attempt at this iteration – if this actor can detect one –
Noneotherwise.Used by
ActiveLearningHandler/StagedActiveLearningHandlerto 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 onremote_handler.core.tasks.DetachableTaskMixintypically overrides this with something likeself.manifest_path(calcdir / "train" / "results"), matching its ownupdate()’sresults_dirconvention – see_MaceArrayTrainerfor the pattern.This default (unsupported, always
None) keeps the hook fully backward compatible: any existing actor – including every concreteSampler, 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.
- class remote_handler.workflows.active_learning_base.Selector[source]
Bases:
ABCA 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:
- abstractmethod get_selected_configs()[source]
Function returns the path(s) to the selected configurations for the upcoming GroundTruthEvaluator step.
- pending_manifest(calcdir)
Default
pending_manifestimplementation: reattach unsupported.Path to a manifest from a previous, interrupted attempt at this iteration – if this actor can detect one –
Noneotherwise.Used by
ActiveLearningHandler/StagedActiveLearningHandlerto 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 onremote_handler.core.tasks.DetachableTaskMixintypically overrides this with something likeself.manifest_path(calcdir / "train" / "results"), matching its ownupdate()’sresults_dirconvention – see_MaceArrayTrainerfor the pattern.This default (unsupported, always
None) keeps the hook fully backward compatible: any existing actor – including every concreteSampler, 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.
- 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.
- class remote_handler.workflows.active_learning_base.Schedule(num_iterations)[source]
Bases:
ABCUtility 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.
- 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:
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:
- 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:
- 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:
- remote_handler.workflows.active_learning_base.validate_schedule_kwargs(actor, kwargs)[source]
Warn about schedule keys that name nothing
actorcan take.By default a key is known if it names an existing attribute of
actor– that is whatapply_schedule_kwargs()sets. An actor whose scheduled values live elsewhere (e.g. in a wrapped strategy object) definesunknown_schedule_keys(kwargs) -> list[str]instead.Unknown keys are not an error: they still reach
updateas 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 aScheduleKeyWarning(make it an error withwarnings.simplefilter("error", ScheduleKeyWarning)). The handlers call this once, at construction.- Return type:
- 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 toupdate’s keyword arguments.- Return type:
- remote_handler.workflows.active_learning_base.apply_schedule_kwargs(actor, kwargs)[source]
Apply one iteration’s schedule values to
actorbeforeupdate.Defaults to
set_schedule_attributes(). An actor that derives state from a scheduled parameter once (so a plainsetattrwould not reach the job) defines anapply_schedule(kwargs)method, which is called instead.The handlers still forward the same values to
updateas keyword arguments, so actors that consume them there keep working.- Return type:
- 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:
ABCImplementation 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 viaStagedActiveLearningHandler.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 samplerevaluator_schedule (
Optional[Schedule]) – A Schedule instance encoding a schedule for the evaluatortrainer_schedule (
Optional[Schedule]) – A Schedule instance encoding a schedule for the trainercombine_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
- 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:
- 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:
- 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:
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.
- class remote_handler.workflows.staged_active_learning.SelectorActor(selector, output_filename='selected.extxyz')[source]
Bases:
SelectorAdapt a
ConfigSelectorstrategy into a Selector actor.Turns the pure
select(configs) -> list[Atoms]interface into theupdate/get_selected_configsactor 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 asLastFrameSelectorkeep 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.
- unknown_schedule_keys(kwargs)[source]
Schedule keys may name attributes of the wrapped selector (e.g.
n_configs) or of this actor.
- 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:
- 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:
- 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:
SelectorRun 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:
updatemerges them overselector_kwargseach iteration.
- apply_schedule(kwargs)[source]
No-op: the scheduled values reach the selector through
update’s keyword arguments, not through attributes.- Return type:
- 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:
- class remote_handler.workflows.staged_active_learning.InputSource(stage, accumulate=True, include_current=False, initial=None)[source]
Bases:
objectA secondary input stream pulled from another stage’s outputs.
The primary input of a stage always follows the ring (its predecessor’s output). An
InputSourcedeclares 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’supdateas a keyword argument named after the dict key inStage.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).
- __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:
objectA 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 eachupdateits values are applied to the actor (set as attributes, or via the actor’sapply_schedulehook) and also passed toupdateas keyword arguments. Keys that name no actor attribute (and that the actor does not declare viaunknown_schedule_keys) only reachupdateand raise aScheduleKeyWarningat 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 (seeInputSource). Each is resolved to a list of paths and passed toupdateas a keyword argument of the same name. Keys must not collide with the stage’s schedule kwargs.
- 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:
objectEvent passed to
on_stage_completehooks.- outputs
The stage’s recorded outputs for this iteration, as absolute paths (the copies under
<stage>_output/).
- __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:
objectGeneric, 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 ofStageobjects (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 aStageCompletedafter every stage step whose outputs were recorded (see the module docstring’s Hooks).
Use
from_actors()for a drop-in mapping of the originalActiveLearningHandlerarguments.- __init__(stages, calchome, num_iterations=5, entry_stage=None, exit_stage=None, on_stage_complete=None)[source]
- 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 aselectorstage between the sampler and the evaluator.cycle_entry_point/cycle_exit_pointaccept the legacy spellings"sampler","evaluation"and"training".For novelty-based selection, set
selector_reference_fromto a stage name (typically"evaluator"): the selector then receives that stage’s accumulated outputs from all previous iterations as areferenceand switches to novelty mode (seeQUESTSSelector).initial_selector_referenceoptionally 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_completeis forwarded to the handler unchanged.- Return type:
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
selectmethod accepts either: list[Atoms]— a flat list of configurationslist[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:
ABCAbstract 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 flatlist[Atoms]or groupedlist[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:
ConfigSelectorSelect 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 flatlist[Atoms]or groupedlist[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:
ConfigSelectorSelect configurations at evenly spaced (strided) intervals.
Picks
n_configsevenly 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.
- 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 flatlist[Atoms]or groupedlist[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:
StrideSelectorDeprecated 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.
- class remote_handler.workflows.selectors.RandomSelector(n_configs)[source]
Bases:
ConfigSelectorSelect configurations at random with an equal probability.
When given grouped input (
list[list[Atoms]]), returns a random sample ofn_configsfrom each inner list (e.g., one random frame from each trajectory/replica).When given a flat list, returns a random sample of
n_configsfrom it.- 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 flatlist[Atoms]or groupedlist[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:
ConfigSelectorSelect 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_configsframes 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 whenthresholdis set (pure threshold mode).energy_key (
str|None) – Key inatoms.infofor per-structure energy uncertainty. Set to None to ignore energy uncertainty.forces_key (
str|None) – Key inatoms.arraysfor 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 withn_configsto 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 flatlist[Atoms]or groupedlist[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:
ConfigSelectorSelect 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/Å).
- 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 flatlist[Atoms]or groupedlist[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:
ConfigSelectorSelect 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:
- 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 flatlist[Atoms]or groupedlist[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:
ConfigSelectorSelect 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
DatasetCompressorto select a structurally diverse subset from the candidates. Themethodparameter controls the selection strategy (MSC, FPS, etc.).Novelty mode (with reference): Uses
delta_entropyto score each candidate by how novel its atomic environments are relative to a reference dataset (e.g., existing training data). Selects then_configscandidates with highest mean novelty score.Requires the
questspackage (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 viaselect(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 flatlist[Atoms]or groupedlist[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:
ConfigSelectorChain 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.
- 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 flatlist[Atoms]or groupedlist[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,GroundTruthEvaluatorSingle-point ground-truth evaluation with any ASE calculator.
Calculator-agnostic: it ships
calc_config(the per-job input JSON) and runssinglepoint_scripton the remote, which builds the calculator, computes energy + forces, and writes a labelleddft_<DB>.extxyz. Concrete calculators are presets that assemblecalc_config(seeVASPEvaluator,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-declaredenvironmentsetup for this calculator).time_limit (
Optional[str]) – SLURM--timevalue (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,updatereconstructs the array submitted by an earlier,collect_only=Falsecall (from the manifest written beside<calcdir>/dft/results, viaRemoteAtomsHandler.from_manifest) instead of allocating/submitting a new one, andget_evaluated_configsskips the (already-done) submission.evaluator_inputis not read in this mode. Use this to collect a detached evaluation run from a fresh process.reattach_max_wait (
Optional[float]) – Only used whencollect_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_configwhen one of them is baked into it (e.g. VASP’sincar_kwargs), so the new value reaches the job.- Return type:
- 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 whencollect_only– a second process reconstructing an already-submitted array from its manifest needs none of the original input, soNoneis expected there.**kwargs – Additional parameters.
- Return type:
- get_evaluated_configs()[source]
Run the evaluation and collect the labelled configurations.
- Return type:
- Returns:
Path to the
.extxyzof evaluated configurations.- Raises:
TaskError – If fewer than
required_fractionjobs succeed (or, whencollect_only, if that doesn’t happen withinreattach_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:
AseCalculatorEvaluatorVASP 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 shippeddft_singlepoint.py.incar_kwargs (
Optional[dict]) – VASP INCAR tags (optional ifincar_config_fileis 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’senvironment["vasp"](and emits a DeprecationWarning when both are set). Prefer putting the VASP module load andVASP_PP_PATHin 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,updatereconstructs the array submitted by an earlier,collect_only=Falsecall instead of allocating/submitting a new one. SeeAseCalculatorEvaluator’s docstring.reattach_max_wait (
Optional[float]) – Only used whencollect_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:
AseCalculatorEvaluatorORCA 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 shippedorca_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’senvironment["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,updatereconstructs the array submitted by an earlier,collect_only=Falsecall instead of allocating/submitting a new one. SeeAseCalculatorEvaluator’s docstring.reattach_max_wait (
Optional[float]) – Only used whencollect_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:
AseCalculatorEvaluatorCheap EMT ground-truth preset (pure ASE, no external binary).
Uses the generic
ase_singlepoint.pypayload 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 thedirectexecutor, 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 shippedase_singlepoint.py.calculator_kwargs (
Optional[dict]) – Keyword arguments forwarded toEMT(...).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,updatereconstructs the array submitted by an earlier,collect_only=Falsecall instead of allocating/submitting a new one. SeeAseCalculatorEvaluator’s docstring.reattach_max_wait (
Optional[float]) – Only used whencollect_only: how long (in seconds) to wait for the reattached job to finish before giving up.None(default) waits forever.
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:
_MaceArrayTrainerTrainer 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 runsconfig_file (
PathLike) – Path to MACE YAML config filetraining_script (
Optional[PathLike]) – Remote payload; defaults to the shippedmace/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 generationvalidation_fraction (
float) – Fraction for train/validation splitremote_savepath (
Optional[PathLike]) – Path on remote machine for calculation filesloop_time (
float) – Interval (seconds) to poll for job completionstub (
bool) – If True, creates mock model outputs without trainingconvert_to_jax (
bool) – If True, convert each trained torch model to a mace-jax bundle in the same job and return those paths fromget_trained_model. The training (cluster) environment must then have both the torch MACE stack andmace-jax.jax_output_format (
str) – Bundle format whenconvert_to_jax–"pkl"(default; an opaque single-file pickle) or"bundle"(a directory withconfig.json+params.msgpack, the canonical inspectable format mace-jax’s loader / jaxrens consume).collect_only (
bool) – If True,updatereconstructs the array task submitted by an earlier,collect_only=Falsecall (from the manifest written beside<calcdir>/train/results) instead of allocating/submitting a new one, andget_trained_modelskips the (already-done) submission.trainer_inputis 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 whencollect_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:
_MaceArrayTrainerTrainer 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 runsconfig_file (
PathLike) – Path to MACE YAML config filefoundation_model (
PathLike) – Path to the pretrained foundation model filetraining_script (
Optional[PathLike]) – Remote payload; defaults to the shippedmace/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 generationvalidation_fraction (
float) – Fraction for train/validation splitremote_savepath (
Optional[PathLike]) – Path on remote machine for calculation filesloop_time (
float) – Interval (seconds) to poll for job completionstub (
bool) – If True, creates mock model outputs without trainingconvert_to_jax (
bool) – If True, convert each trained torch model to a mace-jax bundle in the same job and return those paths fromget_trained_model. The training (cluster) environment must then have both the torch MACE stack andmace-jax.jax_output_format (
str) – Bundle format whenconvert_to_jax–"pkl"(default; an opaque single-file pickle) or"bundle"(a directory withconfig.json+params.msgpack, the canonical inspectable format mace-jax’s loader / jaxrens consume).collect_only (
bool) – If True,updatereconstructs the array task submitted by an earlier,collect_only=Falsecall (from the manifest written beside<calcdir>/train/results) instead of allocating/submitting a new one, andget_trained_modelskips the (already-done) submission.trainer_inputis 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 whencollect_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:
_AceArrayTrainerTrainer 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 (thepython-ace/pyacepackage) is typically installed via conda-forge or built from source, since it ships compiled C++ extensions – see theaceoptional-dependency extra.- Parameters:
remote_fs (
FileSystemHandlerBase) – FileSystemHandlerBase for the machine where training runsconfig_file (
PathLike) – Path to a YAML config with pacemaker’spotential/fit/backendsections (nodata/seedneeded there – those are injected per job)training_script (
Optional[PathLike]) – Remote payload; defaults to the shippedace/ace_training.py.remote_train_runner (
Optional[PathLike]) – Path to thepacemakerexecutable 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 generationvalidation_fraction (
float) – Fraction of data pacemaker splits off as its own internal test setkeep_best (
Optional[int]) – If given, hand on only this many of thenum_modelsmembers: those with the lowest final test loss (pacemaker’stest_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 filesloop_time (
float) – Interval (seconds) to poll for job completionstub (
bool) – If True, creates mock model outputs without trainingcollect_only (
bool) – If True,updatereconstructs the array task submitted by an earlier,collect_only=Falsecall (from the manifest written beside<calcdir>/train/results) instead of allocating/submitting a new one, andget_trained_modelskips the (already-done) submission.trainer_inputis 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 whencollect_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:
_GraceArrayTrainerTrainer 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 thegraceoptional-dependency extra (thetensorpotentialpackage).- Parameters:
remote_fs (
FileSystemHandlerBase) – FileSystemHandlerBase for the machine where training runsconfig_file (
PathLike) – Path to a YAML config with gracemaker’scutoff/potential/fitsections (nodata/seedneeded there – those are injected per job)training_script (
Optional[PathLike]) – Remote payload; defaults to the shippedgrace/grace_training.py.remote_train_runner (
Optional[PathLike]) – Path to thegracemakerexecutable 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 generationvalidation_fraction (
float) – Fraction of data gracemaker splits off as its own internal test setremote_savepath (
Optional[PathLike]) – Path on remote machine for calculation filesloop_time (
float) – Interval (seconds) to poll for job completionstub (
bool) – If True, creates mock model outputs without trainingcollect_only (
bool) – If True,updatereconstructs the array task submitted by an earlier,collect_only=Falsecall (from the manifest written beside<calcdir>/train/results) instead of allocating/submitting a new one, andget_trained_modelskips the (already-done) submission.trainer_inputis 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 whencollect_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,ModelTrainerTrainer 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 shippedneuralil/neuralil_training.py.remote_fs (
FileSystemHandlerBase) – FileSystemHandlerBase for the machine where training runsremote_savepath (
Optional[PathLike]) – Path on remote machine for calculation filestraining_kwargs (
dict) – Explicit hyperparameter overrides (highest precedence).stub (
bool) – If True, creates mock model outputs without trainingloop_time (
float) – Interval (seconds) to poll for job completionconfig_file (
Optional[PathLike]) – Optional path to a YAML file of hyperparameters, layered on the built-in defaults (mirrorsMaceModelTrainer’sconfig_file). Overridden by anything intraining_kwargs.collect_only (
bool) – If True,updatereconstructs the task submitted by an earlier,collect_only=Falsecall (from the manifest written beside<calcdir>/training/results) instead of allocating/submitting a new one, andget_trained_modelskips the (already-done) submission.trainer_inputis 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 whencollect_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).
- apply_schedule(kwargs)[source]
Apply scheduled attributes and hyperparameters.
config_file,training_kwargsandstubre-layer the merged hyperparameters (a scheduledtraining_kwargsreplaces the explicit overrides); single hyperparameter keys then go on top.- Return type: