8000 Add Della self-hosted CI and restore notebook test coverage by davidt0x · Pull Request #621 · brainiak/brainiak · GitHub
[go: up one dir, main page]

Skip to content
Draft
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
2 changes: 2 additions & 0 deletions .conda/meta.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ test:
source_files:
- tests
- pyproject.toml
- .github/scripts
- docs/examples/fcma/FCMA_script
imports:
- brainiak
commands:
Expand Down
396 changes: 396 additions & 0 deletions .github/DELLA_RUNNER.md

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions .github/actionlint.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
self-hosted-runner:
labels:
- brainiak-della
23 changes: 23 additions & 0 deletions .github/della-runner.service
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
[Unit]
Description=BrainIAK GitHub Actions runner on della-rse
After=network.target

[Service]
ExecStart=/scratch/gpfs/CSES/dmturner/brainiak_tests/actions-runner-brainiak/run.sh
WorkingDirectory=/scratch/gpfs/CSES/dmturner/brainiak_tests/actions-runner-brainiak
Environment=BRAINIAK_TEST_ROOT=/scratch/gpfs/CSES/dmturner/brainiak_tests
Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin
Environment=TMPDIR=/scratch/gpfs/CSES/dmturner/brainiak_tests/tmp
Environment=XDG_CACHE_HOME=/scratch/gpfs/CSES/dmturner/brainiak_tests/cache
UMask=0077
Restart=always
RestartSec=10
# Stop all workers and notebook kernels when the service is stopped.
KillMode=control-group
TimeoutStopSec=90
Nice=10
# della-run.py applies CPU affinity, timeouts and sampled memory budgets.
# No CPU delegation or lingering checks are needed to start this service.

[Install]
WantedBy=default.target
13 changes: 13 additions & 0 deletions .github/scripts/della-mpiexec.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
# pytest's MPI plugin appends -n <ranks> and the Python command.
# Keep MPI on this node and preserve the launcher's inherited CPU affinity.
set -euo pipefail
: "${BRAINIAK_TEST_CPUS:?Run through della-run.py}"
if [[ ${1:-} != -n || ! ${2:-} =~ ^[12]$ || $2 -gt $BRAINIAK_TEST_CPUS ]]; then
echo 'Della MPI tests must request at most two local ranks' >&2
exit 2
fi
# The verified module is Open MPI. Disable scheduler discovery and network
# transports: both ranks communicate locally, without a SLURM allocation.
exec mpiexec --host "localhost:$BRAINIAK_TEST_CPUS" --bind-to none \
--mca ras ^slurm --mca plm isolated --mca pml ob1 --mca btl self,vader "$@"
192 changes: 192 additions & 0 deletions .github/scripts/della-run.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
#!/usr/bin/env python3
"""Supervise one local Della test run using only Python's standard library.

CPU affinity is inherited by builds, MPI ranks and notebook kernels. Aggregate
RSS is sampled, so the memory budget is a termination threshold, not a cgroup
hard limit. Linux subreaping lets cleanup find orphaned notebook kernels,
including those that create their own sessions.
"""

import argparse
import ctypes
import fcntl
import json
import logging
import os
from pathlib import Path
import resource
import signal
import subprocess
import time


# CPUs, RSS budget in GiB, wall time in seconds (including installation).
PROFILES = {
"smoke": (1, 8, 20 * 60),
"notebooks": (2, 32, 3 * 60 * 60),
"unit": (2, 32, 3 * 60 * 60),
"all": (2, 32, 3 * 60 * 60),
}
LOG = logging.getLogger("della-run")


def descendants(parent):
"""Find descendants, including children launched from worker threads."""
found = set()
pending = [parent]
while pending:
pid = pending.pop()
for children in Path(f"/proc/{pid}/task").glob("*/children"):
try:
pids = {int(value) for value in children.read_text().split()}
except (FileNotFoundError, ProcessLookupError):
continue
pending.extend(pids - found)
found.update(pids)
return found


def send(pid, signum):
try:
os.kill(pid, signum)
except ProcessLookupError:
pass


