Skip to content

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

9 Commits

Folders and files

Repository files navigation

SlurmBridge

SlurmBridge lets local Python programs create and call persistent Python objects inside Slurm compute jobs. It handles code synchronization, job submission, SSH port forwarding, and asynchronous HTTP JSON RPC.

The local application stays small while CPU-, GPU-, and memory-intensive code runs on the allocated compute node.

How it works

  1. SlurmBackend.connect() opens SSH and prepares the remote workspace.
  2. SlurmBackend.sync() synchronizes the framework and the user's Python package into the selected remote directory.
  3. SlurmBackend.acquire_runtime() uploads a user-provided Slurm configuration script.
  4. SlurmBridge appends the HTTP worker command to the remote copy of the script and submits it with sbatch.
  5. The worker imports classes marked with @remote and publishes its address.
  6. SlurmBridge opens an SSH tunnel from the local machine to the compute node.
  7. Local proxies send asynchronous HTTP requests to objects stored by the worker.
  8. A later process can connect a backend and call attach_runtime(job_id) to rebuild the SSH tunnel without synchronizing code or submitting another job.

The remote workspace has this layout:

<remote-dir>/
├── framework/
│   └── slurmbridge/
├── packages/
│   └── remote/
└── jobs/
    └── Slurm job output files

Job lookup records always live at the fixed default location, including when a custom remote_dir is used:

~/.slurmBridge/jobs/
└── <job-id>.json

Requirements

Local requirements:

  • Python 3.10 or newer
  • OpenSSH
  • rsync
  • access to a Slurm cluster through a login host

The Python environment activated by the Slurm script must contain aiohttp. User code must also install its own remote dependencies, such as PyTorch, vLLM, or Transformers.

Installation

For local development:

git clone https://github.com/<username>/SlurmBridge.git
cd SlurmBridge
python -m pip install -e .

An editable installation imports directly from the checked-out source tree, so source changes become available without reinstalling the package.

To install a fixed local copy:

python -m pip install .

Included examples

Each directory under examples/ is a self-contained example. The first example demonstrates a remote Counter:

examples/
└── counter/
    ├── main.py
    ├── job.sh
    └── remote/
        ├── __init__.py
        └── counter.py

Edit examples/counter/job.sh for the modules and virtual environment available on your cluster. Then run the example from its own directory. The remote project directory defaults to .slurmBridge:

cd examples/counter
python main.py username@login.cluster.example

Running from this directory makes ./remote and ./job.sh resolve to the files belonging to this example.

Two examples demonstrate reconnection:

  • examples/reconnect_stateless catches a simulated local failure, prints the Job ID and reconnect command, then reconnects without requesting new Slurm resources. It uses anonymous objects and does not preserve object state.
  • examples/reconnect_stateful gives a Counter a persistent ID, disconnects, and demonstrates that reconnecting with the same persistent ID preserves its remote in-memory state.
  • examples/counter_runtimes concurrently acquires two Runtimes, deploys one persistent Counter to each, disconnects after a simulated local crash, and attaches both Job IDs from a new backend.

Run each example from its own directory and follow the commands in that directory's README.

User project layout

SlurmBridge is installed as a library. Remote application code belongs to the user's own project:

my-project/
├── main.py
├── job.sh
└── remote/
    ├── __init__.py
    └── counter.py

The remote/ directory must be a Python package and therefore must contain __init__.py.

Define a remote class

remote/counter.py:

from slurmbridge import remote


@remote
class Counter:
    def __init__(self, initial: int = 0) -> None:
        self._value = initial

    def increment(self, amount: int = 1) -> int:
        self._value += amount
        return self._value

    def value(self) -> int:
        return self._value

All public methods are callable through RPC. Methods whose names begin with an underscore are not exposed.

Only classes created directly from the local application need @remote. Helper classes instantiated exclusively by remote code can remain ordinary Python classes.

Configure the Slurm job

job.sh contains resource requests and environment setup only:

Important: The submitted script runs on the cluster and must configure the complete remote runtime environment itself. Load the modules required by your cluster and, in particular, use source to activate your own virtual or Conda environment before the script reaches the worker command. The local Python environment is not automatically available on the compute node.

