Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions autofit/campaign/scheduler/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ class SubmitRequest:
env: Dict[str, str] = field(default_factory=dict)
after: Dict[str, str] = field(default_factory=dict)
log_dir: Optional[str] = None
cache_root: Optional[str] = None

@property
def task_ids(self) -> List[int]:
Expand Down
41 changes: 41 additions & 0 deletions autofit/campaign/scheduler/slurm.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
partition: CPU-only work never goes on a GPU partition.
"""
import logging
import re
import shlex
import subprocess
from typing import Callable, Dict, List, Optional, Sequence
Expand Down Expand Up @@ -46,6 +47,45 @@ def _export(key: str, value: str) -> str:
return f"export {key}={shlex.quote(value)}"


# Where a job's temp files and tool caches go when the campaign names a ``cache_root``.
# On many clusters (RAL: every compute node) $HOME and /tmp sit on a small local OS
# disk that compute nodes do not share with the login node; pip, matplotlib, numba,
# CUDA/Triton, astropy, the PyAutoNerves JAX compile cache and Python's tempfile all
# default there and can fill it and crash the node (RAL admin, 2026-09-25 and
# 2026-11-12). Values are relative to ``cache_root``.
CACHE_DIRS = (
("TMPDIR", "tmp"),
("XDG_CACHE_HOME", ".cache"),
("PIP_CACHE_DIR", ".cache/pip"),
("MPLCONFIGDIR", ".cache/matplotlib"),
("NUMBA_CACHE_DIR", ".cache/numba"),
("CUDA_CACHE_PATH", ".cache/nv"),
("TRITON_CACHE_DIR", ".cache/triton"),
("ASTROPY_CACHE_DIR", ".cache/astropy"),
("JAX_COMPILATION_CACHE_DIR", ".cache/pyauto_jax"),
)


def _cache_exports(cache_root: str) -> List[str]:
"""
Fill-if-unset exports sending temp files and caches under ``cache_root``.

A value already in the job's environment (for example from the submitting shell)
wins. ``JAX_COMPILATION_CACHE_DIR`` uses ``${VAR-...}`` so an explicitly empty value
still disables the JAX cache. A stage's own ``env`` is exported afterwards and so
overrides these.
"""
root = cache_root.rstrip("/") or "/"
lines = []
for key, relative in CACHE_DIRS:
operator = "-" if key == "JAX_COMPILATION_CACHE_DIR" else ":-"
# The default sits inside "${...}", so escape for a double-quoted context.
path = re.sub(r'([\\"$`])', r"\\\1", f"{root}/{relative}")
lines.append(f'export {key}="${{{key}{operator}{path}}}"')
lines.append('mkdir -p "$TMPDIR" "$XDG_CACHE_HOME" 2>/dev/null || true')
return lines


def sbatch_script(request: SubmitRequest) -> str:
"""
The batch script of one array.
Expand Down Expand Up @@ -99,6 +139,7 @@ def sbatch_script(request: SubmitRequest) -> str:
lines += [
"",
"set -euo pipefail",
*(_cache_exports(request.cache_root) if request.cache_root else []),
*(_export(key, value) for key, value in env.items()),
'export CAMPAIGN_INDEX=$((CAMPAIGN_OFFSET + SLURM_ARRAY_TASK_ID))',
f"cd {shlex.quote(str(request.project_root))}",
Expand Down
7 changes: 7 additions & 0 deletions autofit/campaign/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
manifest_fields: [sample, tile] # optional names for a line's fields
chunk: 1000 # tasks per array, ≤ the site's max_array_size
site: ral # autonerves site layer
cache_root: /mnt/ral/jnightin # optional: TMPDIR + caches go here
scheduler: slurm # slurm (default) or local
status_root: output # where fits write *.status.json
log_dir: hpc/logs
Expand Down Expand Up @@ -59,6 +60,7 @@
"manifest_separator",
"chunk",
"site",
"cache_root",
"scheduler",
"status_root",
"log_dir",
Expand Down Expand Up @@ -185,6 +187,7 @@ def __init__(self, raw: Dict, source: Optional[Path] = None):
self.manifest_separator = raw.get("manifest_separator")
self.chunk = raw.get("chunk")
self.site_name = raw.get("site")
self.cache_root = raw.get("cache_root")
self.scheduler = raw.get("scheduler", "slurm")
self.status_root = raw.get("status_root", "output")
self.log_dir = raw.get("log_dir", "hpc/logs")
Expand Down Expand Up @@ -387,6 +390,10 @@ def validate(self) -> List[str]:
errors.append(f"scheduler: {self.scheduler!r} is not one of {sorted(SCHEDULERS)}")
if self.chunk is not None and (not isinstance(self.chunk, int) or self.chunk < 1):
errors.append(f"chunk: must be a positive integer, not {self.chunk!r}")
if self.cache_root is not None and (
not isinstance(self.cache_root, str) or not self.cache_root.startswith("/")
):
errors.append(f"cache_root: must be an absolute path, not {self.cache_root!r}")

site = None
if self.site_name:
Expand Down
1 change: 1 addition & 0 deletions autofit/campaign/submit.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ def requests_for(
manifest=str(campaign.path(campaign.manifest_path)),
env=dict(stage.env),
log_dir=campaign.log_dir,
cache_root=campaign.cache_root,
)
)
return requests
Expand Down
54 changes: 54 additions & 0 deletions test_autofit/campaign/test_slurm.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,60 @@ def test_sbatch_script():
assert "--gres" not in script