def cleanup():
"""Terminate our descendants, including kernels in separate sessions."""
parent = os.getpid()
pids = descendants(parent)
for pid in pids:
send(pid, signal.SIGTERM)
deadline = time.monotonic() + 2
while descendants(parent) and time.monotonic() < deadline:
# Reap adopted children, including any command already waited by Popen.
try:
while os.waitpid(-1, os.WNOHANG)[0]:
pass
except ChildProcessError:
return
time.sleep(0.05)
# Stop parents before the final scan so they cannot spawn more children.
stopped = set()
while True:
remaining = descendants(parent) - stopped
if not remaining:
break
for pid in remaining:
send(pid, signal.SIGSTOP)
stopped.update(remaining)
for pid in stopped:
send(pid, signal.SIGKILL)
deadline = time.monotonic() + 1
while time.monotonic() < deadline:
try:
if not os.waitpid(-1, os.WNOHANG)[0]:
time.sleep(0.05)
except ChildProcessError:
break


def supervise(command, *, cpus, memory_bytes, wall_seconds, env):
"""Return the command status, 124 for timeout, or 137 for excess RSS."""
# PR_SET_CHILD_SUBREAPER: detached descendants reparent here, not to init.
libc = ctypes.CDLL(None, use_errno=True)
if libc.prctl(36, 1, 0, 0, 0) != 0:
raise OSError(ctypes.get_errno(), "Cannot enable child subreaping")
os.sched_setaffinity(0, cpus)
os.nice(10)
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
interrupted = 0

def stop(signum, _frame):
nonlocal interrupted
interrupted = 128 + signum

for signum in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
signal.signal(signum, stop)
deadline = time.monotonic() + wall_seconds
peak_rss = 0
page_size = os.sysconf("SC_PAGE_SIZE")
try:
process = subprocess.Popen(command, env=env, start_new_session=True)
while True:
if interrupted:
return interrupted
status = process.poll()
if status is not None:
return status if status >= 0 else 128 - status
if time.monotonic() >= deadline:
LOG.error("Wall time limit exceeded")
return 124
rss = 0
for pid in descendants(os.getpid()):
try:
rss += int(Path(f"/proc/{pid}/statm").read_text()
.split()[1]) * page_size
except (FileNotFoundError, ProcessLookupError):
continue
peak_rss = max(peak_rss, rss)
if rss > memory_bytes:
LOG.error("Memory budget exceeded: %.2f GiB", rss / 2**30)
return 137
time.sleep(0.25)
finally:
cleanup()
LOG.info("Peak sampled aggregate RSS: %.2f GiB", peak_rss / 2**30)


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("suite", choices=PROFILES, nargs="?", default="smoke")
args = parser.parse_args()
logging.basicConfig(level=logging.INFO,
format="%(levelname)s: %(message)s")
root = Path(os.environ["BRAINIAK_TEST_ROOT"]).resolve(strict=True)
run_id = os.environ["GITHUB_RUN_ID"]
attempt = os.environ["GITHUB_RUN_ATTEMPT"]
if not run_id.isdecimal() or not attempt.isdecimal():
parser.error("Run ID and attempt must be numeric")
count, gib, seconds = PROFILES[args.suite]
available = os.sched_getaffinity(0)
requested = os.environ.get("DELLA_CPUS", "")
try:
candidates = ({int(cpu) for cpu in requested.split(",")} if requested
else available)
except ValueError:
parser.error("DELLA_CPUS must be comma-separated numeric CPU IDs")
if not candidates <= available or len(candidates) < count:
parser.error("DELLA_CPUS must provide enough CPUs in current affinity")
cpus = sorted(candidates)[:count]