Prepare that remote environment once on the cluster. It must contain aiohttp, plus every dependency imported by your remote code, such as PyTorch, vLLM, Transformers, CUDA-specific packages, or private project libraries. For example:

# Run once on the cluster login node.
python -m venv ~/slurmbridge-env
source ~/slurmbridge-env/bin/activate
python -m pip install 'aiohttp>=3.9,<4' your-remote-dependencies

Then activate the same environment in every submitted job.sh:

#!/bin/bash
#SBATCH --job-name=slurmbridge-example
#SBATCH --time=00:20:00
#SBATCH --cpus-per-task=2
#SBATCH --mem=4G

set -euo pipefail

module --force purge
module load python/3.11

source ~/slurmbridge-env/bin/activate

Replace the module names and environment path above with values appropriate for your cluster. If the environment is not activated, the worker may start with the system Python and fail with missing-package or incompatible-CUDA errors.

Do not start the worker in this script. SlurmBridge modifies only the uploaded copy and appends:

export PYTHONPATH="<remote-dir>/framework:<remote-dir>/packages:${PYTHONPATH:-}"
python -m slurmbridge.runtime.worker \
  --package <package-name> \
  --remote-dir <absolute-remote-dir>

The local script is never modified.

Run the same backend locally

LocalBackend has the same core API as SlurmBackend. It runs the provided script and worker in a separate process, so remote classes still create constructor descriptions in the client and real instances only in the worker:

from slurmbridge import LocalBackend

backend = await LocalBackend.connect()
await backend.sync("./remote")
runtime = await backend.acquire_runtime("./local-job.sh")
print(runtime.runtime_id)  # PID of the local worker process

The local script is copied to a temporary file and receives the same PYTHONPATH and worker launcher pattern as a Slurm script. LocalBackend uses the Python interpreter that started the client, binds the worker only to 127.0.0.1, and uses the worker PID as its job ID. To leave it running and attach from a later client process:

job_id = runtime.runtime_id
await backend.disconnect()

backend = await LocalBackend.connect()
runtime = await backend.attach_runtime(job_id)

Local sync() validates and directly references the original package directory; it does not copy user code. Local Runtime lookup records are stored under ~/.slurmBridge/local/runtimes/ so a later process can attach by worker PID. Both backends provide connect, sync, acquire_runtime, attach_runtime, release, disconnect, and close.

Run the application

main.py:

import argparse
import asyncio

from remote.counter import Counter
from slurmbridge import SlurmBackend


async def main(target: str) -> None:
    remote = await SlurmBackend.connect(target=target)
    await remote.sync("./remote")

    try:
        runtime = await remote.acquire_runtime("./job.sh")
        counter = await Counter(10).to(runtime)

        print(f"[_Read Counter_]: {await counter.value()}")
        print(f"[_Increment Counter_]: {await counter.increment(5)}")
    finally:
        await remote.close()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("target", help="Slurm login target, such as user@cluster")
    arguments = parser.parse_args()
    asyncio.run(main(arguments.target))

Counter(10) creates a local constructor description. The awaited .to(runtime) call immediately creates the real Counter on the compute node and returns a local RemoteObject proxy.

Before sending a method RPC, the proxy uses the locally registered @remote class to verify that the method exists and that its positional and keyword arguments match the Python signature. Invalid calls raise locally without executing the method body or contacting the worker.

Give a remote object a persistent ID when its in-memory state must survive a local disconnect and reconnect:

model = await Model(...).to(runtime, "main-model")

After reconnecting to the same Slurm Job ID, using the same persistent ID returns the existing remote object without running its constructor again:

model = await Model(...).to(runtime, "main-model")

Slurm Job IDs and persistent IDs have different roles: the Job ID identifies the remote worker, while the persistent ID identifies one object inside that worker. When a reconnect is established, the worker releases every anonymous object created with .to(runtime) and preserves objects created with .to(runtime, id).

SlurmBridge records the class and JSON constructor arguments used for each persistent object. Reusing an ID with the same class and arguments recovers the existing object. If the class or arguments differ, SlurmBridge constructs a replacement, installs it under the same ID, and emits a local RuntimeWarning. If replacement construction fails, the existing object remains available.