def test_sbatch_script_without_cache_root_sets_no_cache_variables():
script = sbatch_script(_request())
assert "TMPDIR" not in script
assert "XDG_CACHE_HOME" not in script


def test_sbatch_script_cache_root_exports_fill_if_unset():
request = _request()
request.cache_root = "/mnt/ral/x/"
lines = sbatch_script(request).splitlines()
for line in [
'export TMPDIR="${TMPDIR:-/mnt/ral/x/tmp}"',
'export XDG_CACHE_HOME="${XDG_CACHE_HOME:-/mnt/ral/x/.cache}"',
'export NUMBA_CACHE_DIR="${NUMBA_CACHE_DIR:-/mnt/ral/x/.cache/numba}"',
# "-" not ":-": an explicitly empty value still disables the JAX cache.
'export JAX_COMPILATION_CACHE_DIR="${JAX_COMPILATION_CACHE_DIR-/mnt/ral/x/.cache/pyauto_jax}"',
'mkdir -p "$TMPDIR" "$XDG_CACHE_HOME" 2>/dev/null || true',
]:
assert line in lines, line
# After `set -euo pipefail` and before the stage env, so a stage env value wins.
assert lines.index("set -euo pipefail") < lines.index('export TMPDIR="${TMPDIR:-/mnt/ral/x/tmp}"')
assert lines.index('export TMPDIR="${TMPDIR:-/mnt/ral/x/tmp}"') < lines.index("export NAME='a b'")


def _cache_env(tmp_path, cache_root, environment):
"""Run the cache block of a generated script under bash; return its TMPDIR and JAX cache."""
import shutil

if shutil.which("bash") is None:
pytest.skip("needs bash")
request = _request()
request.cache_root = cache_root
request.env = {}
script = sbatch_script(request).split("export PYTHONUNBUFFERED", 1)[0]
script += 'printf "%s\\n%s" "$TMPDIR" "${JAX_COMPILATION_CACHE_DIR-unset}"'
completed = subprocess.run(
["bash", "-c", script], env=environment, capture_output=True, text=True, check=True
)
return completed.stdout.split("\n")


def test_sbatch_script_cache_block_runs_under_bash(tmp_path):
root = str(tmp_path / "a b$c")
tmpdir, jax = _cache_env(tmp_path, root, {"PATH": "/usr/bin:/bin"})
assert tmpdir == f"{root}/tmp"
assert jax == f"{root}/.cache/pyauto_jax"
assert (tmp_path / "a b$c" / "tmp").is_dir()
# The job's own environment wins; an explicitly empty JAX cache stays empty.
tmpdir, jax = _cache_env(
tmp_path, root, {"PATH": "/usr/bin:/bin", "TMPDIR": "/scratch", "JAX_COMPILATION_CACHE_DIR": ""}
)
assert (tmpdir, jax) == ("/scratch", "")


def _run_generated_script(tmp_path, fit_body, signal_usr1):
"""Run the generated batch script under bash, with a stand-in fit."""
import os
Expand Down
7 changes: 7 additions & 0 deletions test_autofit/campaign/test_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,13 @@ def test_unknown_retry_class(tmp_path):
assert "unknown failure class 'segfault'" in _errors(tmp_path, "retry: {{timeout", "retry: {{segfault: none, timeout")


def test_cache_root(tmp_path):
path = write_campaign(tmp_path / "p", CAMPAIGN.replace("site: ral\n", "site: ral\ncache_root: /mnt/ral/x\n"))
assert Campaign.load(path).cache_root == "/mnt/ral/x"
assert Campaign.load(write_campaign(tmp_path / "q")).cache_root is None
assert "cache_root: must be an absolute path" in _errors(tmp_path, "site: ral\n", "site: ral\ncache_root: scratch\n")


def test_cycle(tmp_path):
text = CAMPAIGN.replace(" script: scripts/fit.py --stage=vis_lp", " after: {{sed: aftercorr}}\n script: scripts/fit.py --stage=vis_lp")
message = _errors(tmp_path, CAMPAIGN, text)
Expand Down
8 changes: 8 additions & 0 deletions test_autofit/campaign/test_submit.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,11 @@ def test_dry_run(campaign_file):
assert "#SBATCH --dependency=aftercorr:<vis_lp@4>" in entries[4]["script"]
assert entries[0]["lint"] == "ok"
assert not campaign.directory.exists()


def test_dry_run_carries_cache_root(tmp_path):
from test_autofit.campaign.conftest import CAMPAIGN, write_campaign

path = write_campaign(tmp_path / "p", CAMPAIGN.replace("site: ral\n", "site: ral\ncache_root: /mnt/ral/x\n"))
entries = submit(Campaign.load(path), None, dry_run=True)
assert 'export TMPDIR="${TMPDIR:-/mnt/ral/x/tmp}"' in entries[0]["script"].splitlines()
Loading