# Acquire before creating reports or touching the shared environment/cache.
with (root / "run.lock").open("w") as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
LOG.error("Another Della test run holds the lock")
return 1
run_dir = root / "runs" / f"{run_id}-{attempt}"
reports = run_dir / "reports"
reports.mkdir(parents=True, exist_ok=True)
logging.getLogger().addHandler(
logging.FileHandler(reports / "run.log"))
(reports / "limits.json").write_text(json.dumps({
"suite": args.suite, "cpus": cpus,
"rss_budget_gib": gib, "wall_seconds": seconds,
}, indent=2) + "\n")
env = dict(os.environ, BRAINIAK_RUN_DIR=str(run_dir),
BRAINIAK_TEST_CPUS=str(count))
script = Path(__file__).with_name("della-test.sh")
LOG.info("Running %s on CPUs %s; RSS budget %s GiB; timeout %ss",
args.suite, cpus, gib, seconds)
result = supervise(["bash", str(script), args.suite], cpus=cpus,
memory_bytes=gib * 2**30, wall_seconds=seconds,
env=env)
LOG.info("Test command exit status: %s", result)
return result


if __name__ == "__main__":
os.umask(0o077)
raise SystemExit(main())
88 changes: 88 additions & 0 deletions .github/scripts/della-test.sh
10BC8
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
#!/usr/bin/env bash
# Run through della-run.py to bound local builds and tests.
set -euo pipefail
umask 077
: "${BRAINIAK_TEST_CPUS:?Run through della-run.py}"
: "${BRAINIAK_TEST_ROOT:?}"
: "${BRAINIAK_RUN_DIR:?}"
: "${DELLA_MODULES:?Set compiler and MPI modules for the current Della system}"

# Noninteractive shells do not automatically initialize environment modules.
# shellcheck source=/dev/null
source /etc/profile.d/modules.sh
module purge
read -r -a modules <<< "$DELLA_MODULES"
module load "${modules[@]}"
command -v uv mpicc mpiexec
export MPICC
MPICC=$(command -v mpicc)

export TMPDIR="$BRAINIAK_RUN_DIR/tmp"
export XDG_CACHE_HOME="$BRAINIAK_TEST_ROOT/cache"
export UV_CACHE_DIR="$XDG_CACHE_HOME/uv"
export UV_PYTHON_INSTALL_DIR="$BRAINIAK_TEST_ROOT/python"
export UV_PROJECT_ENVIRONMENT="$BRAINIAK_TEST_ROOT/venv"
export UV_PYTHON=3.12
export UV_LINK_MODE=copy
export JUPYTER_CONFIG_DIR="$BRAINIAK_RUN_DIR/jupyter/config"
export JUPYTER_DATA_DIR="$BRAINIAK_RUN_DIR/jupyter/data"
export JUPYTER_RUNTIME_DIR="$BRAINIAK_RUN_DIR/jupyter/runtime"
export IPYTHONDIR="$BRAINIAK_RUN_DIR/ipython"
export MPLCONFIGDIR="$BRAINIAK_RUN_DIR/matplotlib"
export NUMBA_CACHE_DIR="$BRAINIAK_TEST_ROOT/cache/numba"
export NILEARN_DATA="$BRAINIAK_TEST_ROOT/notebooks/nilearn_data"
export CUDA_VISIBLE_DEVICES=-1
export OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1
export NUMEXPR_NUM_THREADS=1 TF_NUM_INTRAOP_THREADS=1 TF_NUM_INTEROP_THREADS=1
export CMAKE_BUILD_PARALLEL_LEVEL="$BRAINIAK_TEST_CPUS" UV_CONCURRENT_BUILDS=1
export BRAINIAK_MPIEXEC="$GITHUB_WORKSPACE/.github/scripts/della-mpiexec.sh"
mkdir -p "$TMPDIR" "$XDG_CACHE_HOME" "$JUPYTER_RUNTIME_DIR"

uv sync --locked --extra dev --extra matnormal --extra examples \
--no-binary-package mpi4py --reinstall-package brainiak
python="$UV_PROJECT_ENVIRONMENT/bin/python"
export PATH="$UV_PROJECT_ENVIRONMENT/bin:$PATH"
"$python" -m ipykernel install --sys-prefix --name python3
"$python" -c 'import brainiak; from mpi4py import MPI; print(brainiak.__version__); print(MPI.Get_library_version())'