Persistent IDs are user-managed. Do not concurrently create or replace the same persistent ID. Anonymous objects use independently generated UUIDs.

Disconnect and reconnect

Creating a Runtime requires an explicit sync() first. The remote project directory defaults to .slurmBridge, but callers may override it with remote_dir. Each acquire_runtime() call submits an independent Slurm job:

remote = await SlurmBackend.connect(target=target)
await remote.sync("./remote")
runtime = await remote.acquire_runtime("./job.sh")
print(runtime.runtime_id)

The worker does not automatically stop when RPC calls are idle. Disconnecting closes only local SSH resources and does not stop the Slurm job or its remote Python objects:

await remote.disconnect()

In a later local process, connect to the login node and attach using the saved Job ID. Attaching does not require sync():

remote = await SlurmBackend.connect(target)
runtime = await remote.attach_runtime("123456")

attach_runtime() reads ~/.slurmBridge/jobs/<job-id>.json, verifies the published connection information, and rebuilds the local tunnel. It does not synchronize code or submit another job. If a selected local forwarding port is claimed before SSH binds it, SlurmBridge selects a new port and retries the tunnel setup up to five times.

After the worker starts, it writes its hostname, port, Job ID, remote directory, package name, and RPC token to ~/.slurmBridge/jobs/<job-id>.json. The local process reads that record through SSH and exposes the Job ID as runtime.runtime_id.

This reuses the existing worker and rebuilds only the local SSH tunnel. It does not resubmit the job or recreate local proxies for objects already held by the worker. A local process crash also leaves the batch job running until the Slurm time limit, an explicit shutdown, a cancellation, or a remote failure ends it.

Concurrent requests

Local calls are asynchronous. Use asyncio.gather() to issue requests concurrently:

results = await asyncio.gather(
    model.generate("first prompt"),
    model.generate("second prompt"),
    model.generate("third prompt"),
)

The aiohttp worker accepts concurrent requests. Async remote methods are awaited directly, while synchronous methods run through the server's thread pool so that they do not block the HTTP event loop.

Methods on the same remote object may run concurrently. User-defined mutable objects must provide their own locking when concurrent mutation is unsafe.

Serialization

Constructor arguments, method arguments, and return values must be JSON serializable. Convert unsupported values or save them remotely and return a path:

def run(self) -> dict[str, str]:
    output_path = self.save_result()
    return {"output_path": str(output_path)}

Large tensors, model instances, open files, and arbitrary Python objects cannot be returned directly.

Timeouts

Use _rpc_timeout for long-running calls:

result = await application.run(
    epochs=10,
    _rpc_timeout=7200,
)

An HTTP timeout does not automatically cancel work already running on the compute node. Long jobs should save checkpoints and results to persistent cluster storage.

Cleanup

Anonymous proxies make a best-effort destroy request when they are garbage collected. Delivery is not guaranteed if the event loop has stopped or the connection is unavailable. Reconnecting discards anonymous objects still held by the worker; persistent objects remain until replacement or worker shutdown.

Gracefully stop all workers and close the shared SSH connection:

await remote.close()

SlurmBackend.close() first requests an HTTP shutdown so each worker can release objects and let the Slurm script finish normally. If graceful shutdown fails, SlurmBridge falls back to scancel.

Close only local tunnels and keep remote jobs running:

await remote.disconnect()

To release one runtime while keeping other jobs managed by the same remote, call await remote.release(runtime).

Development

Install the package in editable mode and run the test suite:

python -m pip install -e .
python -m unittest discover -s tests -v

Security notes

  • Do not store access tokens, passwords, or SSH private keys in job scripts.
  • SlurmBridge binds the worker on the compute node and reaches it through an SSH tunnel; it does not expose the local tunnel on a public interface.
  • Each worker generates a random RPC token. SlurmBridge stores it in ~/.slurmBridge/jobs/<job-id>.json, reads it automatically over SSH during initial connection and reconnect, and sends it as a Bearer token with every RPC request. Users do not need to save or pass this token themselves.
  • Job information files are mode 600. RPC tokens are not printed to local logs or Slurm output.
  • RPC payloads use JSON. Pickle is not used.
  • Only public Python method names are exposed by the worker.

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages