diff --git a/README.md b/README.md index 62f99fc4..d13db28c 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,8 @@ the features of executorlib as you need them: `asyncio` and batching in the order results arrive. 12. [Document and share a workflow](https://executorlib.readthedocs.io/en/latest/story-12-document-and-share.html) - export the workflow graph and use the cache as an audit trail. +13. [Harvest idle compute time on an overflow queue](https://executorlib.readthedocs.io/en/latest/story-13-overflow-queue-workers.html) - long-lived + worker jobs which are replaced automatically when SLURM preempts them. The cluster-specific settings like the partition, run time limits and the submission template are collected in one cell at the top of each story. Readers without access to an HPC cluster can start with @@ -235,6 +237,7 @@ as hierarchical job scheduler within the allocations. * [Large Jobs which Each Fan Out into Many Small Tasks](https://executorlib.readthedocs.io/en/latest/story-10-fan-out-inside-jobs.html) * [Adaptive Workflows](https://executorlib.readthedocs.io/en/latest/story-11-adaptive-workflows.html) * [Document and Share a Workflow](https://executorlib.readthedocs.io/en/latest/story-12-document-and-share.html) + * [Harvest Idle Compute Time with Workers on an Overflow Queue](https://executorlib.readthedocs.io/en/latest/story-13-overflow-queue-workers.html) * [Comparison](https://executorlib.readthedocs.io/en/latest/comparison.html#comparison) * [At a glace](https://executorlib.readthedocs.io/en/latest/comparison.html#at-a-glance) * [Concurrent futures](https://executorlib.readthedocs.io/en/latest/comparison.html#concurrent-futures-the-python-standard-library) diff --git a/docs/_toc.yml b/docs/_toc.yml index 4463f03a..12a76630 100644 --- a/docs/_toc.yml +++ b/docs/_toc.yml @@ -18,6 +18,7 @@ parts: - file: story-10-fan-out-inside-jobs.ipynb - file: story-11-adaptive-workflows.ipynb - file: story-12-document-and-share.ipynb + - file: story-13-overflow-queue-workers.ipynb - caption: Background chapters: - file: comparison.md diff --git a/notebooks/story-13-overflow-queue-workers.ipynb b/notebooks/story-13-overflow-queue-workers.ipynb new file mode 100644 index 00000000..4a9a2387 --- /dev/null +++ b/notebooks/story-13-overflow-queue-workers.ipynb @@ -0,0 +1,406 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Story 13: Harvest Idle Compute Time with Workers on an Overflow Queue\n", + "You have thousands of short, independent calculations - for example screening candidate structures - and no deadline.\n", + "Your cluster offers an overflow partition (also called scavenger, preemptible or low-priority partition): jobs there\n", + "run on nodes which would otherwise sit idle, often without being charged to your compute budget, but the queuing\n", + "system cancels them whenever a regular job needs the node.\n", + "\n", + "**With plain SLURM** you either submit one job per calculation - flooding the scheduler and paying the queuing and\n", + "Python start-up time for every short calculation - or you write your own worker script which pulls calculations from\n", + "a shared list. Then you also have to find out which calculations were lost when a worker was preempted, and resubmit\n", + "both the workers and the lost calculations by hand.\n", + "\n", + "**With executorlib** the `SlurmClusterExecutor` with `block_allocation=True` submits `max_workers` long-lived workers\n", + "as SLURM jobs and streams your function calls to them. With `restart_limit` the executor watches its workers: when a\n", + "worker job is cancelled, the call it was executing goes back into the queue and a replacement worker job is submitted,\n", + "so the number of workers stays constant while you keep submitting calculations.\n", + "\n", + "This notebook runs on the **login node** of a SLURM cluster." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Cluster-specific settings\n", + "**Adapt the following cell to your cluster.** It collects everything which depends on the cluster rather than on your science. The values below are the ones used to test this notebook on a single-node SLURM test cluster. The submission template is a [Jinja2](https://jinja.palletsprojects.com) template which executorlib renders for every worker job: add the lines your cluster requires, for example `#SBATCH --account=` or `module load ...` commands before `{{command}}`. The [executorlib-cluster-setup](https://executorlib.readthedocs.io/en/latest/2-hpc-cluster.html#setup-with-claude-code) skill for Claude Code can analyse your cluster and generate a tested template.\n", + "\n", + "Two lines matter for this story:\n", + "\n", + "* `#SBATCH --partition=` selects the overflow partition. The test cluster only has a single partition, so the\n", + " line is disabled with a second `#` below. `sinfo` lists the partitions of your cluster.\n", + "* `#SBATCH --no-requeue`: depending on the cluster configuration (`PreemptMode=REQUEUE`), SLURM puts a preempted job\n", + " back into the queue under the same job ID instead of cancelling it. executorlib would then still consider the worker\n", + " alive and wait for the result of the interrupted call. With `--no-requeue` a preempted worker job ends, and\n", + " executorlib submits the replacement itself.\n", + "\n", + "`max_workers` is the number of worker jobs executorlib keeps in the queue. The test cluster provides 2 CPU cores, so\n", + "two workers with one core each fit on it." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "tags": [ + "parameters" + ] + }, + "outputs": [], + "source": [ + "# Cluster-specific settings - adapt these values to your cluster.\n", + "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\n", + "#SBATCH --ntasks={{cores}}\n", + "#SBATCH --no-requeue\n", + "##SBATCH --partition=overflow\n", + "{%- if run_time_max %}\n", + "#SBATCH --time={{ [1, run_time_max // 60]|max }}\n", + "{%- endif %}\n", + "\n", + "{{command}}\n", + "\"\"\"\n", + "max_workers = 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Step 1: Start the workers\n", + "`screen()` stands in for one short calculation. Besides its result it returns the ID of the SLURM job which executed\n", + "it - every worker is a SLURM job, so the environment variable `SLURM_JOB_ID` tells which worker did the work.\n", + "`show_queue()` lists your jobs in the SLURM queue." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import getpass\n", + "import os\n", + "import subprocess\n", + "import time\n", + "\n", + "\n", + "def screen(candidate):\n", + " # Stand-in for a short calculation, e.g. screening one candidate structure.\n", + " import os\n", + " import time\n", + "\n", + " time.sleep(1)\n", + " return {\"candidate\": candidate, \"score\": candidate**2 % 7, \"slurm_job_id\": os.environ[\"SLURM_JOB_ID\"]}\n", + "\n", + "\n", + "def show_queue():\n", + " print(\n", + " subprocess.run(\n", + " [\"squeue\", \"--user\", getpass.getuser(), \"--format\", \"%.10i %.30j %.10T %.10M\"],\n", + " capture_output=True,\n", + " text=True,\n", + " ).stdout\n", + " )\n", + "\n", + "\n", + "def wait_for_job_to_end(job_id, timeout=120):\n", + " # Wait until SLURM no longer lists the job, i.e. the cancelled worker is gone.\n", + " for _ in range(timeout):\n", + " output = subprocess.run(\n", + " [\"squeue\", \"--noheader\", \"--jobs\", str(job_id), \"--format\", \"%T\"],\n", + " capture_output=True,\n", + " text=True,\n", + " ).stdout.strip()\n", + " if output == \"\":\n", + " return\n", + " time.sleep(1)\n", + " raise TimeoutError(f\"SLURM job {job_id} did not end within {timeout} seconds.\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "With `block_allocation=True` the `SlurmClusterExecutor` submits `max_workers` worker jobs, each with the resources\n", + "defined in the `resource_dict` of the executor - here one core and a maximum run time of ten minutes, which the\n", + "template converts to `#SBATCH --time`. A short run time limit helps on an overflow partition, as the scheduler can\n", + "fit short jobs into gaps between regular jobs. The function calls are then sent to the running workers, instead of\n", + "submitting one job per call.\n", + "\n", + "`restart_limit` is the number of replacement jobs executorlib submits for each worker. For harvesting idle compute\n", + "time over hours or days, choose it large enough to cover the expected number of preemptions.\n", + "\n", + "Instead of a `with` statement the executor is assigned to a variable, so it stays open over the following cells and is\n", + "shut down explicitly at the end of this notebook." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import pandas\n", + "from executorlib import SlurmClusterExecutor\n", + "\n", + "cache_directory = os.path.abspath(\"story13_cache\")\n", + "\n", + "exe = SlurmClusterExecutor(\n", + " max_workers=max_workers,\n", + " block_allocation=True,\n", + " restart_limit=10,\n", + " cache_directory=cache_directory,\n", + " resource_dict={\"cores\": 1, \"run_time_max\": 600, \"submission_template\": submission_template},\n", + ")\n", + "future_lst = [exe.submit(screen, candidate) for candidate in range(8)]\n", + "df = pandas.DataFrame([future.result() for future in future_lst])\n", + "df" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Eight calls, but only two SLURM job IDs: the two workers executed all calls. Both worker jobs keep running and wait\n", + "for the next calls:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "show_queue()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Step 2: A worker is preempted while it waits for work\n", + "On an overflow partition, SLURM cancels a worker whenever a regular job needs its node. `scancel` simulates this\n", + "preemption for one of the two workers - while it is idle, between two calls." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "preempted_job_id = df[\"slurm_job_id\"].iloc[0]\n", + "subprocess.run([\"scancel\", preempted_job_id], check=True)\n", + "wait_for_job_to_end(job_id=preempted_job_id)\n", + "show_queue()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Only one worker is left in the queue. The executor notices the cancelled worker as soon as it tries to send the next\n", + "call to it: the call goes back into the queue of the executor and a replacement worker job is submitted. You keep\n", + "submitting calls as before:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "future_lst = [exe.submit(screen, candidate) for candidate in range(8, 20)]\n", + "df = pandas.DataFrame([future.result() for future in future_lst])\n", + "print(\"preempted worker:\", preempted_job_id)\n", + "df.groupby(\"slurm_job_id\")[\"candidate\"].apply(list)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The preempted job ID no longer appears: the calls were executed by the remaining worker and by the replacement worker,\n", + "which has a new SLURM job ID. Two workers are in the queue again:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "show_queue()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Step 3: A worker is preempted in the middle of a calculation\n", + "The more expensive case: the worker is cancelled while it executes a call. To follow the attempts, `long_screen()`\n", + "appends the ID of the SLURM job which executes it to a log file before it starts its ten second calculation. As soon\n", + "as the first attempt is running, its worker is cancelled with `scancel`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "attempt_log_file = os.path.abspath(\"story13_attempts.log\")\n", + "\n", + "\n", + "def long_screen(candidate, log_file):\n", + " # Stand-in for a longer calculation, which records every attempt to execute it.\n", + " import os\n", + " import time\n", + "\n", + " with open(log_file, \"a\") as f:\n", + " f.write(os.environ[\"SLURM_JOB_ID\"] + \"\\n\")\n", + " time.sleep(10)\n", + " return {\"candidate\": candidate, \"score\": candidate**2 % 7, \"slurm_job_id\": os.environ[\"SLURM_JOB_ID\"]}\n", + "\n", + "\n", + "future = exe.submit(long_screen, 42, attempt_log_file)\n", + "while not os.path.exists(attempt_log_file):\n", + " time.sleep(1)\n", + "with open(attempt_log_file) as f:\n", + " preempted_job_id = f.read().split()[0]\n", + "subprocess.run([\"scancel\", preempted_job_id], check=True)\n", + "print(\"preempted worker:\", preempted_job_id)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The future does not fail. The executor notices that the worker executing the call was cancelled, puts the call back\n", + "into its queue and submits a replacement worker. The call is executed again from the beginning - by the other worker\n", + "or by the replacement worker, whichever is ready first:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print(future.result())\n", + "with open(attempt_log_file) as f:\n", + " print(\"attempts executed by the SLURM jobs:\", f.read().split())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The log file shows two attempts in two different SLURM jobs. The work of the interrupted attempt is lost, so on an\n", + "overflow partition:\n", + "\n", + "* **Keep the individual calls short.** A preemption costs at most the run time of the interrupted call. Split long\n", + " calculations into shorter calls, or write checkpoints from within your function and continue from the last\n", + " checkpoint when the call is executed again.\n", + "* **Make the calls safe to repeat.** An interrupted call is executed again from the beginning, so it should not, for\n", + " example, append to a file which it does not clean up first.\n", + "\n", + "## Step 4: When the restart limit is reached\n", + "Each worker counts its own replacement jobs. Once a worker was cancelled more often than `restart_limit` allows, it is\n", + "not replaced anymore and its calls are handed to the remaining workers. When the last worker gives up, the futures of\n", + "the remaining calls fail with an `ExecutorlibSocketError`, so a workflow never waits forever.\n", + "\n", + "Things to keep in mind for long harvesting campaigns:\n", + "\n", + "* **The executor resubmits the workers.** The Python process which created the executor - here this notebook on the\n", + " login node - has to keep running. Use a `tmux` or `screen` session on the login node for campaigns which run for\n", + " days.\n", + "* **Completed results are cached.** With a `cache_directory` the result of every call is stored on the file system.\n", + " If the Python process on the login node stops, submitting the same calls again loads the completed results from the\n", + " cache and only executes the missing ones.\n", + "* **The `init_function` runs once per worker job.** An expensive setup which is loaded with an `init_function` (see\n", + " [Story 9](story-9-expensive-setup-once.ipynb)) is loaded again in every replacement worker. Note that the\n", + " `init_function` and the `cache_directory` should not be combined, as the cache key does not include the state set by\n", + " the `init_function`.\n", + "\n", + "## Shut down the workers\n", + "`shutdown()` waits for all submitted calls, stops the workers and cancels their SLURM jobs:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "exe.shutdown(wait=True)\n", + "time.sleep(5)\n", + "show_queue()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Clean up" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import shutil\n", + "\n", + "shutil.rmtree(cache_directory, ignore_errors=True)\n", + "if os.path.exists(attempt_log_file):\n", + " os.remove(attempt_log_file)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## What you learned\n", + "* `SlurmClusterExecutor(block_allocation=True, max_workers=n)` submits `n` long-lived worker jobs and streams the\n", + " function calls to them - one SLURM job per worker instead of one per call.\n", + "* `restart_limit` replaces workers which are cancelled by SLURM, for example on a preemptible overflow partition. A\n", + " call which was interrupted is executed again by another worker, so its future does not fail.\n", + "* Add `#SBATCH --no-requeue` to the submission template, so SLURM cancels preempted worker jobs instead of requeueing\n", + " them under the same job ID.\n", + "* Keep the calls short and safe to repeat, as an interrupted call is executed again from the beginning.\n", + "\n", + "Compared to the other modes: in [Story 9](story-9-expensive-setup-once.ipynb) the `SlurmJobExecutor` starts the\n", + "workers with `srun` inside an allocation you already hold, while here every worker is a SLURM job of its own, which\n", + "the scheduler can place on idle nodes independently. Without `block_allocation`, the `SlurmClusterExecutor` submits\n", + "one SLURM job per call (see [Story 1](story-1-submit-and-reconnect.ipynb)).\n", + "\n", + "**Reference:** [HPC Cluster Executor](https://executorlib.readthedocs.io/en/latest/2-hpc-cluster.html), [block allocation](https://executorlib.readthedocs.io/en/latest/1-single-node.html#block-allocation)\n", + "and the [resource dictionary](https://executorlib.readthedocs.io/en/latest/trouble_shooting.html#resource-dictionary)." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +}