From 904be00ce14646b64d0fa90900898746a685e31b Mon Sep 17 00:00:00 2001 From: Jan Janssen Date: Thu, 19 Nov 2026 10:39:24 +0100 Subject: [PATCH] Execute the SLURM examples of the documentation notebooks in CI The SLURM examples in notebooks/2-hpc-cluster.ipynb and notebooks/3-hpc-job.ipynb were markdown code blocks which were never executed. They are now code cells which are executed in the new notebooks_slurm job on the single node SLURM test cluster of koesterlab/setup-slurm-action, while the flux examples continue to be executed in the notebooks job. - .ci_support/run_notebooks.py selects the code cells per job based on the cell tags "slurm" / "flux" (untagged cells run in both) and executes notebooks with the notebook metadata "executorlib_ci": {"allocation": true} inside "salloc -n 2". - notebooks_slurm also executes notebooks/story-*.ipynb if they exist. - Fix the submission template: pysqa provides dependency_list, not dependency, and the partition is only set when "partition" is defined in the resource_dict. - Add executable examples for SLURM dependencies and the SlurmJobExecutor with MPI. Co-Authored-By: Claude Opus 5.5 --- .ci_support/run_notebooks.py | 112 +++++++++++++++++++++++++++++++++ .github/workflows/pipeline.yml | 57 +++++++++++++++-- notebooks/2-hpc-cluster.ipynb | 2 +- notebooks/3-hpc-job.ipynb | 71 +++++++++++++++++++-- 4 files changed, 231 insertions(+), 11 deletions(-) create mode 100644 .ci_support/run_notebooks.py diff --git a/.ci_support/run_notebooks.py b/.ci_support/run_notebooks.py new file mode 100644 index 00000000..513b8e18 --- /dev/null +++ b/.ci_support/run_notebooks.py @@ -0,0 +1,112 @@ +""" +Execute the documentation notebooks with papermill for a given job scheduler. + +The documentation notebooks demonstrate executorlib for both SLURM and flux, but each CI job only provides one of the +two job schedulers. To keep the rendered documentation free of any CI plumbing, the selection is based on metadata +which is not visible in the rendered notebooks: + +Cell tags (cell metadata "tags"): + "slurm" - the code cell is only executed in the SLURM CI job (notebooks_slurm). + "flux" - the code cell is only executed in the flux CI job (notebooks). + no tag - the code cell is executed in both jobs, e.g. function definitions or cleaning the cache. + +Notebook metadata (top-level notebook metadata, only evaluated for --scheduler slurm): + "executorlib_ci": {"allocation": true} + The notebook uses the SlurmJobExecutor (srun) and is executed inside a SLURM allocation, which is created with + "salloc -n ". Notebooks without this flag are executed on the login node, i.e. directly on the runner, + which is the setup for the SlurmClusterExecutor (sbatch). + "executorlib_ci": {"allocation": true, "cores": 2} + Number of cores requested for the allocation, defaults to 2. The single node test cluster only provides 2 CPU + cores, so the allocation occupies the whole cluster: a notebook executed inside an allocation must not submit + jobs with sbatch (SlurmClusterExecutor), as these jobs would wait for the allocation to finish. Notebooks which + combine both, like a SlurmJobExecutor nested in a function submitted via the SlurmClusterExecutor, are executed + on the login node. + +For each input notebook the cells which do not match the selected scheduler are removed, the filtered notebook is +written to a temporary directory and executed with papermill in the directory of the original notebook. The executed +notebook is stored next to the original notebook as -out.ipynb. + +Usage: + python .ci_support/run_notebooks.py --scheduler slurm notebooks/2-hpc-cluster.ipynb notebooks/story-*.ipynb + flux start python .ci_support/run_notebooks.py --scheduler flux notebooks/2-hpc-cluster.ipynb +""" + +import argparse +import os +import subprocess +import sys +import tempfile + +import nbformat + +SCHEDULERS = ("flux", "slurm") + + +def filter_notebook(nb: nbformat.NotebookNode, scheduler: str) -> nbformat.NotebookNode: + """Remove the code cells which are tagged for a different job scheduler.""" + other_tags = {s for s in SCHEDULERS if s != scheduler} + nb.cells = [ + cell + for cell in nb.cells + if cell.cell_type != "code" + or not other_tags.intersection(cell.get("metadata", {}).get("tags", [])) + ] + return nb + + +def get_command( + nb: nbformat.NotebookNode, + scheduler: str, + input_path: str, + output_path: str, + cwd: str, +) -> list[str]: + """Construct the papermill command, wrapped in a SLURM allocation if the notebook requests it.""" + command = ["papermill", input_path, output_path, "-k", "python3", "--cwd", cwd] + ci_config = nb.metadata.get("executorlib_ci", {}) + if scheduler == "slurm" and ci_config.get("allocation", False): + command = ["salloc", "-n", str(ci_config.get("cores", 2))] + command + return command + + +def run_notebook(path: str, scheduler: str, tmp_dir: str) -> bool: + nb = filter_notebook(nb=nbformat.read(path, as_version=4), scheduler=scheduler) + name = os.path.splitext(os.path.basename(path))[0] + input_path = os.path.join(tmp_dir, name + "-" + scheduler + ".ipynb") + output_path = os.path.join( + os.path.dirname(os.path.abspath(path)), name + "-out.ipynb" + ) + nbformat.write(nb, input_path) + command = get_command( + nb=nb, + scheduler=scheduler, + input_path=input_path, + output_path=output_path, + cwd=os.path.dirname(os.path.abspath(path)), + ) + print("Execute:", " ".join(command), flush=True) + return subprocess.run(command, check=False).returncode == 0 + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--scheduler", choices=SCHEDULERS, required=True) + parser.add_argument("notebooks", nargs="*") + args = parser.parse_args() + if len(args.notebooks) == 0: + print("No notebooks to execute.") + return 0 + failed = [] + with tempfile.TemporaryDirectory() as tmp_dir: + # skip the output of previous executions which is matched by glob patterns like notebooks/story-*.ipynb + for path in [p for p in args.notebooks if not p.endswith("-out.ipynb")]: + if not run_notebook(path=path, scheduler=args.scheduler, tmp_dir=tmp_dir): + failed.append(path) + if len(failed) > 0: + print("Failed notebooks:", ", ".join(failed)) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index 637672f9..e7165697 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -176,10 +176,59 @@ jobs: timeout-minutes: 5 run: | papermill notebooks/1-single-node.ipynb notebooks/1-single-node-out.ipynb -k python3 - flux start papermill notebooks/2-hpc-cluster.ipynb notebooks/2-hpc-cluster-out.ipynb -k python3 - flux start papermill notebooks/3-hpc-job.ipynb notebooks/3-hpc-job-out.ipynb -k python3 + flux start python .ci_support/run_notebooks.py --scheduler flux notebooks/2-hpc-cluster.ipynb + flux start python .ci_support/run_notebooks.py --scheduler flux notebooks/3-hpc-job.ipynb papermill notebooks/5-developer.ipynb notebooks/5-developer-out.ipynb -k python3 + # Execute the SLURM examples of the documentation notebooks on a single node SLURM test cluster (2 CPU cores). + # The notebooks are executed with .ci_support/run_notebooks.py, which selects the cells based on cell tags: + # - code cells tagged "slurm" are only executed in this job, code cells tagged "flux" only in the notebooks job, + # code cells without these tags are executed in both jobs. + # By default a notebook is executed on the login node (the runner itself), which is the setup for the + # SlurmClusterExecutor (sbatch). Notebooks using the SlurmJobExecutor (srun) declare in their notebook metadata + # "executorlib_ci": {"allocation": true} + # and are executed inside a SLURM allocation "salloc -n 2 papermill ...". As the allocation occupies all cores of the + # test cluster, these notebooks must not submit jobs with sbatch (SlurmClusterExecutor). The user story notebooks + # notebooks/story-*.ipynb follow the same convention and are executed if they exist. + notebooks_slurm: + needs: [black] + runs-on: ubuntu-24.04 + services: + mysql: + image: mysql:8.0 + env: + MYSQL_ROOT_PASSWORD: root + ports: + - "8888:3306" + options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3 + steps: + - uses: actions/checkout@v7 + - uses: koesterlab/setup-slurm-action@v1 + timeout-minutes: 10 + - name: ubnuntu install + run: sudo apt install -y mpich + - name: Merge Notebook environment + run: | + cp .ci_support/environment-mpich.yml environment.yml + tail --lines=+4 .ci_support/environment-notebooks.yml >> environment.yml + - uses: conda-incubator/setup-miniconda@v4 + with: + python-version: '3.14' + miniforge-version: latest + channels: conda-forge + conda-remove-defaults: "true" + environment-file: environment.yml + - name: Install + shell: bash -l {0} + run: pip install . --no-deps --no-build-isolation + - name: Notebooks + shell: bash -l {0} + timeout-minutes: 20 + run: | + sinfo -o "%n %e %m %a %c %C" + shopt -s nullglob + python .ci_support/run_notebooks.py --scheduler slurm notebooks/2-hpc-cluster.ipynb notebooks/3-hpc-job.ipynb notebooks/story-*.ipynb + notebooks_integration: needs: [black] runs-on: ubuntu-latest @@ -445,7 +494,7 @@ jobs: OMPI_MCA_btl_vader_single_copy_mechanism: 'none' autobot: - needs: [unittest_old, unittest_win, unittest_openmpi, unittest_mpich, unittest_flux_openmpi, unittest_flux_mpich, notebooks, benchmark, minimal, pip_check, mypy] + needs: [unittest_old, unittest_win, unittest_openmpi, unittest_mpich, unittest_flux_openmpi, unittest_flux_mpich, notebooks, notebooks_slurm, benchmark, minimal, pip_check, mypy] permissions: contents: write pull-requests: write @@ -459,7 +508,7 @@ jobs: GH_TOKEN: ${{secrets.GITHUB_TOKEN}} uml: - needs: [uv_check, unittest_slurm_mpich, unittest_old, unittest_win, unittest_openmpi, unittest_mpich, unittest_flux_openmpi, unittest_flux_mpich, notebooks, benchmark, minimal, pip_check, mypy] + needs: [uv_check, unittest_slurm_mpich, unittest_old, unittest_win, unittest_openmpi, unittest_mpich, unittest_flux_openmpi, unittest_flux_mpich, notebooks, notebooks_slurm, benchmark, minimal, pip_check, mypy] runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 diff --git a/notebooks/2-hpc-cluster.ipynb b/notebooks/2-hpc-cluster.ipynb index e80c5815..49ae6355 100644 --- a/notebooks/2-hpc-cluster.ipynb +++ b/notebooks/2-hpc-cluster.ipynb @@ -1 +1 @@ -{"metadata":{"kernelspec":{"display_name":"Flux","language":"python","name":"flux"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.13.14"}},"nbformat_minor":5,"nbformat":4,"cells":[{"id":"ddf66f38-dc4a-4306-8b1c-b923fdb76922","cell_type":"markdown","source":"# HPC Cluster Executor\nIn contrast to the [Single Node Executor](https://executorlib.readthedocs.io/en/latest/1-single-node.html) and the [HPC Job Executor](https://executorlib.readthedocs.io/en/latest/3-hpc-job.html) the HPC Submission Executors do not communicate via the [zero message queue](https://zeromq.org) but instead store the python functions on the file system and uses the job scheduler to handle the dependencies of the Python functions. Consequently, the block allocation `block_allocation` and the init function `init_function` are not available in the HPC Cluster Executors. At the same time it is possible to close the Python process which created the `Executor`, wait until the execution of the submitted Python functions is completed and afterwards reload the results from the cache.\n\nInternally the HPC submission mode is using the [Python simple queuing system adatper (pysqa)](https://pysqa.readthedocs.io) to connect to HPC job schedulers and the [h5py](https://www.h5py.org) package for serializing the Python functions to store them on the file system. Both packages are optional dependency of executorlib. The installation of the [pysqa](https://pysqa.readthedocs.io) package and the [h5py](https://www.h5py.org) package are covered in the installation section. ","metadata":{}},{"id":"d56862a6-8279-421d-a090-7ca2a3c4d416","cell_type":"markdown","source":["## SLURM\n","The [Simple Linux Utility for Resource Management (SLURM)](https://slurm.schedmd.com) job scheduler is currently the most commonly used job scheduler for HPC clusters. On shared HPC systems users cannot access compute nodes directly — SLURM acts as the resource controller, accepting job requests, managing the queue, and assigning work to nodes when resources become free.\n","\n","In the HPC submission mode executorlib internally uses the [sbatch](https://slurm.schedmd.com/sbatch.html) command, this is in contrast to the [HPC Job Executor](https://executorlib.readthedocs.io/en/latest/3-hpc-job.html) which internally uses the [srun](https://slurm.schedmd.com/srun.html) command.\n","\n","The connection to the job scheduler is based on the [Python simple queuing system adatper (pysqa)](https://pysqa.readthedocs.io). It provides a default configuration for most commonly used job schedulers including SLURM, in addition it is also possible to provide the submission template as part of the resource dictionary `resource_dict` for a single script, or persist it once in a configuration directory referenced via the `pysqa_config_directory` parameter, as covered in the \"Reusing the Configuration\" section below. All three options are covered in more detail on the [pysqa documentation](https://pysqa.readthedocs.io)."],"metadata":{}},{"id":"slurm-background-001","cell_type":"markdown","source":"### Background\n\nThree commands cover the day-to-day SLURM workflow:\n\n**`sbatch`** submits a batch script from the login node. The script carries resource directives on lines starting with `#SBATCH`:\n\n```bash\n#!/bin/bash\n#SBATCH --job-name=my_job\n#SBATCH --output=my_job.out\n#SBATCH --ntasks=4 # total MPI ranks\n#SBATCH --cpus-per-task=1 # CPU threads per rank\n#SBATCH --time=00:30:00 # wall-clock limit (HH:MM:SS)\n#SBATCH --partition=regular\n\nsrun --mpi=pmix python my_script.py\n```\n\n```bash\nsbatch job.sh # submit — returns a job ID immediately\n```\n\nKey `#SBATCH` directives:\n\n| Directive | Meaning |\n|---|---|\n| `--ntasks=N` | Total MPI ranks (processes) |\n| `--cpus-per-task=N` | CPU threads available to each rank |\n| `--mem=NG` | Memory per node (e.g. `8G`) |\n| `--time=HH:MM:SS` | Maximum wall-clock time |\n| `--partition=name` | Queue / partition to target |\n| `--dependency=afterok:JOBID` | Run only after another job succeeds |\n\n**`srun`** launches parallel tasks *inside* an existing allocation. Multiple `srun` calls can run concurrently using shell backgrounding:\n\n```bash\nsrun --mpi=pmix -n 4 python task_a.py &\nsrun --mpi=pmix -n 4 python task_b.py &\nwait # block until both finish\n```\n\n**`squeue`** and **`sacct`** let you inspect the queue and verify resource assignments:\n\n```bash\nsqueue --me # your running/pending jobs\nsacct -j 12345 --format=JobID,State,AllocCPUS,Elapsed # accounting for job 12345\n```\n\nCommon `squeue` state codes: `PD` (pending), `R` (running), `CG` (completing).","metadata":{}},{"id":"slurm-mpi-001","cell_type":"markdown","source":"### MPI-parallel Python\n\nThe [Message Passing Interface (MPI)](https://www.mpi-forum.org) is the dominant parallelisation standard on HPC systems. [`mpi4py`](https://mpi4py.readthedocs.io) provides Python bindings. A minimal example:\n\n```python\n# script.py\nfrom mpi4py import MPI\ncomm = MPI.COMM_WORLD\nprint(f\"rank {comm.Get_rank()} of {comm.Get_size()}\")\n```\n\n```bash\nsrun --mpi=pmix -n 4 python script.py\n```\n\nWhen multiple independent groups of ranks need to run inside one allocation there are two approaches:\n\n| Approach | How | Cross-group communication |\n|---|---|---|\n| Multiple `srun` calls | Each `srun` gets its own communicator | Not possible |\n| `MPI_Comm_split` | One `srun`, split in Python | Possible via `MPI.COMM_WORLD` |\n\n```python\n# communicator splitting — 8 ranks split into two groups of 4\ncomm = MPI.COMM_WORLD\ncolor = comm.Get_rank() // 4 # group 0 or group 1\nsub_comm = comm.Split(color)\n```","metadata":{}},{"id":"db7760e8-35a6-4a1c-8b0f-410b536c3835","cell_type":"markdown","source":"### SlurmClusterExecutor\n\n```python\nfrom executorlib import SlurmClusterExecutor\n```","metadata":{}},{"id":"b20913f3-59e4-418c-a399-866124f8e497","cell_type":"markdown","source":"In comparison to the [SingleNodeExecutor](https://executorlib.readthedocs.io/en/latest/1-single-node.html), the only parameter which is changed in the `SlurmClusterExecutor` is the requirement to specify the cache directory using the `cache_directory=\"./cache\"`. The rest of the syntax remains exactly the same, to simplify the up-scaling of simulation workflows.","metadata":{}},{"id":"0b8f3b77-6199-4736-9f28-3058c5230777","cell_type":"markdown","source":"```python\nwith SlurmClusterExecutor(cache_directory=\"./cache\") as exe:\n future_lst = [exe.submit(sum, [i, i]) for i in range(1, 4)]\n print([f.result() for f in future_lst])\n```","metadata":{}},{"id":"37bef7ac-ce3e-4d8a-b848-b1474c370bca","cell_type":"markdown","source":"Specific parameters for `SlurmClusterExecutor` like the maximum run time `\"run_time_max\"`, the maximum memory `\"memory_max\"` or the submission template for the job submission script `\"submission_template\"` can be specified as part of the resource dictionary. Again it is possible to specify the resource dictonary `resource_dicionary` either for each function in the `submit()` function or during the initialization of the `SlurmClusterExecutor`.","metadata":{}},{"id":"658781de-f222-4235-8c26-b0f77a0831b3","cell_type":"markdown","source":"```python\nsubmission_template = \"\"\"\\\n#!/bin/bash\n#SBATCH --output=time.out\n#SBATCH --job-name={{job_name}}\n#SBATCH --chdir={{working_directory}}\n#SBATCH --get-user-env=L\n#SBATCH --partition={{partition}}\n{%- if run_time_max %}\n#SBATCH --time={{ [1, run_time_max // 60]|max }}\n{%- endif %}\n{%- if dependency %}\n#SBATCH --dependency=afterok:{{ dependency | join(',') }}\n{%- endif %}\n{%- if memory_max %}\n#SBATCH --mem={{memory_max}}G\n{%- endif %}\n#SBATCH --ntasks={{cores}}\n\n{{command}}\n\"\"\"\n\nwith SlurmClusterExecutor(cache_directory=\"./cache\") as exe:\n future = exe.submit(\n sum, [4, 4], \n resource_dict={\n \"submission_template\": submission_template, \n \"run_time_max\": 180, # in seconds \n \"partition\": \"s.cmfe\",\n })\n print(future.result())\n```","metadata":{}},{"id":"f7ad9c97-7743-4f87-9344-4299b2b31a56","cell_type":"markdown","source":"The template uses [Jinja2](https://jinja.palletsprojects.com) syntax. executorlib fills `{{cores}}` into `--ntasks`, so `cores=1` requests one serial process and `cores=4` requests four MPI ranks. With `pmi_mode=\"pmix\"` the executor additionally wraps the function call in `srun --mpi=pmix -n `:\n\n```python\ndef mpi_calc(i):\n from mpi4py import MPI\n comm = MPI.COMM_WORLD\n return {\"rank\": comm.Get_rank(), \"size\": comm.Get_size(), \"input\": i}\n\nwith SlurmClusterExecutor(pmi_mode=\"pmix\", cache_directory=\"./cache\") as exe:\n future = exe.submit(\n mpi_calc, 42,\n resource_dict={\"submission_template\": submission_template, \"cores\": 4, \"partition\": \"regular\", \"run_time_max\": 120})\n print(future.result())\n```\n\nWith these options executorlib in combination with the SLURM job scheduler provides a lot flexibility to configure the submission of Python functions depending on the specific configuration of the job scheduler. \n\nIn case the submission goes wrong, for example when no submission template is defined and executorlib falls back to the default submission template a `CalledProcessError` is raised:\n\n```python\ndef echo(i):\n return i\n\nwith SlurmClusterExecutor() as exe:\n f1 = exe.submit(echo)\n print(f1.result())\n```\n\nThe error message would be something like:\n```\nCalledProcessError: Command '['sbatch', '--parsable', '/home/jovyan/executorlib_cache/echoe5873521b7330f831bed941744079e83/run_queue.sh']' returned non-zero exit status 1.\n```\n\nThis is not really helpful, as it primarily says the `sbatch` command was not successful, but the error message which `sbatch` raised on the command line is not directly accessible from Python. To access the error message you can access the exception of the future object:\n\n```python\nexcep = f1.exception()\nprint(excep.output)\n```\n\nThis gives:\n```\nsbatch: error: invalid partition specified: (null)\nsbatch: error: Batch job submission failed: Invalid partition name specified\n```\n\nSo the submission failed because no partition was provided, which can be corrected by adding the `--partition` flag in the submission template, as demonstrated above. ","metadata":{}},{"id":"e1299068-990e-4fd3-b926-f6415b4e9d75","cell_type":"markdown","source":"### Verifying the Resource Assignment\nAfter the submission it is often useful to confirm that the job scheduler actually assigned the requested resources. For the `SlurmClusterExecutor` the SLURM job identifier is stored in the cache and can be retrieved with the `get_cache_data()` function. This job identifier `queue_id` can then be passed to the SLURM [sacct](https://slurm.schedmd.com/sacct.html) command to inspect the accounting record of the job:\n\n```python\nfrom executorlib import get_cache_data\nimport subprocess\n\nfor entry in get_cache_data(cache_directory=\"./cache\"):\n if \"calc\" in str(entry[\"function\"]):\n job_id = entry[\"queue_id\"]\n print(subprocess.check_output(\n [\"sacct\", \"-j\", str(job_id), \"--format=JobID,State,AllocCPUS,Elapsed\"],\n universal_newlines=True,\n ))\n```\n\nThe `AllocCPUS` column reports the number of CPU cores SLURM allocated for the function. In addition to the `queue_id` each cache entry also contains the full `resource_dict`, the runtime and the path of the result file, which together provide a complete audit trail of the submission - this is the same information returned by the `get_cache_data()` function demonstrated for the [Single Node Executor](https://executorlib.readthedocs.io/en/latest/1-single-node.html#cache).","metadata":{}},{"cell_type":"markdown","id":"pysqa-config-directory-001","metadata":{"trusted":true},"source":["### Reusing the Configuration with `pysqa_config_directory`\n","The `submission_template` shown above is convenient for a single script, but has to be repeated in every Python session which submits jobs. For a configuration which is set up once and reused by any number of scripts and users, executorlib can instead read the submission template from a configuration directory via the `pysqa_config_directory` parameter, which is passed through to the [pysqa](https://pysqa.readthedocs.io) package. This is the same mechanism [pyiron](https://pyiron.org) uses to manage its HPC configuration, so an existing pysqa configuration directory can be reused directly with executorlib.\n","\n","A pysqa configuration directory contains a `queue.yaml` file which lists the available queues, together with a Jinja2 submission template for each of them:\n","```\n","~/.queues/\n","├── queue.yaml\n","└── slurm.sh\n","```\n","\n","`queue.yaml` defines the queue type, the primary queue and the individual queues - `cores_min` and `cores_max` restrict the number of cores which can be requested, `run_time_max` caps the maximum run time in seconds and `script` points to the Jinja2 template file used to generate the submission script:\n","```yaml\n","queue_type: SLURM\n","queue_primary: slurm\n","queues:\n"," slurm: {cores_min: 1, cores_max: 100, run_time_max: 259200, script: slurm.sh}\n","```\n","\n","`slurm.sh` is the same kind of Jinja2 template already introduced above as the `submission_template`, just stored in a file rather than a Python string:\n","```\n","#!/bin/bash\n","#SBATCH --output=time.out\n","#SBATCH --job-name={{job_name}}\n","#SBATCH --chdir={{working_directory}}\n","#SBATCH --get-user-env=L\n","#SBATCH --partition=my_partition\n","{%- if run_time_max %}\n","#SBATCH --time={{ [1, run_time_max // 60]|max }}\n","{%- endif %}\n","{%- if dependency_list %}\n","#SBATCH --dependency=afterok:{{ dependency_list | join(',') }}\n","{%- endif %}\n","{%- if memory_max %}\n","#SBATCH --mem={{memory_max}}G\n","{%- endif %}\n","#SBATCH --ntasks={{cores}}\n","\n","{{command}}\n","```\n","\n","Once the directory is set up it can be reused by any `SlurmClusterExecutor`, simply by pointing `pysqa_config_directory` at it - no `submission_template` needs to be specified anymore:\n","```python\n","with SlurmClusterExecutor(cache_directory=\"./cache\", pysqa_config_directory=\"~/.queues\") as exe:\n"," future = exe.submit(sum, [4, 4], resource_dict={\"run_time_max\": 180, \"cores\": 4})\n"," print(future.result())\n","```\n","\n","If `pysqa_config_directory` is not provided, as in the earlier examples, executorlib falls back to a generic, built-in submission template for the selected job scheduler - this is the default submission template referenced in the `CalledProcessError` example above. Providing an explicit `pysqa_config_directory` (or `submission_template`) becomes necessary as soon as the target HPC system requires mandatory options like `--partition`.\n","\n","For clusters which are only reachable via SSH, or setups spanning multiple job schedulers, the configuration directory can instead contain a `clusters.yaml` file referencing several such `queue.yaml` configurations. This and further configuration options, like SSH-based remote submission, are covered in the [pysqa documentation](https://pysqa.readthedocs.io)."]},{"cell_type":"markdown","id":"claude-code-setup-001","metadata":{},"source":["### Setup with Claude Code\n","Writing a `submission_template` for a new HPC cluster requires knowing its partitions, memory defaults, GPU resources, submit filters and job limits. To automate this step, executorlib provides the [executorlib-cluster-setup](https://github.com/pyiron/executorlib/blob/main/.claude/skills/executorlib-cluster-setup/SKILL.md) skill for [Claude Code](https://docs.claude.com/en/docs/claude-code/overview). Started on the login node of a SLURM cluster, it analyses the cluster with `sinfo`, `scontrol` and `sacctmgr`, checks the generated submission templates with `sbatch --test-only`, runs short smoke tests for serial functions, GPUs, MPI binaries and dependencies, and finally writes a cluster-specific skill `executorlib-`. This cluster-specific skill contains the tested `submission_template`, helper functions to construct the `resource_dict` and the pitfalls found during testing, so later Claude Code sessions can submit Python functions with the `SlurmClusterExecutor` on this cluster.\n","\n","To install the skill for your user, download it to the Claude Code skills directory on the login node:\n","\n","```bash\n","mkdir -p ~/.claude/skills/executorlib-cluster-setup\n","curl -o ~/.claude/skills/executorlib-cluster-setup/SKILL.md https://raw.githubusercontent.com/pyiron/executorlib/main/.claude/skills/executorlib-cluster-setup/SKILL.md\n","```\n","\n","Afterwards start `claude` on the login node, in the Python environment with executorlib and pysqa installed, and call the skill with `/executorlib-cluster-setup` or ask Claude Code to set up executorlib for this cluster. Claude Code asks for the information the cluster cannot provide itself, like the codes you want to run, the account to charge and the URL of the site documentation. As the smoke tests submit short jobs, preferably to a debug or test partition, they consume a small amount of your computing time."]},{"id":"2a814efb-2fbc-41ba-98df-cf121d19ea66","cell_type":"markdown","source":"## Flux\n[Flux](http://flux-framework.org) is a modern HPC resource manager developed at Lawrence Livermore National Laboratory (LLNL). On many systems it runs as a **secondary scheduler inside a SLURM allocation**, enabling fine-grained hierarchical task distribution. Unlike SLURM, Flux can also be installed locally via conda — making it especially suitable for demonstrations, testing, and continuous integration:\n\n```bash\nconda install -c conda-forge flux-core\nflux start # launch a local Flux instance\n```\n\nThis simple installation is explained in the [installation section](https://executorlib.readthedocs.io/en/latest/installation.html#alternative-installations). The features demonstrated below using Flux apply equally to SLURM.","metadata":{}},{"id":"flux-background-001","cell_type":"markdown","source":"### Background\n\nThe key Flux commands map closely onto their SLURM equivalents:\n\n| Flux command | SLURM equivalent | Description |\n|---|---|---|\n| `flux resource list` | `sinfo` | Show available nodes, cores, and GPUs |\n| `flux jobs -a` | `squeue` | List all jobs (running and completed) |\n| `flux submit` | `sbatch` | Submit a non-blocking job; returns a job ID immediately |\n| `flux run` | `srun` | Launch a blocking job; waits for completion |\n| `flux job attach ` | — | Stream output of a previously submitted job |\n\n```bash\n# submit a non-blocking 4-rank MPI job\nflux submit -o pmi=pmix --ntasks=4 python script.py\n\n# run a blocking 4-rank MPI job (waits for output)\nflux run -o pmi=pmix -n 4 python script.py\n```\n\nThe `-o pmi=pmix` flag matches what SLURM's `--mpi=pmix` provides — the same `mpi4py` scripts run unchanged under both schedulers.","metadata":{}},{"id":"29d7aa18-357e-416e-805c-1322b59abec1","cell_type":"markdown","source":"### Dependencies\nAs already demonstrated for the [SingleNodeExecutor](https://executorlib.readthedocs.io/en/latest/1-single-node.html) the `Executor` classes from executorlib are capable of resolving the dependencies of serial functions, when [concurrent futures Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) objects are used as inputs for subsequent function calls. For the case of the HPC submission these dependencies are communicated to the job scheduler, which allows to stop the Python process which created the `Executor` class, wait until the execution of the submitted Python functions is completed and afterwards restart the Python process for the `Executor` class and reload the calculation results from the cache defined by the `cache_directory` parameter.","metadata":{}},{"id":"0f7fc37a-1248-492d-91ab-9db1d737eaee","cell_type":"code","source":"def add_funct(a, b):\n return a + b","metadata":{"trusted":true},"outputs":[],"execution_count":1},{"id":"ae308683-6083-4e78-afc2-bff6c6dc297b","cell_type":"code","source":"from executorlib import FluxClusterExecutor\n\nwith FluxClusterExecutor(cache_directory=\"./file\") as exe:\n future = 0\n for i in range(4, 8):\n future = exe.submit(add_funct, i, future)\n print(future.result())","metadata":{"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":"22\n"}],"execution_count":2},{"id":"ca75cb6c-c50f-4bee-9b09-d8d29d6c263b","cell_type":"markdown","source":"### Resource Assignment\nIn analogy to the [SingleNodeExecutor](https://executorlib.readthedocs.io/en/latest/1-single-node.html) the resource assignment for the `FluxClusterExecutor` is handled by either including the resource dictionary parameter `resource_dict` in the initialization of the `FluxClusterExecutor` class or in every call of the `submit()` function.\n\nBelow this is demonstrated once for the assignment of multiple CPU cores for the execution of a Python function which internally uses the message passing interface (MPI) via the [mpi4py](https://mpi4py.readthedocs.io) package.","metadata":{}},{"id":"eded3a0f-e54f-44f6-962f-eedde4bd2158","cell_type":"code","source":"def calc(i):\n from mpi4py import MPI\n\n size = MPI.COMM_WORLD.Get_size()\n rank = MPI.COMM_WORLD.Get_rank()\n return i, size, rank\n","metadata":{"trusted":true},"outputs":[],"execution_count":3},{"id":"669b05df-3cb2-4f69-9d94-8b2442745ebb","cell_type":"code","source":"with FluxClusterExecutor(cache_directory=\"./file\") as exe:\n fs = exe.submit(calc, 3, resource_dict={\"cores\": 2})\n print(fs.result())","metadata":{"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":"(3, 1, 0)\n"}],"execution_count":4},{"id":"d91499d7-5c6c-4c10-b7b7-bfc4b87ddaa8","cell_type":"markdown","source":"Beyond CPU cores and threads which were previously also introduced for the [Single Node Executor](https://executorlib.readthedocs.io/en/latest/1-single-node.html) the HPC Cluster Executors also provide the option to select the available accelerator cards or GPUs, by specifying the `\"gpus_per_core\"` parameter in the resource dictionary `resource_dict`. For demonstration we create a Python function which reads the GPU device IDs and submit it to the `FluxClusterExecutor` class:\n```python\ndef get_available_gpus():\n import socket\n from tensorflow.python.client import device_lib\n local_device_protos = device_lib.list_local_devices()\n return [\n (x.name, x.physical_device_desc, socket.gethostname()) \n for x in local_device_protos if x.device_type == 'GPU'\n ]\n```\n\n```python\nwith FluxClusterExecutor(\n cache_directory=\"./cache\",\n resource_dict={\"gpus_per_core\": 1}\n) as exe:\n fs_1 = exe.submit(get_available_gpus)\n fs_2 = exe.submit(get_available_gpus)\n print(fs_1.result(), fs_2.result())\n```","metadata":{}},{"id":"b779e393-0c01-4a2a-9343-3480ea59f74b","cell_type":"markdown","source":"### Block Allocation\nIn analogy to the `SingleNodeExecutor` also the `FluxClusterExecutor` and `SlurmClusterExecutor` support the block allocation mode. This starts a number of workers by submitting jobs to the HPC cluster. After these jobs are started, functions are submitted using socket based communication and the same Executor is used to execute multiple functions. This scheme is commonly known as a worker approach, which enables off-loading compute heavy tasks. Below the same example is repeated, which was previously introduced for the `SingleNodeExecutor`:","metadata":{}},{"id":"da81f07f-99f9-469b-9454-efbc083e2043","cell_type":"code","source":"def init_function():\n return {\"j\": 4, \"k\": 3, \"l\": 2}","metadata":{"trusted":true},"outputs":[],"execution_count":5},{"id":"7a3bca08-f39a-48ea-a07c-c41855006843","cell_type":"code","source":"def calc_with_preload(i, j, k):\n return i + j + k","metadata":{"trusted":true},"outputs":[],"execution_count":6},{"id":"1265650e-457d-4a46-9a62-9ad2c95fb80a","cell_type":"markdown","source":"The function `calc_with_preload()` requires three inputs `i`, `j` and `k`. But when the function is submitted to the executor only two inputs are provided `fs = exe.submit(calc, 2, j=5)`. In this case the first input parameter is mapped to `i=2`, the second input parameter is specified explicitly `j=5` but the third input parameter `k` is not provided. So the `FluxClusterExecutor` automatically checks the keys set in the `init_function()` function. In this case the returned dictionary `{\"j\": 4, \"k\": 3, \"l\": 2}` defines `j=4`, `k=3` and `l=2`. For this specific call of the `calc_with_preload()` function, `i` and `j` are already provided so `j` is not required, but `k=3` is used from the `init_function()` and as the `calc_with_preload()` function does not define the `l` parameter this one is also ignored.","metadata":{}},{"id":"ce4dd44c-8db5-4445-bcc5-fad731702444","cell_type":"code","source":"with FluxClusterExecutor(\n cache_directory=\"./file\", \n max_workers=2, \n init_function=init_function, \n block_allocation=True\n) as exe:\n fs = exe.submit(calc_with_preload, 2, j=5)\n print(fs.result())","metadata":{"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":"10\n"}],"execution_count":7},{"id":"93a54d18-9d65-469b-ad6e-bcc1ec590671","cell_type":"markdown","source":"The result is `2+5+3=10` as `i=2` and `j=5` are provided during the submission and `k=3` is defined in the `init_function()` function.","metadata":{}},{"id":"c9c46c64-d097-49d3-ba79-ecb871c8f4da","cell_type":"markdown","source":"## Disconnecting and Reconnecting\nA key advantage of the HPC Cluster Executors over the [HPC Job Executors](https://executorlib.readthedocs.io/en/latest/3-hpc-job.html) is that the Python process which created the executor does not need to stay alive while the submitted functions are running. As the functions are submitted as individual scheduler jobs and the results are stored on the file system, the Python process can be closed after the submission - for example to log out of the login node overnight - and the results can be reloaded later. This is controlled with the `shutdown()` method of the executor, which provides the same `wait` and `cancel_futures` parameters as the [Executor interface](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.shutdown) of the Python standard library.\n\nTo submit a set of functions and disconnect without waiting, the executor is created without a `with` statement and `shutdown()` is called with `wait=False` and `cancel_futures=False`:\n\n```python\nfrom executorlib import SlurmClusterExecutor\n\nexe = SlurmClusterExecutor(cache_directory=\"./cache\")\nfuture_lst = [exe.submit(sum, [i, i]) for i in range(1, 4)]\nexe.shutdown(wait=False, cancel_futures=False)\n```\n\nThe submitted jobs remain in the queue of the job scheduler and continue to run. At a later point - even from a new Python process - the same functions are submitted again using the same `cache_directory`. executorlib recognises the cached results and returns them immediately instead of submitting the functions a second time:\n\n```python\nfrom executorlib import SlurmClusterExecutor\n\nwith SlurmClusterExecutor(cache_directory=\"./cache\") as exe:\n future_lst = [exe.submit(sum, [i, i]) for i in range(1, 4)]\n print([f.result() for f in future_lst])\n```\n\nThe behaviour of the `shutdown()` method is summarized in the following table:\n\n| `shutdown()` call | Effect |\n|---|---|\n| `shutdown(wait=True)` | Wait until all submitted functions are finished before continuing - this is the default and also what the `with` statement does. |\n| `shutdown(wait=False, cancel_futures=False)` | Return immediately and leave the submitted jobs running in the scheduler queue - used to disconnect from a running workflow. |\n| `shutdown(wait=False, cancel_futures=True)` | Cancel the submitted jobs which have not started or finished yet. |\n\nThis disconnect-and-reconnect capability is available for both the `SlurmClusterExecutor` and the `FluxClusterExecutor`, as both communicate via the file system rather than via sockets.","metadata":{}},{"id":"slurm-job-executor-001","cell_type":"markdown","source":"## Combine both\n\nWhile `SlurmClusterExecutor` submits each Python function as a separate `sbatch` job from the login node, the [HPC Job Executor](https://executorlib.readthedocs.io/en/latest/3-hpc-job.html) (`SlurmJobExecutor`) runs **inside** an already-running SLURM allocation and dispatches tasks as `srun` steps — no new jobs enter the queue.\n\n```python\nfrom executorlib import SlurmJobExecutor\n\n# This code runs inside an existing SLURM job\nwith SlurmJobExecutor(max_workers=4) as exe:\n futures = [exe.submit(sum, [i, i], resource_dict={\"cores\": 1}) for i in range(4)]\n print([f.result() for f in futures])\n```\n\nThe two executor types can be nested: a function submitted via `SlurmClusterExecutor` (running as an `sbatch` job) can itself create a `SlurmJobExecutor` to parallelise sub-tasks as `srun` steps within the same allocation:\n\n```python\nfrom executorlib import SlurmClusterExecutor, SlurmJobExecutor\n\ndef parallel_workflow(n):\n with SlurmJobExecutor(max_workers=n) as inner:\n futures = [inner.submit(sum, [i, i], resource_dict={\"cores\": 1}) for i in range(n)]\n return [f.result() for f in futures]\n\nwith SlurmClusterExecutor(cache_directory=\"./cache\") as outer:\n future = outer.submit(\n parallel_workflow, 4,\n resource_dict={\"cores\": 1, \"partition\": \"regular\", \"run_time_max\": 300})\n print(future.result())\n```\n\nThe `sacct` output for such a job will show the outer `sbatch` job together with numbered `srun` steps (e.g. `12345.0`, `12345.1`, …), all completing within the same allocation.\n\n| Executor | Scheduler command | Typical use |\n|---|---|---|\n| `SlurmClusterExecutor` | `sbatch` (one job per function) | Submit from login node |\n| `SlurmJobExecutor` | `srun` steps within current job | Inside an existing allocation |\n| `FluxClusterExecutor` | `flux submit` | Flux-managed allocation or local testing |","metadata":{}},{"id":"3f47fd34-04d1-42a7-bb06-6821dc99a648","cell_type":"markdown","source":"## Cleaning Cache\nFinally, as the HPC Cluster Executors leverage the file system to communicate serialized Python functions, it is important to clean up the cache directory specified by the `cache_directory` parameter once the results of the submitted Python functions are no longer needed. The serialized Python functions are stored in binary format using the [cloudpickle](https://github.com/cloudpipe/cloudpickle) library for serialization. This format is design for caching but not for long-term storage. The user is responsible for the long-term storage of their data.","metadata":{}},{"id":"f537b4f6-cc98-43da-8aca-94a823bcbcbd","cell_type":"code","source":"import os\nimport shutil\n\ncache_dir = \"./file\"\nif os.path.exists(cache_dir):\n print(os.listdir(cache_dir))\n try:\n shutil.rmtree(cache_dir)\n except OSError:\n pass","metadata":{"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":"['add_funct144ecf19b5020fccad214df3f4bdabd0_o.h5', 'add_funct67b8245bf71c3c6dcb2018663939c72d', 'add_funct4a5d1f06cca57f0ffbaa3116d39ecc6a', 'add_functcb272924f36cbaa9ac79f8d42b6771c8_o.h5', 'calcd732cdcbd2c8e68145d99f0be814e667', '393f99f890d39348c6248689096e6efb', 'add_funct67b8245bf71c3c6dcb2018663939c72d_o.h5', 'add_funct4a5d1f06cca57f0ffbaa3116d39ecc6a_o.h5', 'calcd732cdcbd2c8e68145d99f0be814e667_o.h5', '3888b889a896c43b68f0bd924ee5285c', 'add_funct144ecf19b5020fccad214df3f4bdabd0', 'add_functcb272924f36cbaa9ac79f8d42b6771c8', 'calc_with_preloade920bec0b69f103b2579175e37aa3528_o.h5']\n"}],"execution_count":8},{"id":"3efc9f5d-fbf9-4a85-8963-5711a453130d","cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]} \ No newline at end of file +{"metadata":{"kernelspec":{"display_name":"Flux","language":"python","name":"flux"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.13.14"}},"nbformat_minor":5,"nbformat":4,"cells":[{"id":"ddf66f38-dc4a-4306-8b1c-b923fdb76922","cell_type":"markdown","source":"# HPC Cluster Executor\nIn contrast to the [Single Node Executor](https://executorlib.readthedocs.io/en/latest/1-single-node.html) and the [HPC Job Executor](https://executorlib.readthedocs.io/en/latest/3-hpc-job.html) the HPC Submission Executors do not communicate via the [zero message queue](https://zeromq.org) but instead store the python functions on the file system and uses the job scheduler to handle the dependencies of the Python functions. Consequently, the block allocation `block_allocation` and the init function `init_function` are not available in the HPC Cluster Executors. At the same time it is possible to close the Python process which created the `Executor`, wait until the execution of the submitted Python functions is completed and afterwards reload the results from the cache.\n\nInternally the HPC submission mode is using the [Python simple queuing system adatper (pysqa)](https://pysqa.readthedocs.io) to connect to HPC job schedulers and the [h5py](https://www.h5py.org) package for serializing the Python functions to store them on the file system. Both packages are optional dependency of executorlib. The installation of the [pysqa](https://pysqa.readthedocs.io) package and the [h5py](https://www.h5py.org) package are covered in the installation section. ","metadata":{}},{"id":"d56862a6-8279-421d-a090-7ca2a3c4d416","cell_type":"markdown","source":["## SLURM\n","The [Simple Linux Utility for Resource Management (SLURM)](https://slurm.schedmd.com) job scheduler is currently the most commonly used job scheduler for HPC clusters. On shared HPC systems users cannot access compute nodes directly — SLURM acts as the resource controller, accepting job requests, managing the queue, and assigning work to nodes when resources become free.\n","\n","In the HPC submission mode executorlib internally uses the [sbatch](https://slurm.schedmd.com/sbatch.html) command, this is in contrast to the [HPC Job Executor](https://executorlib.readthedocs.io/en/latest/3-hpc-job.html) which internally uses the [srun](https://slurm.schedmd.com/srun.html) command.\n","\n","The connection to the job scheduler is based on the [Python simple queuing system adatper (pysqa)](https://pysqa.readthedocs.io). It provides a default configuration for most commonly used job schedulers including SLURM, in addition it is also possible to provide the submission template as part of the resource dictionary `resource_dict` for a single script, or persist it once in a configuration directory referenced via the `pysqa_config_directory` parameter, as covered in the \"Reusing the Configuration\" section below. All three options are covered in more detail on the [pysqa documentation](https://pysqa.readthedocs.io)."],"metadata":{}},{"id":"slurm-background-001","cell_type":"markdown","source":"### Background\n\nThree commands cover the day-to-day SLURM workflow:\n\n**`sbatch`** submits a batch script from the login node. The script carries resource directives on lines starting with `#SBATCH`:\n\n```bash\n#!/bin/bash\n#SBATCH --job-name=my_job\n#SBATCH --output=my_job.out\n#SBATCH --ntasks=4 # total MPI ranks\n#SBATCH --cpus-per-task=1 # CPU threads per rank\n#SBATCH --time=00:30:00 # wall-clock limit (HH:MM:SS)\n#SBATCH --partition=regular\n\nsrun --mpi=pmix python my_script.py\n```\n\n```bash\nsbatch job.sh # submit — returns a job ID immediately\n```\n\nKey `#SBATCH` directives:\n\n| Directive | Meaning |\n|---|---|\n| `--ntasks=N` | Total MPI ranks (processes) |\n| `--cpus-per-task=N` | CPU threads available to each rank |\n| `--mem=NG` | Memory per node (e.g. `8G`) |\n| `--time=HH:MM:SS` | Maximum wall-clock time |\n| `--partition=name` | Queue / partition to target |\n| `--dependency=afterok:JOBID` | Run only after another job succeeds |\n\n**`srun`** launches parallel tasks *inside* an existing allocation. Multiple `srun` calls can run concurrently using shell backgrounding:\n\n```bash\nsrun --mpi=pmix -n 4 python task_a.py &\nsrun --mpi=pmix -n 4 python task_b.py &\nwait # block until both finish\n```\n\n**`squeue`** and **`sacct`** let you inspect the queue and verify resource assignments:\n\n```bash\nsqueue --me # your running/pending jobs\nsacct -j 12345 --format=JobID,State,AllocCPUS,Elapsed # accounting for job 12345\n```\n\nCommon `squeue` state codes: `PD` (pending), `R` (running), `CG` (completing).","metadata":{}},{"id":"slurm-mpi-001","cell_type":"markdown","source":"### MPI-parallel Python\n\nThe [Message Passing Interface (MPI)](https://www.mpi-forum.org) is the dominant parallelisation standard on HPC systems. [`mpi4py`](https://mpi4py.readthedocs.io) provides Python bindings. A minimal example:\n\n```python\n# script.py\nfrom mpi4py import MPI\ncomm = MPI.COMM_WORLD\nprint(f\"rank {comm.Get_rank()} of {comm.Get_size()}\")\n```\n\n```bash\nsrun --mpi=pmix -n 4 python script.py\n```\n\nWhen multiple independent groups of ranks need to run inside one allocation there are two approaches:\n\n| Approach | How | Cross-group communication |\n|---|---|---|\n| Multiple `srun` calls | Each `srun` gets its own communicator | Not possible |\n| `MPI_Comm_split` | One `srun`, split in Python | Possible via `MPI.COMM_WORLD` |\n\n```python\n# communicator splitting — 8 ranks split into two groups of 4\ncomm = MPI.COMM_WORLD\ncolor = comm.Get_rank() // 4 # group 0 or group 1\nsub_comm = comm.Split(color)\n```","metadata":{}},{"id":"ef94e3cb-f353-440b-b235-040833993d2c","cell_type":"markdown","source":"### SlurmClusterExecutor","metadata":{}},{"id":"6b7fde30-92fb-43e7-9875-120c1ae555eb","cell_type":"code","source":"from executorlib import SlurmClusterExecutor","metadata":{"trusted":true,"tags":["slurm"]},"outputs":[],"execution_count":null},{"id":"b20913f3-59e4-418c-a399-866124f8e497","cell_type":"markdown","source":"In comparison to the [SingleNodeExecutor](https://executorlib.readthedocs.io/en/latest/1-single-node.html), the only parameter which is changed in the `SlurmClusterExecutor` is the requirement to specify the cache directory using the `cache_directory=\"./cache\"`. The rest of the syntax remains exactly the same, to simplify the up-scaling of simulation workflows.\n\nIn addition, most HPC clusters require site-specific options in the job submission script, like the partition or the maximum run time. These options are defined in a submission template, which is explained in more detail below:","metadata":{}},{"id":"afef53ac-a787-43f2-8062-62ad14610527","cell_type":"code","source":"submission_template = \"\"\"\\\n#!/bin/bash\n#SBATCH --output=time.out\n#SBATCH --job-name={{job_name}}\n#SBATCH --chdir={{working_directory}}\n#SBATCH --get-user-env=L\n{%- if partition %}\n#SBATCH --partition={{partition}}\n{%- endif %}\n{%- if run_time_max %}\n#SBATCH --time={{ [1, run_time_max // 60]|max }}\n{%- endif %}\n{%- if dependency_list %}\n#SBATCH --dependency=afterok:{{ dependency_list | join(',') }}\n{%- endif %}\n{%- if memory_max %}\n#SBATCH --mem={{memory_max}}G\n{%- endif %}\n#SBATCH --ntasks={{cores}}\n\n{{command}}\n\"\"\"","metadata":{"trusted":true,"tags":["slurm"]},"outputs":[],"execution_count":null},{"id":"c24193fb-0cf7-436d-9004-835362b222da","cell_type":"markdown","source":"The submission template is passed to the `SlurmClusterExecutor` as part of the resource dictionary `resource_dict`:","metadata":{}},{"id":"35c9decb-bc65-4ba8-a9cb-9078363f66ef","cell_type":"code","source":"with SlurmClusterExecutor(\n cache_directory=\"./cache\",\n resource_dict={\"submission_template\": submission_template},\n) as exe:\n future_lst = [exe.submit(sum, [i, i]) for i in range(1, 4)]\n print([f.result() for f in future_lst])","metadata":{"trusted":true,"tags":["slurm"]},"outputs":[],"execution_count":null},{"id":"37bef7ac-ce3e-4d8a-b848-b1474c370bca","cell_type":"markdown","source":"Specific parameters for `SlurmClusterExecutor` like the maximum run time `\"run_time_max\"`, the maximum memory `\"memory_max\"` or the submission template for the job submission script `\"submission_template\"` can be specified as part of the resource dictionary. Again it is possible to specify the resource dictonary `resource_dicionary` either for each function in the `submit()` function or during the initialization of the `SlurmClusterExecutor`.","metadata":{}},{"id":"d342170b-3149-4dbc-a4ad-f9e7eab6a051","cell_type":"markdown","source":"The submission template defined above only adds the `#SBATCH` lines for parameters which are set, for example the `--partition` line is only added when the `\"partition\"` is specified in the resource dictionary:","metadata":{}},{"id":"3f68277b-2eb5-4349-a72c-718aeed97466","cell_type":"code","source":"with SlurmClusterExecutor(cache_directory=\"./cache\") as exe:\n future = exe.submit(\n sum, [4, 4],\n resource_dict={\n \"submission_template\": submission_template,\n \"run_time_max\": 180, # in seconds\n # \"partition\": \"regular\", # select the partition of your HPC cluster\n })\n print(future.result())","metadata":{"trusted":true,"tags":["slurm"]},"outputs":[],"execution_count":null},{"id":"65e32bbb-c5b0-4be0-8d1d-32fd583c79aa","cell_type":"markdown","source":"The template uses [Jinja2](https://jinja.palletsprojects.com) syntax. executorlib fills `{{cores}}` into `--ntasks`, so `cores=1` requests one serial process and `cores=4` requests four MPI ranks. With the `pmi_mode` parameter the executor additionally wraps the function call in `srun --mpi= -n `, for example `pmi_mode=\"pmix\"` for OpenMPI >= 5 or `pmi_mode=\"pmi2\"` for MPICH:","metadata":{}},{"id":"b165bb7e-f76f-4634-b502-5c3e04febcb2","cell_type":"code","source":"def mpi_calc(i):\n from mpi4py import MPI\n comm = MPI.COMM_WORLD\n return {\"rank\": comm.Get_rank(), \"size\": comm.Get_size(), \"input\": i}\n\nwith SlurmClusterExecutor(pmi_mode=\"pmi2\", cache_directory=\"./cache\") as exe:\n future = exe.submit(\n mpi_calc, 42,\n resource_dict={\"submission_template\": submission_template, \"cores\": 2, \"run_time_max\": 120})\n print(future.result())","metadata":{"trusted":true,"tags":["slurm"]},"outputs":[],"execution_count":null},{"id":"1e66986c-650c-4c65-8fa4-fafccb772c7c","cell_type":"markdown","source":"When the result of one function is used as input for the next function, executorlib communicates this dependency to SLURM. The job of the second function is submitted with the `--dependency=afterok:` option, which is generated from the `dependency_list` in the submission template:","metadata":{}},{"id":"2619ad8e-fad7-457c-83d0-9d1ea4823186","cell_type":"code","source":"def add(a, b):\n return a + b\n\nwith SlurmClusterExecutor(\n cache_directory=\"./cache\",\n resource_dict={\"submission_template\": submission_template},\n) as exe:\n future = 0\n for i in range(1, 4):\n future = exe.submit(add, i, future)\n print(future.result())","metadata":{"trusted":true,"tags":["slurm"]},"outputs":[],"execution_count":null},{"id":"961b0769-6aa2-4957-a650-e042f9e5cfb0","cell_type":"markdown","source":"With these options executorlib in combination with the SLURM job scheduler provides a lot flexibility to configure the submission of Python functions depending on the specific configuration of the job scheduler. \n\nIn case the submission goes wrong, for example when no submission template is defined and executorlib falls back to the default submission template a `CalledProcessError` is raised:\n\n```python\ndef echo(i):\n return i\n\nwith SlurmClusterExecutor() as exe:\n f1 = exe.submit(echo)\n print(f1.result())\n```\n\nThe error message would be something like:\n```\nCalledProcessError: Command '['sbatch', '--parsable', '/home/jovyan/executorlib_cache/echoe5873521b7330f831bed941744079e83/run_queue.sh']' returned non-zero exit status 1.\n```\n\nThis is not really helpful, as it primarily says the `sbatch` command was not successful, but the error message which `sbatch` raised on the command line is not directly accessible from Python. To access the error message you can access the exception of the future object:\n\n```python\nexcep = f1.exception()\nprint(excep.output)\n```\n\nThis gives:\n```\nsbatch: error: invalid partition specified: (null)\nsbatch: error: Batch job submission failed: Invalid partition name specified\n```\n\nSo the submission failed because no partition was provided, which can be corrected by adding the `--partition` flag in the submission template, as demonstrated above - with the submission template defined above by adding the `\"partition\"` to the resource dictionary `resource_dict`.","metadata":{}},{"id":"a334b1b1-d316-42c0-995f-d44ea01cbaaa","cell_type":"markdown","source":"### Verifying the Resource Assignment\nAfter the submission it is often useful to confirm that the job scheduler actually assigned the requested resources. For the `SlurmClusterExecutor` the SLURM job identifier is stored in the cache and can be retrieved with the `get_cache_data()` function. This job identifier `queue_id` can then be passed to the SLURM [sacct](https://slurm.schedmd.com/sacct.html) command to inspect the accounting record of the job:","metadata":{}},{"id":"c1ea42c4-29f8-490f-aa8e-1890018677f4","cell_type":"code","source":"from executorlib import get_cache_data\nimport subprocess\n\nfor entry in get_cache_data(cache_directory=\"./cache\"):\n if \"mpi_calc\" in str(entry[\"function\"]):\n job_id = entry[\"queue_id\"]\n print(subprocess.check_output(\n [\"sacct\", \"-j\", str(job_id), \"--format=JobID,State,AllocCPUS,Elapsed\"],\n universal_newlines=True,\n ))","metadata":{"trusted":true,"tags":["slurm"]},"outputs":[],"execution_count":null},{"id":"3b150860-2c27-455f-9072-a526ab51da5a","cell_type":"markdown","source":"The `AllocCPUS` column reports the number of CPU cores SLURM allocated for the function. In addition to the `queue_id` each cache entry also contains the full `resource_dict`, the runtime and the path of the result file, which together provide a complete audit trail of the submission - this is the same information returned by the `get_cache_data()` function demonstrated for the [Single Node Executor](https://executorlib.readthedocs.io/en/latest/1-single-node.html#cache).","metadata":{}},{"cell_type":"markdown","id":"pysqa-config-directory-001","metadata":{"trusted":true},"source":["### Reusing the Configuration with `pysqa_config_directory`\n","The `submission_template` shown above is convenient for a single script, but has to be repeated in every Python session which submits jobs. For a configuration which is set up once and reused by any number of scripts and users, executorlib can instead read the submission template from a configuration directory via the `pysqa_config_directory` parameter, which is passed through to the [pysqa](https://pysqa.readthedocs.io) package. This is the same mechanism [pyiron](https://pyiron.org) uses to manage its HPC configuration, so an existing pysqa configuration directory can be reused directly with executorlib.\n","\n","A pysqa configuration directory contains a `queue.yaml` file which lists the available queues, together with a Jinja2 submission template for each of them:\n","```\n","~/.queues/\n","├── queue.yaml\n","└── slurm.sh\n","```\n","\n","`queue.yaml` defines the queue type, the primary queue and the individual queues - `cores_min` and `cores_max` restrict the number of cores which can be requested, `run_time_max` caps the maximum run time in seconds and `script` points to the Jinja2 template file used to generate the submission script:\n","```yaml\n","queue_type: SLURM\n","queue_primary: slurm\n","queues:\n"," slurm: {cores_min: 1, cores_max: 100, run_time_max: 259200, script: slurm.sh}\n","```\n","\n","`slurm.sh` is the same kind of Jinja2 template already introduced above as the `submission_template`, just stored in a file rather than a Python string:\n","```\n","#!/bin/bash\n","#SBATCH --output=time.out\n","#SBATCH --job-name={{job_name}}\n","#SBATCH --chdir={{working_directory}}\n","#SBATCH --get-user-env=L\n","#SBATCH --partition=my_partition\n","{%- if run_time_max %}\n","#SBATCH --time={{ [1, run_time_max // 60]|max }}\n","{%- endif %}\n","{%- if dependency_list %}\n","#SBATCH --dependency=afterok:{{ dependency_list | join(',') }}\n","{%- endif %}\n","{%- if memory_max %}\n","#SBATCH --mem={{memory_max}}G\n","{%- endif %}\n","#SBATCH --ntasks={{cores}}\n","\n","{{command}}\n","```\n","\n","Once the directory is set up it can be reused by any `SlurmClusterExecutor`, simply by pointing `pysqa_config_directory` at it - no `submission_template` needs to be specified anymore:\n","```python\n","with SlurmClusterExecutor(cache_directory=\"./cache\", pysqa_config_directory=\"~/.queues\") as exe:\n"," future = exe.submit(sum, [4, 4], resource_dict={\"run_time_max\": 180, \"cores\": 4})\n"," print(future.result())\n","```\n","\n","If `pysqa_config_directory` is not provided, as in the earlier examples, executorlib falls back to a generic, built-in submission template for the selected job scheduler - this is the default submission template referenced in the `CalledProcessError` example above. Providing an explicit `pysqa_config_directory` (or `submission_template`) becomes necessary as soon as the target HPC system requires mandatory options like `--partition`.\n","\n","For clusters which are only reachable via SSH, or setups spanning multiple job schedulers, the configuration directory can instead contain a `clusters.yaml` file referencing several such `queue.yaml` configurations. This and further configuration options, like SSH-based remote submission, are covered in the [pysqa documentation](https://pysqa.readthedocs.io)."]},{"cell_type":"markdown","id":"claude-code-setup-001","metadata":{},"source":["### Setup with Claude Code\n","Writing a `submission_template` for a new HPC cluster requires knowing its partitions, memory defaults, GPU resources, submit filters and job limits. To automate this step, executorlib provides the [executorlib-cluster-setup](https://github.com/pyiron/executorlib/blob/main/.claude/skills/executorlib-cluster-setup/SKILL.md) skill for [Claude Code](https://docs.claude.com/en/docs/claude-code/overview). Started on the login node of a SLURM cluster, it analyses the cluster with `sinfo`, `scontrol` and `sacctmgr`, checks the generated submission templates with `sbatch --test-only`, runs short smoke tests for serial functions, GPUs, MPI binaries and dependencies, and finally writes a cluster-specific skill `executorlib-`. This cluster-specific skill contains the tested `submission_template`, helper functions to construct the `resource_dict` and the pitfalls found during testing, so later Claude Code sessions can submit Python functions with the `SlurmClusterExecutor` on this cluster.\n","\n","To install the skill for your user, download it to the Claude Code skills directory on the login node:\n","\n","```bash\n","mkdir -p ~/.claude/skills/executorlib-cluster-setup\n","curl -o ~/.claude/skills/executorlib-cluster-setup/SKILL.md https://raw.githubusercontent.com/pyiron/executorlib/main/.claude/skills/executorlib-cluster-setup/SKILL.md\n","```\n","\n","Afterwards start `claude` on the login node, in the Python environment with executorlib and pysqa installed, and call the skill with `/executorlib-cluster-setup` or ask Claude Code to set up executorlib for this cluster. Claude Code asks for the information the cluster cannot provide itself, like the codes you want to run, the account to charge and the URL of the site documentation. As the smoke tests submit short jobs, preferably to a debug or test partition, they consume a small amount of your computing time."]},{"id":"2a814efb-2fbc-41ba-98df-cf121d19ea66","cell_type":"markdown","source":"## Flux\n[Flux](http://flux-framework.org) is a modern HPC resource manager developed at Lawrence Livermore National Laboratory (LLNL). On many systems it runs as a **secondary scheduler inside a SLURM allocation**, enabling fine-grained hierarchical task distribution. Unlike SLURM, Flux can also be installed locally via conda — making it especially suitable for demonstrations, testing, and continuous integration:\n\n```bash\nconda install -c conda-forge flux-core\nflux start # launch a local Flux instance\n```\n\nThis simple installation is explained in the [installation section](https://executorlib.readthedocs.io/en/latest/installation.html#alternative-installations). The features demonstrated below using Flux apply equally to SLURM.","metadata":{}},{"id":"flux-background-001","cell_type":"markdown","source":"### Background\n\nThe key Flux commands map closely onto their SLURM equivalents:\n\n| Flux command | SLURM equivalent | Description |\n|---|---|---|\n| `flux resource list` | `sinfo` | Show available nodes, cores, and GPUs |\n| `flux jobs -a` | `squeue` | List all jobs (running and completed) |\n| `flux submit` | `sbatch` | Submit a non-blocking job; returns a job ID immediately |\n| `flux run` | `srun` | Launch a blocking job; waits for completion |\n| `flux job attach ` | — | Stream output of a previously submitted job |\n\n```bash\n# submit a non-blocking 4-rank MPI job\nflux submit -o pmi=pmix --ntasks=4 python script.py\n\n# run a blocking 4-rank MPI job (waits for output)\nflux run -o pmi=pmix -n 4 python script.py\n```\n\nThe `-o pmi=pmix` flag matches what SLURM's `--mpi=pmix` provides — the same `mpi4py` scripts run unchanged under both schedulers.","metadata":{}},{"id":"29d7aa18-357e-416e-805c-1322b59abec1","cell_type":"markdown","source":"### Dependencies\nAs already demonstrated for the [SingleNodeExecutor](https://executorlib.readthedocs.io/en/latest/1-single-node.html) the `Executor` classes from executorlib are capable of resolving the dependencies of serial functions, when [concurrent futures Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) objects are used as inputs for subsequent function calls. For the case of the HPC submission these dependencies are communicated to the job scheduler, which allows to stop the Python process which created the `Executor` class, wait until the execution of the submitted Python functions is completed and afterwards restart the Python process for the `Executor` class and reload the calculation results from the cache defined by the `cache_directory` parameter.","metadata":{}},{"id":"0f7fc37a-1248-492d-91ab-9db1d737eaee","cell_type":"code","source":"def add_funct(a, b):\n return a + b","metadata":{"trusted":true},"outputs":[],"execution_count":1},{"id":"ae308683-6083-4e78-afc2-bff6c6dc297b","cell_type":"code","source":"from executorlib import FluxClusterExecutor\n\nwith FluxClusterExecutor(cache_directory=\"./file\") as exe:\n future = 0\n for i in range(4, 8):\n future = exe.submit(add_funct, i, future)\n print(future.result())","metadata":{"trusted":true,"tags":["flux"]},"outputs":[{"name":"stdout","output_type":"stream","text":"22\n"}],"execution_count":2},{"id":"ca75cb6c-c50f-4bee-9b09-d8d29d6c263b","cell_type":"markdown","source":"### Resource Assignment\nIn analogy to the [SingleNodeExecutor](https://executorlib.readthedocs.io/en/latest/1-single-node.html) the resource assignment for the `FluxClusterExecutor` is handled by either including the resource dictionary parameter `resource_dict` in the initialization of the `FluxClusterExecutor` class or in every call of the `submit()` function.\n\nBelow this is demonstrated once for the assignment of multiple CPU cores for the execution of a Python function which internally uses the message passing interface (MPI) via the [mpi4py](https://mpi4py.readthedocs.io) package.","metadata":{}},{"id":"eded3a0f-e54f-44f6-962f-eedde4bd2158","cell_type":"code","source":"def calc(i):\n from mpi4py import MPI\n\n size = MPI.COMM_WORLD.Get_size()\n rank = MPI.COMM_WORLD.Get_rank()\n return i, size, rank\n","metadata":{"trusted":true},"outputs":[],"execution_count":3},{"id":"669b05df-3cb2-4f69-9d94-8b2442745ebb","cell_type":"code","source":"with FluxClusterExecutor(cache_directory=\"./file\") as exe:\n fs = exe.submit(calc, 3, resource_dict={\"cores\": 2})\n print(fs.result())","metadata":{"trusted":true,"tags":["flux"]},"outputs":[{"name":"stdout","output_type":"stream","text":"(3, 1, 0)\n"}],"execution_count":4},{"id":"d91499d7-5c6c-4c10-b7b7-bfc4b87ddaa8","cell_type":"markdown","source":"Beyond CPU cores and threads which were previously also introduced for the [Single Node Executor](https://executorlib.readthedocs.io/en/latest/1-single-node.html) the HPC Cluster Executors also provide the option to select the available accelerator cards or GPUs, by specifying the `\"gpus_per_core\"` parameter in the resource dictionary `resource_dict`. For demonstration we create a Python function which reads the GPU device IDs and submit it to the `FluxClusterExecutor` class:\n```python\ndef get_available_gpus():\n import socket\n from tensorflow.python.client import device_lib\n local_device_protos = device_lib.list_local_devices()\n return [\n (x.name, x.physical_device_desc, socket.gethostname()) \n for x in local_device_protos if x.device_type == 'GPU'\n ]\n```\n\n```python\nwith FluxClusterExecutor(\n cache_directory=\"./cache\",\n resource_dict={\"gpus_per_core\": 1}\n) as exe:\n fs_1 = exe.submit(get_available_gpus)\n fs_2 = exe.submit(get_available_gpus)\n print(fs_1.result(), fs_2.result())\n```","metadata":{}},{"id":"b779e393-0c01-4a2a-9343-3480ea59f74b","cell_type":"markdown","source":"### Block Allocation\nIn analogy to the `SingleNodeExecutor` also the `FluxClusterExecutor` and `SlurmClusterExecutor` support the block allocation mode. This starts a number of workers by submitting jobs to the HPC cluster. After these jobs are started, functions are submitted using socket based communication and the same Executor is used to execute multiple functions. This scheme is commonly known as a worker approach, which enables off-loading compute heavy tasks. Below the same example is repeated, which was previously introduced for the `SingleNodeExecutor`:","metadata":{}},{"id":"da81f07f-99f9-469b-9454-efbc083e2043","cell_type":"code","source":"def init_function():\n return {\"j\": 4, \"k\": 3, \"l\": 2}","metadata":{"trusted":true},"outputs":[],"execution_count":5},{"id":"7a3bca08-f39a-48ea-a07c-c41855006843","cell_type":"code","source":"def calc_with_preload(i, j, k):\n return i + j + k","metadata":{"trusted":true},"outputs":[],"execution_count":6},{"id":"1265650e-457d-4a46-9a62-9ad2c95fb80a","cell_type":"markdown","source":"The function `calc_with_preload()` requires three inputs `i`, `j` and `k`. But when the function is submitted to the executor only two inputs are provided `fs = exe.submit(calc, 2, j=5)`. In this case the first input parameter is mapped to `i=2`, the second input parameter is specified explicitly `j=5` but the third input parameter `k` is not provided. So the `FluxClusterExecutor` automatically checks the keys set in the `init_function()` function. In this case the returned dictionary `{\"j\": 4, \"k\": 3, \"l\": 2}` defines `j=4`, `k=3` and `l=2`. For this specific call of the `calc_with_preload()` function, `i` and `j` are already provided so `j` is not required, but `k=3` is used from the `init_function()` and as the `calc_with_preload()` function does not define the `l` parameter this one is also ignored.","metadata":{}},{"id":"ce4dd44c-8db5-4445-bcc5-fad731702444","cell_type":"code","source":"with FluxClusterExecutor(\n cache_directory=\"./file\", \n max_workers=2, \n init_function=init_function, \n block_allocation=True\n) as exe:\n fs = exe.submit(calc_with_preload, 2, j=5)\n print(fs.result())","metadata":{"trusted":true,"tags":["flux"]},"outputs":[{"name":"stdout","output_type":"stream","text":"10\n"}],"execution_count":7},{"id":"93a54d18-9d65-469b-ad6e-bcc1ec590671","cell_type":"markdown","source":"The result is `2+5+3=10` as `i=2` and `j=5` are provided during the submission and `k=3` is defined in the `init_function()` function.","metadata":{}},{"id":"5d1d1374-46a4-4c2d-8a88-eceeebb568e8","cell_type":"markdown","source":"## Disconnecting and Reconnecting\nA key advantage of the HPC Cluster Executors over the [HPC Job Executors](https://executorlib.readthedocs.io/en/latest/3-hpc-job.html) is that the Python process which created the executor does not need to stay alive while the submitted functions are running. As the functions are submitted as individual scheduler jobs and the results are stored on the file system, the Python process can be closed after the submission - for example to log out of the login node overnight - and the results can be reloaded later. This is controlled with the `shutdown()` method of the executor, which provides the same `wait` and `cancel_futures` parameters as the [Executor interface](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.shutdown) of the Python standard library.\n\nTo submit a set of functions and disconnect without waiting, the executor is created without a `with` statement and `shutdown()` is called with `wait=False` and `cancel_futures=False`:","metadata":{}},{"id":"77db00e6-d201-4315-abec-21388ce75e0c","cell_type":"code","source":"from executorlib import SlurmClusterExecutor\n\nexe = SlurmClusterExecutor(\n cache_directory=\"./cache_disconnect\",\n resource_dict={\"submission_template\": submission_template},\n)\nfuture_lst = [exe.submit(sum, [i, i]) for i in range(1, 4)]\nexe.shutdown(wait=False, cancel_futures=False)","metadata":{"trusted":true,"tags":["slurm"]},"outputs":[],"execution_count":null},{"id":"a976ae9f-0d30-42fb-9d41-3571b02036ca","cell_type":"markdown","source":"The submitted jobs remain in the queue of the job scheduler and continue to run. At a later point - even from a new Python process - the same functions are submitted again using the same `cache_directory`. executorlib recognises the cached results and returns them immediately instead of submitting the functions a second time:","metadata":{}},{"id":"2cc8722d-a60e-4a7c-8336-bbac5b48141b","cell_type":"code","source":"from executorlib import SlurmClusterExecutor\n\nwith SlurmClusterExecutor(\n cache_directory=\"./cache_disconnect\",\n resource_dict={\"submission_template\": submission_template},\n) as exe:\n future_lst = [exe.submit(sum, [i, i]) for i in range(1, 4)]\n print([f.result() for f in future_lst])","metadata":{"trusted":true,"tags":["slurm"]},"outputs":[],"execution_count":null},{"id":"2dd17c71-3cbb-46e8-ae50-89f005437a21","cell_type":"markdown","source":"The behaviour of the `shutdown()` method is summarized in the following table:\n\n| `shutdown()` call | Effect |\n|---|---|\n| `shutdown(wait=True)` | Wait until all submitted functions are finished before continuing - this is the default and also what the `with` statement does. |\n| `shutdown(wait=False, cancel_futures=False)` | Return immediately and leave the submitted jobs running in the scheduler queue - used to disconnect from a running workflow. |\n| `shutdown(wait=False, cancel_futures=True)` | Cancel the submitted jobs which have not started or finished yet. |\n\nThis disconnect-and-reconnect capability is available for both the `SlurmClusterExecutor` and the `FluxClusterExecutor`, as both communicate via the file system rather than via sockets.","metadata":{}},{"id":"6842f73f-d6c4-4203-a43d-687ec97e7be7","cell_type":"markdown","source":"## Combine both\n\nWhile `SlurmClusterExecutor` submits each Python function as a separate `sbatch` job from the login node, the [HPC Job Executor](https://executorlib.readthedocs.io/en/latest/3-hpc-job.html) (`SlurmJobExecutor`) runs **inside** an already-running SLURM allocation and dispatches tasks as `srun` steps — no new jobs enter the queue.\n\n```python\nfrom executorlib import SlurmJobExecutor\n\n# This code runs inside an existing SLURM job\nwith SlurmJobExecutor(max_workers=4) as exe:\n futures = [exe.submit(sum, [i, i], resource_dict={\"cores\": 1}) for i in range(4)]\n print([f.result() for f in futures])\n```\n\nThis example is executed inside a SLURM allocation in the [HPC Job Executor](https://executorlib.readthedocs.io/en/latest/3-hpc-job.html) section. The two executor types can be nested: a function submitted via `SlurmClusterExecutor` (running as an `sbatch` job) can itself create a `SlurmJobExecutor` to parallelise sub-tasks as `srun` steps within the same allocation:","metadata":{}},{"id":"d66f03dc-8e72-4a22-8b63-f7cf15258fbf","cell_type":"code","source":"from executorlib import SlurmClusterExecutor, SlurmJobExecutor\n\ndef parallel_workflow(n):\n with SlurmJobExecutor(max_workers=n) as inner:\n futures = [inner.submit(sum, [i, i], resource_dict={\"cores\": 1}) for i in range(n)]\n return [f.result() for f in futures]\n\nwith SlurmClusterExecutor(cache_directory=\"./cache\") as outer:\n future = outer.submit(\n parallel_workflow, 2,\n resource_dict={\"cores\": 1, \"run_time_max\": 300, \"submission_template\": submission_template})\n print(future.result())","metadata":{"trusted":true,"tags":["slurm"]},"outputs":[],"execution_count":null},{"id":"9ce9bf0f-33c6-4b40-ab36-a1d0975e4d78","cell_type":"markdown","source":"The `sacct` output for such a job will show the outer `sbatch` job together with numbered `srun` steps (e.g. `12345.0`, `12345.1`, …), all completing within the same allocation.\n\n| Executor | Scheduler command | Typical use |\n|---|---|---|\n| `SlurmClusterExecutor` | `sbatch` (one job per function) | Submit from login node |\n| `SlurmJobExecutor` | `srun` steps within current job | Inside an existing allocation |\n| `FluxClusterExecutor` | `flux submit` | Flux-managed allocation or local testing |","metadata":{}},{"id":"3f47fd34-04d1-42a7-bb06-6821dc99a648","cell_type":"markdown","source":"## Cleaning Cache\nFinally, as the HPC Cluster Executors leverage the file system to communicate serialized Python functions, it is important to clean up the cache directory specified by the `cache_directory` parameter once the results of the submitted Python functions are no longer needed. The serialized Python functions are stored in binary format using the [cloudpickle](https://github.com/cloudpipe/cloudpickle) library for serialization. This format is design for caching but not for long-term storage. The user is responsible for the long-term storage of their data.","metadata":{}},{"id":"f537b4f6-cc98-43da-8aca-94a823bcbcbd","cell_type":"code","source":"import os\nimport shutil\n\nfor cache_dir in [\"./file\", \"./cache\", \"./cache_disconnect\"]:\n if os.path.exists(cache_dir):\n print(os.listdir(cache_dir))\n try:\n shutil.rmtree(cache_dir)\n except OSError:\n pass","metadata":{"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":"['add_funct144ecf19b5020fccad214df3f4bdabd0_o.h5', 'add_funct67b8245bf71c3c6dcb2018663939c72d', 'add_funct4a5d1f06cca57f0ffbaa3116d39ecc6a', 'add_functcb272924f36cbaa9ac79f8d42b6771c8_o.h5', 'calcd732cdcbd2c8e68145d99f0be814e667', '393f99f890d39348c6248689096e6efb', 'add_funct67b8245bf71c3c6dcb2018663939c72d_o.h5', 'add_funct4a5d1f06cca57f0ffbaa3116d39ecc6a_o.h5', 'calcd732cdcbd2c8e68145d99f0be814e667_o.h5', '3888b889a896c43b68f0bd924ee5285c', 'add_funct144ecf19b5020fccad214df3f4bdabd0', 'add_functcb272924f36cbaa9ac79f8d42b6771c8', 'calc_with_preloade920bec0b69f103b2579175e37aa3528_o.h5']\n"}],"execution_count":8},{"id":"3efc9f5d-fbf9-4a85-8963-5711a453130d","cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]} \ No newline at end of file diff --git a/notebooks/3-hpc-job.ipynb b/notebooks/3-hpc-job.ipynb index 7985423d..ca8d43d3 100644 --- a/notebooks/3-hpc-job.ipynb +++ b/notebooks/3-hpc-job.ipynb @@ -38,15 +38,20 @@ ] }, { - "cell_type": "markdown", - "id": "9b74944e-2ccd-4cb0-860a-d876310ea870", - "metadata": {}, + "cell_type": "code", + "execution_count": null, + "id": "dd6a748e-75b1-4c7d-9ae0-09d0b4926d51", + "metadata": { + "tags": [ + "slurm" + ], + "trusted": true + }, + "outputs": [], "source": [ - "```python\n", "with SlurmJobExecutor() as exe:\n", " future = exe.submit(sum, [1, 1])\n", - " print(future.result())\n", - "```" + " print(future.result())" ] }, { @@ -78,7 +83,9 @@ "#SBATCH --job-name={{job_name}}\n", "#SBATCH --chdir={{working_directory}}\n", "#SBATCH --get-user-env=L\n", + "{%- if partition %}\n", "#SBATCH --partition={{partition}}\n", + "{%- endif %}\n", "{%- if run_time_max %}\n", "#SBATCH --time={{ [1, run_time_max // 60]|max }}\n", "{%- endif %}\n", @@ -132,6 +139,9 @@ "execution_count": null, "id": "5802c7d7-9560-4909-9d30-a915a91ac0a1", "metadata": { + "tags": [ + "flux" + ], "trusted": true }, "outputs": [ @@ -151,6 +161,31 @@ " print(fs.result())" ] }, + { + "cell_type": "markdown", + "id": "6f3066cd-16d1-46a4-b697-102a4c04f135", + "metadata": {}, + "source": [ + "The same MPI parallel function can be executed with the `SlurmJobExecutor`. In this case the `pmi_mode` is passed to the `srun` command as `--mpi=`, for example `pmi_mode=\"pmi2\"` for MPICH:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "eaaccb1c-3014-4da7-80d5-a8eb8249a4cc", + "metadata": { + "tags": [ + "slurm" + ], + "trusted": true + }, + "outputs": [], + "source": [ + "with SlurmJobExecutor(pmi_mode=\"pmi2\") as exe:\n", + " fs = exe.submit(calc_mpi, 3, resource_dict={\"cores\": 2})\n", + " print(fs.result())" + ] + }, { "cell_type": "markdown", "id": "da862425-08b6-4ced-999f-89a74e85f410", @@ -191,6 +226,9 @@ "execution_count": null, "id": "0da13efa-1941-416f-b9e6-bba15b5cdfa2", "metadata": { + "tags": [ + "flux" + ], "trusted": true }, "outputs": [ @@ -250,6 +288,9 @@ "execution_count": null, "id": "1a2d440f-3cfc-4ff2-b74d-e21823c65f69", "metadata": { + "tags": [ + "flux" + ], "trusted": true }, "outputs": [ @@ -283,6 +324,9 @@ "execution_count": null, "id": "dcba63e0-72f5-49d1-ab04-2092fccc1c47", "metadata": { + "tags": [ + "flux" + ], "trusted": true }, "outputs": [ @@ -360,6 +404,9 @@ "execution_count": null, "id": "89b7d0fd-5978-4913-a79a-f26cc8047445", "metadata": { + "tags": [ + "flux" + ], "trusted": true }, "outputs": [ @@ -391,6 +438,9 @@ "execution_count": 13, "id": "3df0357e-d936-4989-a271-d0b03c6d0b48", "metadata": { + "tags": [ + "flux" + ], "trusted": true }, "outputs": [ @@ -426,6 +476,9 @@ "execution_count": 14, "id": "7481eb0a-a41b-4d46-bb48-b4db299fcd86", "metadata": { + "tags": [ + "flux" + ], "trusted": true }, "outputs": [ @@ -457,6 +510,9 @@ "execution_count": 15, "id": "1ee6e147-f53a-4526-8ed0-fd036f2ee6bf", "metadata": { + "tags": [ + "flux" + ], "trusted": true }, "outputs": [ @@ -505,6 +561,9 @@ } ], "metadata": { + "executorlib_ci": { + "allocation": true + }, "kernelspec": { "display_name": "Flux", "language": "python",