suite=${1:-smoke}
status=0
if [[ "$suite" == unit || "$suite" == all ]]; then
"$python" -m pytest -v tests -m 'not notebook' \
--mpiexec="$GITHUB_WORKSPACE/.github/scripts/della-mpiexec.sh" \
--basetemp="$TMPDIR/pytest-unit" \
--junitxml="$BRAINIAK_RUN_DIR/reports/unit.xml" \
> "$BRAINIAK_RUN_DIR/reports/unit.log" 2>&1 || status=1
fi
if [[ "$suite" == smoke || "$suite" == notebooks || "$suite" == all ]]; then
if [[ "$suite" != smoke ]]; then
# Reuse the existing 2025 data cache without copying gigabytes or
# overwriting its scripts. Link only known, nonempty input files.
for dataset in \
eventseg/Sherlock_AG_movie.npy eventseg/Sherlock_AG_recall.npy \
fmrisim/Corr_MVPA_archive.tar.gz \
fmrisim/Corr_MVPA/Participant_01_rest_run01.nii \
iem/RademakerEtAl2019_WM_S05_avgTime.npz \
iem/AL61_Bilat-V1_attnContrast.mat \
isc/brainiak-aperture-isc-data.tgz \
srm/brainiak-aperture-srm-data.tgz; do
cached="$BRAINIAK_TEST_ROOT/brainiak-example-data/$dataset"
target="$BRAINIAK_TEST_ROOT/notebooks/$dataset"
if [[ -s "$cached" && ! -e "$target" && ! -L "$target" ]]; then
mkdir -p "$(dirname "$target")"
ln -s "$cached" "$target"
fi
done
fi
selection=()
if [[ "$suite" == smoke ]]; then
selection=(-k iem_synthetic_RF)
fi
"$python" -m pytest -v tests/test_notebooks.py --enable_notebook_tests \
"${selection[@]}" --notebook-timeout=3600 \
--notebook-workdir="$BRAINIAK_TEST_ROOT/notebooks" \
--basetemp="$TMPDIR/pytest-notebooks" \
--junitxml="$BRAINIAK_RUN_DIR/reports/notebooks.xml" \
> "$BRAINIAK_RUN_DIR/reports/notebooks.log" 2>&1 || status=1
fi
exit "$status"
65 changes: 65 additions & 0 deletions .github/workflows/della_notebooks.yml
BEF0
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
name: Della tests

# Only trusted repository code should reach a cluster account. In particular,
# do not add pull_request or pull_request_target triggers to this workflow.
on:
workflow_dispatch:
inputs:
suite:
description: Tests to run (smoke needs no notebook datasets)
type: choice
default: smoke
options:
- smoke
- notebooks
- unit
- all

permissions:
contents: read

concurrency:
group: brainiak-della
cancel-in-progress: false

jobs:
tests:
if: github.repository == 'brainiak/brainiak'
runs-on: [self-hosted, Linux, X64, brainiak-della]
environment: della
timeout-minutes: 240
env:
BRAINIAK_TEST_ROOT: /scratch/gpfs/CSES/dmturner/brainiak_tests
DELLA_MODULES: ${{ vars.DELLA_MODULES }}
DELLA_CPUS: ${{ vars.DELLA_CPUS }}
TEST_SUITE: ${{ inputs.suite }}
defaults:
run:
shell: bash
steps:
- name: Verify runner storage before checkout
working-directory: /scratch/gpfs/CSES/dmturner/brainiak_tests
run: |
case "$(realpath "$GITHUB_WORKSPACE")" in
"$BRAINIAK_TEST_ROOT"/*) ;;
*) echo 'Runner work directory must be under BRAINIAK_TEST_ROOT' >&2; exit 1 ;;
esac
command -v python3 uv
test -n "$DELLA_MODULES" || { echo 'Set the della environment variable DELLA_MODULES' >&2; exit 1; }

- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
fetch-depth: 0
persist-credentials: false

- name: Build and test on della-rse
run: python3 .github/scripts/della-run.py "$TEST_SUITE"

- name: Upload test reports
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: della-${{ inputs.suite }}-${{ github.run_id }}-${{ github.run_attempt }}
path: /scratch/gpfs/CSES/dmturner/brainiak_tests/runs/${{ github.run_id }}-${{ github.run_attempt }}/reports/
if-no-files-found: warn
retention-days: 14
Loading
Loading
0