From 612fdd414d99dbd51a90b74d91de7ef8c0ca3120 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:29:29 +0100 Subject: [PATCH] DPL: add dpl-tune, a tuner of the runtime configuration of a workflow dpl-tune runs a workflow dumped with --dump-workflow on a few input files with --resources-monitoring, reads performanceMetrics.json and proposes --aod-memory-rate-limit, --pipeline, --readers, --timeframes-rate-limit and --shm-segment-size within a memory budget, explaining each change with the metric behind it. The tuned configuration is then run on the same inputs and backed off if it fails or is not faster. It can also tune from an existing performanceMetrics.json, e.g. from a Grid job, without running anything. Since performanceMetrics.json has no memory on macOS, the memory of every process is sampled while the workflow runs (phys_footprint on macOS, PSS from /proc on Linux). On two analysis reproducers it raised --aod-memory-rate-limit from 200 MB to about 1.1 GB and made the runs 1.6x faster on the probe inputs and 1.9x on a larger set of inputs it had not seen, within a 16 GiB budget. It changed nothing on a reconstruction workflow bound by its start-up. --readers > 1 together with --aod-memory-rate-limit deadlocks in the current O2, so a failed verification backs off the extra readers first; this guard can be switched off with --no-readers-guard. The script uses the Python standard library only. Like the other scripts in Framework/Core/scripts it is installed with pip, which provides a dpl-tune command. --- Framework/Core/scripts/dpl-tune/README.md | 105 ++ Framework/Core/scripts/dpl-tune/dpl_tune.py | 1053 +++++++++++++++++ .../Core/scripts/dpl-tune/pyproject.toml | 16 + 3 files changed, 1174 insertions(+) create mode 100644 Framework/Core/scripts/dpl-tune/README.md create mode 100755 Framework/Core/scripts/dpl-tune/dpl_tune.py create mode 100644 Framework/Core/scripts/dpl-tune/pyproject.toml diff --git a/Framework/Core/scripts/dpl-tune/README.md b/Framework/Core/scripts/dpl-tune/README.md new file mode 100644 index 0000000000000..8da1ad43e75ba --- /dev/null +++ b/Framework/Core/scripts/dpl-tune/README.md @@ -0,0 +1,105 @@ +# dpl-tune + +Tunes the runtime configuration of a DPL workflow from a short probe run. +It runs the workflow on a few input files with `--resources-monitoring`, reads +the driver's `performanceMetrics.json`, and proposes the DPL options that +should raise the throughput within a memory budget. +Python 3 standard library only. + +## What it tunes, and from which metrics + +| option | changed when | metrics used | +|---|---|---| +| `--aod-memory-rate-limit` | the devices are mostly idle and few TFs are in flight | `total-timeframes-in-flight`, `table-bytes-*-created`, `total_wall_time_ms` | +| `--pipeline dev:N` | one device is the slowest by at least 1.3x and can be pipelined | `total_wall_time_ms`, `cpuUsedAbsolute` | +| `--readers` | the AOD reader becomes the slowest device | `total_wall_time_ms`, `aod-file-read-info` | +| `--timeframes-rate-limit` | an explicit limit would cap the TFs in flight | `total-timeframes-in-flight` | +| `--shm-segment-size` | only raised, to twice the in-flight data | sampled shared memory, `arrow-bytes-delta` | + +The steady state is taken from the first to the last completed TF +(`total-timeframes-consumed`). The throughput is modelled as limited by the +slowest lane, by the CPU (CPU seconds per TF over the cores) or by the TFs in +flight (Little's law); each step is checked against the memory budget. +`tuning.md` gives each change with the numbers behind it. + +By default the tuned configuration is then run on the probe inputs +(verification). If it fails (non-zero exit, fewer TFs, a hang, memory above the +budget) the riskiest change is backed off and the run repeated; if it is not +faster, the changes are withdrawn. `--no-verify` skips this. + +## Usage + +Dump the topology with the usual command line, adding +`--dump-workflow --dump-workflow-file` to the last executable of the pipe: + +```bash +o2-analysis-a ... | o2-analysis-b ... -b --aod-file @inputs.txt \ + --dump-workflow --dump-workflow-file workflow.json +``` + +The JSON is run again by piping it into that last executable, so only that one +can be the driver (`o2-dpl-run` only if it was the last stage). + +Probe, tune and verify, for a budget of 2 GB per core on 8 cores: + +```bash +dpl-tune tune workflow.json --inputs inputs.txt --probe-files 1 \ + --mem-budget 2G --per-core --cores 8 -o out \ + [--env env.sh] [--stage configuration.json ...] [--set=--max-tf=8] [--lock FILE] +``` + +- `--env` is sourced before each run (e.g. the environment of a reproducer), + `--stage` copies files into each run directory, `--clone-dir` clones a whole directory. +- `--set=OPT=VALUE` overrides an option wherever it already appears. +- `--lock FILE` runs each DPL run under an exclusive `flock()` on FILE, waiting + while another process (e.g. `lockf` or `flock` on the same file) holds it. +- Every run uses `-b` and a fresh run directory (`out/probe`, `out/verify*`). + +Tune from an existing `performanceMetrics.json` (e.g. from a Grid job), without running: + +```bash +dpl-tune tune [workflow.json] --from-metrics performanceMetrics.json \ + [--mem-samples mem.tsv] --mem-budget 16G --cores 8 -o out \ + [--driver "exe --aod-memory-rate-limit ... --shm-segment-size ..."] +``` + +Run a topology, with or without a tuning, to compare them: + +```bash +dpl-tune run workflow.json --inputs inputs.txt --files 4 -o run-base +dpl-tune run workflow.json --inputs inputs.txt --files 4 --tuning out/tuning.json -o run-tuned +``` + +`run` writes `summary.json` (exit code, wall time, TFs, TF/s, peak memory) in the run directory. + +Install with `pip install ./Framework/Core/scripts/dpl-tune/` to get a +`dpl-tune` command, or run `python3 dpl_tune.py` directly. + +## Outputs + +- `tuning.md`: the changes with the numbers behind them, the observations, the + prediction, a per-device table. +- `tuning.json`: the same, machine readable (`knobs`, `changes`, `extra_args`, `analysis`). +- `workflow.tuned.json`: the topology with the options applied to every data processor. +- `run-tuned.sh`: the driver command running `workflow.tuned.json`. +- `probe/`, `verify*/`: the run directories (`run.log`, `performanceMetrics.json`, `mem.tsv`). + +## Limitations + +- **Memory on macOS**: `performanceMetrics.json` has no RSS/PSS on macOS, so + the memory of every process is sampled once per second (`phys_footprint`, + plus the resident size of the shared-memory segment). The sum is an upper + bound: shared pages are counted once per process touching them. On Linux PSS + is read from `/proc//smaps_rollup`, which counts them once. +- **Reconstruction**: only `--pipeline` is tuned, and only when a device is + busy most of the time. The TFs in flight, the shared memory free and the + dropped messages are not in `performanceMetrics.json`, so + `--timeframes-rate-limit` and `--shm-segment-size` cannot be tuned for + reconstruction without more metrics. +- **Readers guard**: in the O2 versions tested, `--readers` > 1 combined with + `--aod-memory-rate-limit` deadlocked (the readers wait for AOD memory offers + that never come). When a verification with both fails, the extra readers are + backed off first. `--no-readers-guard` disables this once O2 is fixed. +- The extrapolated shared memory is a lower bound; the verification run + measures the real peak against the budget. +- The output content is not compared: check it separately. diff --git a/Framework/Core/scripts/dpl-tune/dpl_tune.py b/Framework/Core/scripts/dpl-tune/dpl_tune.py new file mode 100755 index 0000000000000..0dd7363554187 --- /dev/null +++ b/Framework/Core/scripts/dpl-tune/dpl_tune.py @@ -0,0 +1,1053 @@ +#!/usr/bin/env python3 +# Copyright 2019-2026 CERN and copyright holders of ALICE O2. +# See https://alice-o2.web.cern.ch/copyright for details of the copyright holders. +# All rights not expressly granted are reserved. +# +# This software is distributed under the terms of the GNU General Public +# License v3 (GPL Version 3), copied verbatim in the file "COPYING". +# +# In applying this license CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization +# or submit itself to any jurisdiction. +"""dpl-tune: tune a DPL workflow's runtime configuration from a short probe run. + +Standard library only. Two subcommands: + + tune TOPOLOGY.json --inputs LIST --probe-files N --mem-budget 16G --cores 8 -o OUTDIR + [--env ENV.sh] [--stage FILE ...] [--clone-dir DIR] [--set OPT=VALUE ...] [--lock FILE] + [--from-metrics performanceMetrics.json [--mem-samples mem.tsv]] + Runs the topology on the first N inputs with --resources-monitoring, samples the + memory of every device, and writes OUTDIR/{tuning.json,tuning.md,workflow.tuned.json,run-tuned.sh}. + With --from-metrics no run is made: the tuning is derived from an existing performanceMetrics.json + (and, if given, a mem.tsv written by a previous dpl-tune run). + + run TOPOLOGY.json --inputs LIST --files N -o RUNDIR [--tuning OUTDIR/tuning.json] [same staging options] + Runs the topology (optionally with a tuning applied) and writes RUNDIR/summary.json + (wall time, TFs, throughput, peak memory), e.g. to compare a tuning with the baseline. + +The topology is a DPL workflow dump (--dump-workflow --dump-workflow-file F): the JSON with +"workflow", "metadata" (executable + cmdLineArgs of every data processor) and "command". It is run +by piping it into the last stage of "command" (the executable that was the driver when it was +dumped), which is what `a | b | c` does. o2-dpl-run works only when it was that last stage. + +Every DPL run is made with -b, in a fresh run directory. With --lock FILE each run first takes an +exclusive flock() on FILE, waiting while another process holds it, so that runs can be serialised +with other jobs on the same machine. +""" +import argparse +import ctypes +import ctypes.util +import fcntl +import json +import math +import os +import re +import shlex +import shutil +import subprocess +import sys +import threading +import time + +PROC = "/proc" # Linux process information +INPUT_OPTIONS = ["--aod-file", "--ctf-input"] # option carrying the input file list, first match wins +# Options that DPL requires to be identical in every sub-workflow (runDataProcessing.cxx uniformOptions): +# we set them in every metadata entry and on the driver command line. +GLOBAL_KNOBS = ["--readers", "--aod-memory-rate-limit", "--shm-segment-size", "--timeframes-rate-limit"] +NOT_PIPELINABLE = re.compile(r"^internal-dpl-|writer|sink|reader|proxy|^ctf-reader$") +# Readers guard: in the O2 versions this tool was tested with, --readers > 1 combined with +# --aod-memory-rate-limit deadlocked (every reader waits for an AOD memory offer that never comes, after +# a few TFs). With the guard on, a failed verification of a tuning containing both backs off the extra +# readers first. It can be switched off with --no-readers-guard once that is fixed in O2. +READERS_GUARD = True +GiB = 1024 ** 3 +MB = 1000 ** 2 + + +# ---------------------------------------------------------------------------------------------- +# small helpers +def parse_size(s): + m = re.fullmatch(r"\s*([0-9.]+)\s*([kKmMgGtT]?)(i?[bB])?\s*", str(s)) + if not m: + raise ValueError(f"bad size {s!r}") + mult = {"": 1, "k": 1024, "m": 1024 ** 2, "g": GiB, "t": 1024 ** 4}[m.group(2).lower()] + return int(float(m.group(1)) * mult) + + +def fmt_bytes(b): + if b is None: + return "n/a" + for unit, div in (("GiB", GiB), ("MiB", 1024 ** 2), ("KiB", 1024)): + if abs(b) >= div: + return f"{b / div:.2f} {unit}" + return f"{b:.0f} B" + + +def get_opt(args, name): + for i, a in enumerate(args): + if a == name and i + 1 < len(args): + return args[i + 1] + if a.startswith(name + "="): + return a.split("=", 1)[1] + return None + + +def del_opt(args, name, nvals=1): + out, i = [], 0 + while i < len(args): + if args[i] == name: + i += 1 + nvals + continue + if args[i].startswith(name + "="): + i += 1 + continue + out.append(args[i]) + i += 1 + return out + + +def set_opt(args, name, value): + if value is None: + return del_opt(args, name) + return del_opt(args, name) + [name, str(value)] + + +def merge_pipeline(args, pipeline): + """Merge {device: N} into the (single) --pipeline option of an argument list.""" + if not pipeline: + return args + cur = get_opt(args, "--pipeline") or "" + spec = {} + for tok in filter(None, cur.split(",")): + k, v = tok.rsplit(":", 1) + spec[k] = int(v) + spec.update(pipeline) + return set_opt(args, "--pipeline", ",".join(f"{k}:{v}" for k, v in spec.items())) + + +# ---------------------------------------------------------------------------------------------- +# topology +def load_topology(path): + with open(path) as f: + topo = json.load(f) + for k in ("workflow", "metadata"): + if k not in topo: + sys.exit(f"{path}: not a DPL workflow dump (no '{k}')") + return topo + + +def clean_args(args): + args = del_opt(args, "--dump-workflow", 0) + args = del_opt(args, "--dump", 0) + args = del_opt(args, "--dump-workflow-file") + # The no-op backend sends no metric to the driver, so performanceMetrics.json would be empty. + if get_opt(args, "--monitoring-backend") == "no-op://": + args = del_opt(args, "--monitoring-backend") + return args + + +def driver_stage(topo, override=None): + """Executable and arguments of the last stage of the dumped command (the driver).""" + if override: + toks = shlex.split(override) + else: + toks = shlex.split(topo.get("command", "")) + stages, cur = [], [] + for t in toks: + if t == "|": + stages.append(cur) + cur = [] + else: + cur.append(t) + stages.append(cur) + toks = stages[-1] + if not toks: + sys.exit("cannot find the driver stage in the topology 'command'; pass --driver") + args = clean_args(toks[1:]) + if "-b" not in args and "--batch" not in args: + args.append("-b") + return toks[0], args + + +def topology_kind(topo, dargs): + names = {m["name"] for m in topo["metadata"]} + if any(n.startswith("internal-dpl-aod-reader") for n in names) or get_opt(dargs, "--aod-file"): + return "analysis" + return "reconstruction" + + +def find_input_option(topo, dargs, explicit=None): + if explicit: + return explicit + for opt in INPUT_OPTIONS: + if get_opt(dargs, opt) is not None: + return opt + for m in topo["metadata"]: + if get_opt(m["cmdLineArgs"], opt) is not None: + return opt + return None + + +def is_source(spec): + lifetimes = {str(i.get("lifetime", "")).lower() for i in spec.get("inputs", [])} + # Lifetime.h: 1 Condition, 4 Timer, 5 Enumeration, 6 Signal, 8 OutOfBand: no timeframe data in + return not spec.get("inputs") or lifetimes <= {"1", "4", "5", "6", "8"} + + +def apply_knobs(topo, dargs, knobs, input_opt=None, input_value=None, extra=None): + """Return (topology, driver args) with the knobs applied uniformly.""" + topo = json.loads(json.dumps(topo)) + glob = dict(knobs.get("global", {})) + pipe = dict(knobs.get("pipeline", {})) + extra = extra or {} + + def fix(args): + args = clean_args(list(args)) + for k, v in glob.items(): + args = set_opt(args, k, v) + args = merge_pipeline(args, pipe) + if input_opt and input_value is not None and get_opt(args, input_opt) is not None: + args = set_opt(args, input_opt, input_value) + for k, v in extra.items(): # only where the option already exists (other executables reject it) + if get_opt(args, k) is not None: + args = set_opt(args, k, v) + return args + + for m in topo["metadata"]: + m["cmdLineArgs"] = fix(m["cmdLineArgs"]) + for w in topo["workflow"]: + if w["name"] in pipe: + w["maxInputTimeslices"] = pipe[w["name"]] + dargs = fix(dargs) + if input_opt == "--aod-file" and input_value is not None: + dargs = set_opt(dargs, input_opt, input_value) # the driver injects the AOD reader + return topo, dargs + + +# ---------------------------------------------------------------------------------------------- +# memory sampling (macOS: proc_pid_rusage phys_footprint; Linux: smaps_rollup) +class RegionInfo(ctypes.Structure): # struct proc_regioninfo, + _fields_ = [(n, ctypes.c_uint32) for n in ("prot", "maxprot", "inherit", "flags")] + [("offset", ctypes.c_uint64)] + \ + [(n, ctypes.c_uint32) for n in ("behavior", "wired", "tag", "res", "snp", "swapped", "dirtied", "ref", + "shadow", "share", "privres", "shres", "objid", "depth")] + \ + [("address", ctypes.c_uint64), ("size", ctypes.c_uint64)] + + +class MemReader: + """Memory of one process, and resident size of the shared-memory segment. + + macOS: phys_footprint (proc_pid_rusage). It charges a touched POSIX shm page to every process that + touched it, so the sum over processes is an upper bound of the physical memory (shm counted once per + process touching it). The resident size of the FairMQ segment itself (the VM object, counted once) + comes from proc_pidinfo(PROC_PIDREGIONINFO) on the large shared region; the region info is per object, + not per process, so it cannot be subtracted per process. + Linux: PSS from /proc//smaps_rollup (or the sum over /proc//smaps on kernels older than + 4.14); sum(PSS) counts shm once (proportionally): exact. + """ + SHARED_MODES = (4, 5, 7) # SM_SHARED, SM_TRUESHARED, SM_SHARED_ALIASED + + def __init__(self): + self.mac = sys.platform == "darwin" + self.page = os.sysconf("SC_PAGE_SIZE") + self.region = {} # pid -> address of its large shared region (None: none found yet) + self.tries = {} + if self.mac: + self.lib = ctypes.CDLL("/usr/lib/libSystem.dylib") + self.buf = (ctypes.c_uint64 * 64)() + + def shm_objects(self, pid): + """{object id: resident bytes} of the large shared regions mapped by pid (macOS).""" + if not self.mac: + return {} + ri = RegionInfo() + addr = self.region.get(pid) + if addr is None: + n = self.tries.get(pid, 0) + self.tries[pid] = n + 1 + if n % 10: # full scans are expensive: at most every 10th tick until found + return {} + addr, scan = 0, True + else: + scan = False + while True: + if self.lib.proc_pidinfo(ctypes.c_int(pid), ctypes.c_int(7), ctypes.c_uint64(addr), + ctypes.byref(ri), ctypes.c_int(ctypes.sizeof(ri))) <= 0: + break + if ri.size >= (256 << 20) and ri.share in self.SHARED_MODES: + self.region[pid] = ri.address + return {ri.objid: ri.res * self.page} + if not scan: + self.region[pid] = None + break + addr = ri.address + ri.size + return {} + + def read(self, pid): + """(memory bytes, rss bytes) or None.""" + if self.mac: + # struct rusage_info_v4: uint8 uuid[16], then uint64: [6] resident, [7] phys_footprint (RUSAGE_INFO_V4 = 4) + if self.lib.proc_pid_rusage(ctypes.c_int(pid), ctypes.c_int(4), ctypes.byref(self.buf)) != 0: + return None + f = list(self.buf)[2:] + return f[7], f[6] + for name in ("smaps_rollup", "smaps"): + try: + vals = {} + with open(f"{PROC}/{pid}/{name}") as fh: + for line in fh: # "Pss: 1234 kB"; summed over the mappings of smaps + p = line.split() + if len(p) >= 2 and p[0].endswith(":") and p[1].isdigit(): + vals[p[0][:-1]] = vals.get(p[0][:-1], 0) + int(p[1]) * 1024 + return vals.get("Pss", 0), vals.get("Rss", 0) + except FileNotFoundError: + continue + except OSError: + return None + return None + + +def process_table(): + """{pid: (ppid, command line)} of every process.""" + procs = {} + if sys.platform.startswith("linux"): # /proc: complete command lines, which ps may truncate + for e in filter(str.isdigit, os.listdir(PROC)): + try: + with open(f"{PROC}/{e}/stat") as f: + stat = f.read() + with open(f"{PROC}/{e}/cmdline", "rb") as f: + cmd = f.read().rstrip(b"\0").replace(b"\0", b" ").decode(errors="replace") + except (OSError, ValueError): + continue # not a process, or gone + # "pid (comm) state ppid ...": comm may contain spaces and parentheses + procs[int(e)] = (int(stat[stat.rindex(")") + 2:].split()[1]), cmd or "[kernel]") + return procs + out = subprocess.run(["ps", "-axo", "pid=,ppid=,command="], capture_output=True, text=True).stdout + for line in out.splitlines(): + p = line.strip().split(None, 2) + if len(p) == 3: + procs[int(p[0])] = (int(p[1]), p[2]) + return procs + + +def descendants(procs, root): + kids = {} + for pid, (ppid, _) in procs.items(): + kids.setdefault(ppid, []).append(pid) + out, todo = [], [root] + while todo: + p = todo.pop() + for c in kids.get(p, []): + out.append(c) + todo.append(c) + return out + + +class Sampler(threading.Thread): + def __init__(self, root_pid, path, interval=1.0): + super().__init__(daemon=True) + self.root, self.path, self.interval = root_pid, path, interval + self.stop = threading.Event() + self.mem = MemReader() + self.peak_total = 0 # max over ticks of sum(private) + shm + self.peak_private = 0 + self.peak_shm = 0 + self.peak_total_rss = 0 + + def run(self): + with open(self.path, "w") as out: + out.write("t\tpid\tdevice\tprivate\trss\tshm\n") + while not self.stop.is_set(): + t = time.time() + procs = process_table() + tot = tot_rss = 0 + shm = {} + for pid in descendants(procs, self.root): + cmd = procs[pid][1] + exe = os.path.basename(cmd.split()[0]) + if exe in ("bash", "sh", "ps"): + continue + m = re.search(r"--id (\S+)", cmd) + dev = m.group(1) if m else "driver" + r = self.mem.read(pid) + if not r: + continue + priv, rss = r + tot += priv + tot_rss += rss + if not shm and dev != "driver": # one process mapping the segment is enough + shm = self.mem.shm_objects(pid) + out.write(f"{t:.3f}\t{pid}\t{dev}\t{priv}\t{rss}\t0\n") + out.write(f"{t:.3f}\t0\t__shm__\t0\t0\t{sum(shm.values())}\n") + out.flush() + self.peak_private = max(self.peak_private, tot) + self.peak_shm = max(self.peak_shm, sum(shm.values())) + # Linux: sum(PSS) is the physical total. macOS: sum(footprint) misses shm pages charged to no + # live mapping, while the segment's resident size can exceed it: footprint + segment = upper bound + self.peak_total = max(self.peak_total, tot + sum(shm.values())) + self.peak_total_rss = max(self.peak_total_rss, tot_rss) + self.stop.wait(self.interval) + + +# ---------------------------------------------------------------------------------------------- +# running +def prepare_rundir(rundir, stage, clone_dir): + if os.path.exists(rundir) and os.listdir(rundir): + sys.exit(f"{rundir} exists and is not empty: every run needs a fresh directory") + os.makedirs(rundir, exist_ok=True) + if clone_dir: + for e in os.listdir(clone_dir): + src = os.path.join(clone_dir, e) + if e in ("dpl-config.json", "performanceMetrics.json") or re.match(r"(AO2D|AnalysisResults).*\.root$", e): + continue + # APFS clonefile copy (cheap), plain copy elsewhere + r = subprocess.run(["cp", "-cR" if sys.platform == "darwin" else "-R", src, rundir]) + if r.returncode: + sys.exit(f"cannot clone {src}") + for f in stage or []: + dst = os.path.join(rundir, os.path.basename(f)) + (shutil.copytree if os.path.isdir(f) else shutil.copy2)(f, dst) + + +def run_topology(topo, driver, dargs, rundir, env_script=None, monitoring=1, timeout=None, lock=None): + """Run the topology from its JSON in rundir. Returns a dict with wall time and memory peaks.""" + wf = os.path.join(rundir, "workflow.json") + with open(wf, "w") as f: + json.dump(topo, f) + args = set_opt(dargs, "--resources-monitoring", monitoring) + script = os.path.join(rundir, "run.sh") + with open(script, "w") as f: + f.write("#!/bin/bash\n# written by dpl-tune: run the topology from its JSON\n") + if env_script: + f.write(f". {shlex.quote(os.path.abspath(env_script))}\n") + f.write(f"cd {shlex.quote(rundir)}\n") + f.write(f"{sys.executable} -c 'import time; print(time.time())' > .t0\n") + f.write(f"{shlex.quote(driver)} {' '.join(shlex.quote(a) for a in args)} < workflow.json\n") + f.write("rc=$?\n") + f.write(f"{sys.executable} -c 'import time; print(time.time())' > .t1\nexit $rc\n") + log = open(os.path.join(rundir, "run.log"), "w") + lock_fd = None + if lock: # held by this process (not inherited by the run) until the run has finished + lock_fd = os.open(lock, os.O_RDWR | os.O_CREAT, 0o644) + while True: + try: + fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except BlockingIOError: + print(f" {lock} is held, waiting 30 s ({rundir})", file=sys.stderr, flush=True) + time.sleep(30) + p = subprocess.Popen(["bash", script], stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, cwd=rundir) + sampler = Sampler(p.pid, os.path.join(rundir, "mem.tsv")) + sampler.start() + try: + rc = p.wait(timeout=timeout) + except subprocess.TimeoutExpired: + kill_tree(p.pid) + p.wait() + rc = -9 + sampler.stop.set() + sampler.join() + if lock_fd is not None: + os.close(lock_fd) + log.close() + try: + wall = float(open(os.path.join(rundir, ".t1")).read()) - float(open(os.path.join(rundir, ".t0")).read()) + except (OSError, ValueError): + wall = None + return {"rc": rc, "wall_s": wall, "peak_mem_bytes": sampler.peak_total, "peak_private_bytes": sampler.peak_private, + "peak_shm_bytes": sampler.peak_shm, "peak_rss_sum_bytes": sampler.peak_total_rss} + + +def kill_tree(root): + """Stop a hung run: SIGINT to every process below root (DPL shuts down), then SIGKILL what is left.""" + import signal + for sig, wait in ((signal.SIGINT, 15), (signal.SIGKILL, 2)): + pids = descendants(process_table(), root) + for pid in pids: + try: + os.kill(pid, sig) + except OSError: + pass + time.sleep(wait if pids else 0) + + +def make_inputs(rundir, inputs, nfiles, input_opt): + files = [l.strip() for l in open(inputs) if l.strip() and not l.startswith("#")][:nfiles] + if not files: + sys.exit(f"no input files in {inputs}") + lst = os.path.join(rundir, "dpl-tune-inputs.txt") + with open(lst, "w") as f: + f.write("\n".join(files) + "\n") + if input_opt == "--aod-file": + return files, "@" + lst + return files, ",".join(files) + + +# ---------------------------------------------------------------------------------------------- +# metrics +def series(m, key): + out = [] + for x in m.get(key, []): + try: + out.append((int(x["timestamp"]), float(x["value"]))) + except (ValueError, KeyError): + pass + return sorted(out) + + +def interp(s, t): + """Value of a cumulative counter at time t (linear between samples; 0 before the first sample, + since DPL counters start at 0 when the device starts).""" + if not s: + return 0.0 + if t < s[0][0]: + return 0.0 + for (t0, v0), (t1, v1) in zip(s, s[1:]): + if t0 <= t <= t1: + return v0 + (v1 - v0) * (t - t0) / max(1, t1 - t0) + return s[-1][1] + + +def read_mem_tsv(path): + """Per device peak private memory, peak of the per-tick private sum, peak shm.""" + per_dev, per_tick, shm = {}, {}, {} + if not path or not os.path.exists(path): + return per_dev, 0, 0 + with open(path) as f: + next(f, None) + for line in f: + p = line.rstrip("\n").split("\t") + if len(p) < 6: + continue + t, dev, priv = p[0], p[2], int(p[3]) + if dev == "__shm__": + shm[t] = int(p[5]) + continue + base = re.sub(r"_t\d+$", "", dev) + per_dev[base] = max(per_dev.get(base, 0), priv) + per_tick[t] = per_tick.get(t, 0) + priv + return per_dev, max(per_tick.values(), default=0), max(shm.values(), default=0) + + +def analyse(pm, mem_tsv=None, wall=None): + d = pm + drv = d.get("driver", {}) + devs = {k: v for k, v in d.items() if k != "driver"} + cons = series(drv, "total-timeframes-consumed") + read = series(drv, "total-timeframes-read") + # TFs fully processed (consumed); fall back to the TFs read when nothing reports consumption + ntf = int(max([v for _, v in cons] + [0])) or int(max([v for _, v in read] + [0])) + all_ts = [t for m in devs.values() for k in m for t, _ in series(m, k)] + t_start, t_end = (min(all_ts), max(all_ts)) if all_ts else (0, 0) + # steady-state window: from the first completed TF to the last one (excludes start-up and the first + # TF's initialisation). When TFs complete in a burst (everything in flight at once, typical of + # reconstruction), that window is meaningless: then use the processing period instead, from the first + # processing callback anywhere (total_wall_time_ms > 0) to the last completed TF, with all TFs. + p0 = min([t for m in devs.values() for t, v in series(m, "total_wall_time_ms") if v > 0] or [t_start]) + w0 = w1 = None + if ntf >= 2 and cons: + w0 = next(t for t, v in cons if v >= 1) + w1 = next((t for t, v in cons if v >= ntf), t_end) + nwin = ntf - 1 + if w0 is None or (w1 - w0) < 0.2 * (w1 - p0): + w1 = next((t for t, v in cons if v >= ntf), t_end) if cons else t_end + w0, nwin = p0, max(1, ntf) + window_kind = "processing period (TFs complete in a burst)" + else: + window_kind = "first to last completed TF" + T = max(1e-3, (w1 - w0) / 1000.0) + per_dev_mem, peak_sum_mem, peak_shm = read_mem_tsv(mem_tsv) + res = {"ntf": ntf, "window_s": T, "tf_in_window": nwin, "devices": {}, "window_kind": window_kind, + "run_s": (t_end - t_start) / 1000.0 if all_ts else None, "wall_s": wall} + tot_cpu_win = 0.0 + for name, m in devs.items(): + busy = series(m, "total_wall_time_ms") + cpu = series(m, "cpuUsedAbsolute") # per-interval microseconds + b_tot = busy[-1][1] / 1000.0 if busy else 0.0 + b_win = (interp(busy, w1) - interp(busy, w0)) / 1000.0 if busy else 0.0 + c_tot = sum(v for _, v in cpu) / 1e6 + c_win = sum(v for t, v in cpu if w0 < t <= w1) / 1e6 + tot_cpu_win += c_win + pss = max([v for _, v in series(m, "proportionalSetSize")] or [0]) * 1024 # kB, Linux only + rss = max([v for _, v in series(m, "residentSetSize")] or [0]) * 1024 + base = re.sub(r"_t\d+$", "", name) + mem = per_dev_mem.get(base) or pss or None + tb = 0 + for k in m: + if k.startswith("table-bytes-"): + tb += sum(v for _, v in series(m, k)) + e = res["devices"].setdefault(base, {"busy_s": 0, "busy_win_s": 0, "cpu_s": 0, "cpu_win_s": 0, + "mem_bytes": None, "rss_bytes": 0, "table_bytes": 0, "lanes": 0}) + e["busy_s"] += b_tot + e["busy_win_s"] += b_win + e["cpu_s"] += c_tot + e["cpu_win_s"] += c_win + e["mem_bytes"] = max(e["mem_bytes"] or 0, mem or 0) or None + e["rss_bytes"] = max(e["rss_bytes"], rss) + e["table_bytes"] += tb + e["lanes"] += 1 + info = m.get("aod-file-read-info") + if info: + kv = dict(x.split("=", 1) for x in info[-1]["value"].split(",") if "=" in x) + e["read_info"] = kv + res["cpu_win_s"] = tot_cpu_win + # per-TF arrow/table bytes (all tables created for one TF live in shm while the TF is in flight) + tbytes = sum(e["table_bytes"] for e in res["devices"].values()) + res["table_bytes_per_tf"] = tbytes / ntf if ntf else 0 + # arrow-bytes-delta is created - destroyed as uint64: a transient negative value wraps around + delta = [(t, v - 2.0 ** 64 if v >= 2.0 ** 63 else v) for t, v in series(drv, "arrow-bytes-delta")] + infl = series(drv, "total-timeframes-in-flight") + res["arrow_peak_bytes"] = max([v for _, v in delta] or [0]) + # read - consumed is only meaningful when an AOD reader counts what it sends (df-sent) + win_infl = [v for t, v in infl if w0 <= t <= w1] if any(v > 0 for _, v in read) else [] + res["inflight_max"] = max(win_infl or [0]) + if len(win_infl) > 1: + # time-weighted mean of TFs in flight in the window + pts = [(t, v) for t, v in infl if w0 <= t <= w1] + acc = sum(v0 * (t1 - t0) for (t0, v0), (t1, _) in zip(pts, pts[1:])) + res["inflight_mean"] = acc / max(1, pts[-1][0] - pts[0][0]) + else: + res["inflight_mean"] = None + res["peak_private_sum_bytes"] = peak_sum_mem or None + res["shm_resident_peak_bytes"] = peak_shm or None + return res + + +# ---------------------------------------------------------------------------------------------- +# the tuner +def tune(an, topo, dargs, kind, budget, cores): + """Returns (knobs, explanations, prediction).""" + specs = {w["name"]: w for w in topo["workflow"]} + devs = an["devices"] + N, T = an["tf_in_window"], an["window_s"] + notes, knobs = [], {"global": {}, "pipeline": {}} + why = [] # (knob, value, reason) + tau = T / N # observed seconds per TF in steady state + for d in devs.values(): + d["b"] = d["busy_win_s"] / N / max(1, d["lanes"]) # busy seconds per TF per lane + d["u"] = d["busy_win_s"] / T / max(1, d["lanes"]) # busy fraction per lane + d["c"] = d["cpu_win_s"] / N # CPU seconds per TF (all lanes) + ranked = sorted(devs.items(), key=lambda kv: -kv[1]["b"]) + top, topd = ranked[0] + cpu_per_tf = sum(d["c"] for d in devs.values()) + cpu_util = cpu_per_tf / tau / cores + # memory model: sum of per-device private peaks + in-flight shm + mem_known = all(d["mem_bytes"] for d in devs.values()) + priv = sum(d["mem_bytes"] or 0 for d in devs.values()) + measured_peak = an.get("peak_private_sum_bytes") or priv + s_tf = an["table_bytes_per_tf"] if kind == "analysis" else 0 + # shm: resident pages of the FairMQ segment (macOS, measured); otherwise the arrow bytes in flight + shm_now = max(0, an.get("shm_resident_peak_bytes") or (an["arrow_peak_bytes"] if kind == "analysis" else 0)) + pred = {"tau_obs_s": tau, "cpu_util_obs": cpu_util, "bottleneck": top, "bottleneck_busy_frac": topd["u"], + "measured_peak_private_bytes": measured_peak, "measured_shm_peak_bytes": shm_now, + "measured_peak_total_bytes": measured_peak} + notes.append(f"steady state: {N} TFs in {T:.1f} s = {tau:.3f} s/TF (window: {an.get('window_kind')}; " + f"driver metric total-timeframes-consumed)") + notes.append(f"busiest device per lane: {top} busy {topd['u']:.0%} of the window " + f"({topd['b']*1000:.0f} ms/TF, total_wall_time_ms); next: " + + ", ".join(f"{k} {v['u']:.0%}" for k, v in ranked[1:4])) + notes.append(f"CPU in the window: {cpu_per_tf:.2f} CPU-s/TF = {cpu_util:.0%} of {cores} cores (cpuUsedAbsolute)") + if not mem_known: + notes.append("per-device memory not measured for every device (no mem.tsv / PSS): memory-raising knobs are " + "left alone") + if N < 4: + notes.append(f"only {N} TFs in the steady-state window: too few to tune from; nothing changed") + return knobs, why, notes, pred + + busy_sum_per_tf = sum(d["b"] * max(1, d["lanes"]) for d in devs.values()) + # Is the observed throughput limited by one device, by the CPU, or by the number of TFs in flight? + if topd["u"] >= 0.85: + regime = "device" + elif cpu_util >= 0.85: + regime = "cpu" + else: + regime = "concurrency" + pred["regime"] = regime + notes.append(f"regime: {regime}-bound (sum of busy times {busy_sum_per_tf*1000:.0f} ms/TF vs " + f"{tau*1000:.0f} ms/TF observed; TFs in flight mean {an['inflight_mean'] or 0:.1f}, max {an['inflight_max']:.0f})") + if regime == "cpu": + notes.append("CPU-bound: no knob raises throughput on this many cores; nothing changed") + return knobs, why, notes, pred + + usable = budget * 0.9 + # Memory of the probe: sum over processes at its peak (Linux PSS: exact; macOS footprint: upper bound, + # shm counted once per process touching it). More TFs in flight add their shm once. + base_mem = measured_peak + lanes0 = {k: max(1, d["lanes"]) for k, d in devs.items()} + reader = next((k for k in devs if k.startswith("internal-dpl-aod-reader")), None) + lat = max(tau * (an["inflight_mean"] or 1.0), busy_sum_per_tf) # TF latency (Little's law, or sum of busy) + pred["latency_s"] = lat + tau_cpu = cpu_per_tf / (0.9 * cores) + k_cur = max(1, int(an["inflight_max"] or 1)) + can_k = kind == "analysis" and s_tf > 0 # only the AOD rate limit has a measured per-TF size + + def per_lane(lanes): + return {k: devs[k]["b"] * lanes0[k] / lanes[k] for k in devs} + + def shm_for(k): # linear in the TFs in flight, never below the measured high-water mark. Measured on + # macOS: the segment's resident high-water mark grows ~3-4x faster than this (allocator spread), + # so this is a lower bound; the verification run measures the real peak against the budget. + return max(shm_now, shm_now * k / max(1, k_cur), k * s_tf) + + def mem(lanes, k): + extra = sum((lanes[d] - lanes0[d]) * (devs[d]["mem_bytes"] or 0) for d in devs) + return base_mem + extra + shm_for(k) - shm_now + + def plan(lanes): + """TFs in flight needed for these lanes, and what fits in memory.""" + tau_t = max(max(per_lane(lanes).values()), tau_cpu) + k_need = max(k_cur, math.ceil(lat / tau_t)) if can_k else k_cur + k_fit = k_cur + while can_k and mem(lanes, k_fit + 1) <= usable and k_fit < 64: + k_fit += 1 + return tau_t, k_need, min(k_need, k_fit) + + lanes = dict(lanes0) + if regime == "concurrency" and an.get("window_kind", "").startswith("processing"): + notes.append(f"all TFs complete in one burst and the busiest device is busy {topd['u']:.0%} of the processing " + "period: the run is bound by start-up and the first TF's latency (initialisation, CCDB), not by " + "a device's throughput or the TFs in flight; no runtime knob in scope changes that: nothing changed") + lanes_ok = False + elif regime == "concurrency" and not can_k: + notes.append(f"{kind}: devices are mostly idle ({topd['u']:.0%} at most) but the TFs in flight cannot be " + "measured for this kind of workflow (no in-flight / shm metric in performanceMetrics.json): " + "nothing changed") + lanes_ok = False + else: + lanes_ok = mem_known + for _ in range(8): + if not lanes_ok: + break + eff = per_lane(lanes) + bott = max(eff, key=eff.get) + second = max([v for k, v in eff.items() if k != bott] + [1e-6]) + if tau_cpu >= 0.95 * eff[bott]: + notes.append(f"after the changes the CPU ({cpu_per_tf:.2f} CPU-s/TF on {cores} cores) is the limit") + break + if bott == reader and kind == "analysis": + n = lanes[bott] + 1 + elif not NOT_PIPELINABLE.search(bott) and (bott in specs and not is_source(specs[bott]) or not specs) \ + and eff[bott] >= 1.3 * second and eff[bott] >= 0.02: + n = min(math.ceil(lanes[bott] * eff[bott] / max(second, tau_cpu)), max(1, cores // 2), 8) + else: + if eff[bott] >= 0.02: + notes.append(f"{bott} would be the next limit ({eff[bott]*1000:.0f} ms/TF per lane) but " + + ("it cannot be pipelined" if bott in specs or bott.startswith("internal-") else "it is not in the topology") + + (f" or does not dominate (next {second*1000:.0f} ms/TF)" if eff[bott] < 1.3 * second else "")) + break + if n <= lanes[bott]: + break + trial = dict(lanes, **{bott: n}) + t_tau, t_need, t_k = plan(trial) + if mem(trial, t_k) > usable or (can_k and t_k < t_need and lat / max(t_k, 1) >= eff[bott]): + notes.append(f"{bott}: {n} lanes do not fit the memory budget with the TFs in flight they need: left alone") + break + lanes = trial + if not lanes_ok and regime == "concurrency" and an.get("window_kind", "").startswith("processing"): + can_k = False + tau_t, k_need, k_new = plan(lanes) + tau_pred = max(tau_t, lat / max(k_new, 1)) if can_k else max(tau_t, tau if regime != "device" else tau_t) + eff = per_lane(lanes) + for d in devs: + if lanes[d] == lanes0[d]: + continue + if d == reader: + ri = devs[d].get("read_info", {}) + knobs["global"]["--readers"] = lanes[d] + why.append(("--readers", lanes[d], + f"the AOD reader needs {devs[d]['b']*1000:.0f} ms/TF (total_wall_time_ms; io_time " + f"{ri.get('io_time', '?')} s, wait_time {ri.get('wait_time', '?')} s in aod-file-read-info) and " + f"would be the limit once more TFs are in flight; {lanes[d]} readers bring it to " + f"{eff[d]*1000:.0f} ms/TF, at +{fmt_bytes((lanes[d]-lanes0[d])*(devs[d]['mem_bytes'] or 0))}")) + else: + knobs["pipeline"][d] = lanes[d] + why.append(("--pipeline", f"{d}:{lanes[d]}", + f"{d} needs {devs[d]['b']*lanes0[d]*1000:.0f} ms/TF (total_wall_time_ms), the slowest " + f"pipelinable device; {lanes[d]} lanes bring it to {eff[d]*1000:.0f} ms/TF per lane, at " + f"+{fmt_bytes((lanes[d]-lanes0[d])*(devs[d]['mem_bytes'] or 0))} (private peak " + f"{fmt_bytes(devs[d]['mem_bytes'])} per lane)")) + if can_k and k_new > k_cur and mem_known: + old = get_opt(dargs, "--aod-memory-rate-limit") + limit = int(math.ceil(k_new * s_tf * 1.1 / MB) * MB) + if old is None or limit > int(old): + knobs["global"]["--aod-memory-rate-limit"] = limit + why.append(("--aod-memory-rate-limit", limit, + f"{an['inflight_mean'] or 0:.1f} TFs in flight on average (max {k_cur}; " + f"total-timeframes-in-flight) with a limit of {old or 'default'} B and {fmt_bytes(s_tf)} of " + f"tables per TF (table-bytes-*-created): the TF latency is {lat:.2f} s and the slowest lane " + f"needs {tau_t*1000:.0f} ms/TF, so {k_need} TFs in flight are needed; {k_new} fit in the " + f"budget ({fmt_bytes(shm_for(k_new))} of shm extrapolated from the measured {fmt_bytes(shm_now)}; limit = {k_new} x tables per TF +10%)")) + # the default TF limit is readers x 64 (ArrowSupport.cxx driverInit); only an explicit one can bind + tfl = get_opt(dargs, "--timeframes-rate-limit") + if tfl and int(tfl) < k_new: + knobs["global"]["--timeframes-rate-limit"] = k_new + why.append(("--timeframes-rate-limit", k_new, f"the explicit TF limit {tfl} would cap the {k_new} TFs in flight")) + elif can_k and k_need > k_cur and not mem_known: + notes.append(f"{k_need} TFs in flight would be needed but the memory is unknown: rate limit unchanged") + k_final = max(k_cur, k_new) if can_k else k_cur + + # shm segment: must hold the in-flight data (twice, for fragmentation); never shrink it + shm = get_opt(dargs, "--shm-segment-size") + shm_cur = int(shm) if shm else None + need = 2 * shm_for(k_final) + if shm_cur is not None and need > shm_cur: + new = int(math.ceil(need / GiB) * GiB) + knobs["global"]["--shm-segment-size"] = new + why.append(("--shm-segment-size", new, f"in-flight data up to {fmt_bytes(need/2)} (TFs in flight x table " + f"bytes per TF) needs 2x headroom over {fmt_bytes(shm_cur)}")) + elif shm_cur is not None: + notes.append(f"--shm-segment-size {fmt_bytes(shm_cur)} kept: in-flight shm {fmt_bytes(shm_for(k_final))} " + "at most; a smaller segment saves no resident memory (untouched pages are not counted)") + m_pred = mem(lanes, k_final) + pred.update({"tau_pred_s": tau_pred if why else tau, "mem_pred_bytes": m_pred, "budget_bytes": budget, + "tf_in_flight": k_final, "lanes": {k: v for k, v in lanes.items() if v != lanes0[k]}}) + if m_pred > budget: + notes.append(f"WARNING: the probe itself ({fmt_bytes(m_pred)}) exceeds the budget") + if not why: + notes.append("no knob is justified by the metrics: configuration unchanged") + return knobs, why, notes, pred + + +# ---------------------------------------------------------------------------------------------- +def write_outputs(out, topo, driver, dargs, knobs, why, notes, pred, an, args, input_opt): + os.makedirs(out, exist_ok=True) + if not topo["workflow"]: + notes.append("no topology given: pipelinability of devices not checked against their inputs, no tuned JSON written") + ttopo, targs = apply_knobs(topo, dargs, knobs) + with open(os.path.join(out, "workflow.tuned.json"), "w") as f: + json.dump(ttopo, f) + with open(os.path.join(out, "run-tuned.sh"), "w") as f: + f.write("#!/bin/bash\n# tuned configuration written by dpl-tune; run from a fresh directory with the\n" + "# same environment and staged files as the probe\n") + f.write(f"{shlex.quote(driver)} {' '.join(shlex.quote(a) for a in targs)} < {shlex.quote(os.path.join(out, 'workflow.tuned.json'))}\n") + flat = [] + for k, v in knobs["global"].items(): + flat += [k, str(v)] + if knobs["pipeline"]: + flat += ["--pipeline", ",".join(f"{k}:{v}" for k, v in knobs["pipeline"].items())] + js = {"knobs": knobs, "changes": [{"option": k, "value": v, "reason": r} for k, v, r in why], + "notes": notes, "prediction": pred, "extra_args": flat, "analysis": an, + "inputs": {"budget_bytes": pred.get("budget_bytes"), "cores": args.cores, "input_option": input_opt}} + with open(os.path.join(out, "tuning.json"), "w") as f: + json.dump(js, f, indent=1, default=str) + lines = ["# dpl-tune result", "", f"Topology: {args.topology}", f"Budget: {fmt_bytes(pred.get('budget_bytes') or 0)}, cores: {args.cores}", ""] + lines.append("## Changes") + if why: + for k, v, r in why: + lines.append(f"- `{k} {v}`: {r}") + else: + lines.append("- none") + lines += ["", "## Observations"] + [f"- {n}" for n in notes] + lines += ["", "## Prediction"] + if "tau_pred_s" in pred: + lines.append(f"- s/TF: {pred['tau_obs_s']:.3f} observed -> {pred['tau_pred_s']:.3f} predicted (lower bound)") + lines.append(f"- memory: {fmt_bytes(pred['measured_peak_total_bytes'])} measured (sum over processes, of which shm " + f"segment resident {fmt_bytes(pred['measured_shm_peak_bytes'])}) -> " + f"{fmt_bytes(pred['mem_pred_bytes'])} extrapolated, budget {fmt_bytes(pred['budget_bytes'])}") + lines += ["", "## Per device (steady-state window)", "", + "| device | lanes | busy ms/TF | busy % | CPU ms/TF | private mem peak |", "|---|---|---|---|---|---|"] + for k, d in sorted(an["devices"].items(), key=lambda kv: -kv[1].get("b", 0)): + lines.append(f"| {k} | {d['lanes']} | {d.get('b', 0)*1000:.0f} | {d.get('u', 0):.0%} | {d.get('c', 0)*1000:.0f} | {fmt_bytes(d['mem_bytes'])} |") + with open(os.path.join(out, "tuning.md"), "w") as f: + f.write("\n".join(lines) + "\n") + print("\n".join(lines[:lines.index("## Per device (steady-state window)")])) + + +def common_args(p): + p.add_argument("topology", nargs="?", help="DPL workflow dump (JSON); optional with --from-metrics") + p.add_argument("--inputs", help="input file list (AO2D for analysis, CTF/TF files for reconstruction)") + p.add_argument("--input-option", help=f"option carrying the inputs (default: first of {INPUT_OPTIONS} found)") + p.add_argument("--env", help="bash file sourced before running (the reproducer's environment)") + p.add_argument("--stage", nargs="*", default=[], help="files copied into the run directory (configs)") + p.add_argument("--clone-dir", help="directory whose contents are cloned into the run directory") + p.add_argument("--driver", help="driver command line (default: last stage of the topology 'command')") + p.add_argument("--set", action="append", default=[], metavar="OPT=VALUE", + help="override an option everywhere it appears, e.g. --set=--max-tf=8") + p.add_argument("--monitoring", type=int, default=1, help="--resources-monitoring interval (s)") + p.add_argument("--timeout", type=int, default=3600, help="seconds after which a run is stopped") + p.add_argument("--lock", metavar="FILE", help="run each DPL run under an exclusive flock() on FILE, waiting " + "while another process holds it (e.g. to serialise with builds or other runs)") + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = ap.add_subparsers(dest="cmd", required=True) + t = sub.add_parser("tune", help="probe a topology (or read --from-metrics) and write a tuned configuration") + common_args(t) + t.add_argument("--probe-files", type=int, default=1, help="number of input files of the probe run") + t.add_argument("--mem-budget", required=True, help="total memory budget, e.g. 16G, or per core with --per-core") + t.add_argument("--per-core", action="store_true", help="--mem-budget is per core (Grid style, e.g. 2G)") + t.add_argument("--cores", type=int, required=True, help="cores available to the workflow") + t.add_argument("-o", "--out", required=True, help="output directory") + t.add_argument("--from-metrics", help="tune from this performanceMetrics.json without running") + t.add_argument("--mem-samples", help="mem.tsv of the run that produced --from-metrics") + t.add_argument("--no-verify", dest="verify", action="store_false", + help="do not run the tuned configuration on the probe inputs to check it") + t.add_argument("--no-readers-guard", dest="readers_guard", action="store_false", default=READERS_GUARD, + help="do not back off --readers first when a verification with --readers > 1 and " + "--aod-memory-rate-limit fails (see README.md)") + r = sub.add_parser("run", help="run a topology, optionally with a tuning, and write summary.json") + common_args(r) + r.add_argument("--files", type=int, default=1) + r.add_argument("--tuning", help="tuning.json to apply") + r.add_argument("-o", "--out", required=True, help="run directory (must be new)") + args = ap.parse_args() + + if args.topology: + topo = load_topology(args.topology) + driver, dargs = driver_stage(topo, args.driver) + elif getattr(args, "from_metrics", None): + # metrics only (e.g. a Grid performanceMetrics.json): no topology to check or rewrite + topo = {"workflow": [], "metadata": [{"name": k, "cmdLineArgs": []} for k in json.load(open(args.from_metrics)) + if k != "driver"], "command": ""} + toks = shlex.split(args.driver) if args.driver else ["?"] + driver, dargs = toks[0], toks[1:] + else: + sys.exit("a topology is needed unless --from-metrics is given") + kind = topology_kind(topo, dargs) + input_opt = find_input_option(topo, dargs, args.input_option) + extra = dict(s.split("=", 1) for s in getattr(args, "set", [])) + + if args.cmd == "run": + rundir = os.path.abspath(args.out) + prepare_rundir(rundir, args.stage, args.clone_dir) + knobs = json.load(open(args.tuning))["knobs"] if args.tuning else {"global": {}, "pipeline": {}} + files, val = make_inputs(rundir, args.inputs, args.files, input_opt) if args.inputs else ([], None) + rtopo, rargs = apply_knobs(topo, dargs, knobs, input_opt, val, extra) + res = run_topology(rtopo, driver, rargs, rundir, args.env, args.monitoring, args.timeout, args.lock) + pmf = os.path.join(rundir, "performanceMetrics.json") + if os.path.exists(pmf): + an = analyse(json.load(open(pmf)), os.path.join(rundir, "mem.tsv"), res["wall_s"]) + res["ntf"] = an["ntf"] + res["tf_per_s"] = an["ntf"] / res["wall_s"] if res["wall_s"] else None + res["steady_s_per_tf"] = an["window_s"] / an["tf_in_window"] + res.update({"files": files, "knobs": knobs, "kind": kind}) + json.dump(res, open(os.path.join(rundir, "summary.json"), "w"), indent=1) + print(json.dumps({k: res.get(k) for k in ("rc", "wall_s", "ntf", "tf_per_s", "steady_s_per_tf", + "peak_mem_bytes", "peak_private_bytes", "peak_shm_bytes")})) + return 0 if res["rc"] == 0 else 1 + + budget = parse_size(args.mem_budget) * (args.cores if args.per_core else 1) + out = os.path.abspath(args.out) + if args.from_metrics: + pm = json.load(open(args.from_metrics)) + an = analyse(pm, args.mem_samples) + res, val = None, None + else: + if not args.inputs and not input_opt: + print("no input list: the probe runs the topology as dumped", file=sys.stderr) + rundir = os.path.join(out, "probe") + prepare_rundir(rundir, args.stage, args.clone_dir) + files, val = make_inputs(rundir, args.inputs, args.probe_files, input_opt) if args.inputs else ([], None) + rtopo, rargs = apply_knobs(topo, dargs, {"global": {}, "pipeline": {}}, input_opt, val, extra) + print(f"probe: {kind} topology, {len(topo['metadata'])} data processors, inputs {files}", flush=True) + res = run_topology(rtopo, driver, rargs, rundir, args.env, args.monitoring, args.timeout, args.lock) + if res["rc"] != 0: # some tasks crash at random at shutdown: one retry in a fresh directory + print(f"probe run failed (rc={res['rc']}, {rundir}/run.log): retrying once", flush=True) + os.rename(rundir, rundir + f"-failed-rc{res['rc']}") + prepare_rundir(rundir, args.stage, args.clone_dir) + files, val = make_inputs(rundir, args.inputs, args.probe_files, input_opt) if args.inputs else ([], None) + rtopo, rargs = apply_knobs(topo, dargs, {"global": {}, "pipeline": {}}, input_opt, val, extra) + res = run_topology(rtopo, driver, rargs, rundir, args.env, args.monitoring, args.timeout, args.lock) + if res["rc"] != 0: + sys.exit(f"probe run failed (rc={res['rc']}), see {rundir}/run.log") + print(f"probe: wall {res['wall_s']:.1f} s, peak memory {fmt_bytes(res['peak_mem_bytes'])} (sum over processes; " + f"shm segment resident {fmt_bytes(res['peak_shm_bytes'])})", flush=True) + an = analyse(json.load(open(os.path.join(rundir, "performanceMetrics.json"))), + os.path.join(rundir, "mem.tsv"), res["wall_s"]) + knobs, why, notes, pred = tune(an, topo, dargs, kind, budget, args.cores) + if not args.from_metrics and args.verify and why: + knobs, why, notes = verify(knobs, why, notes, pred, an, res, topo, driver, dargs, args, out, budget, + input_opt, val, extra) + elif args.readers_guard and {"--readers", "--aod-memory-rate-limit"} <= set(knobs["global"]): + notes.append("WARNING (readers guard): --readers > 1 with --aod-memory-rate-limit deadlocked in the O2 " + "versions tested, and this tuning is not verified: drop --readers if the run stalls") + write_outputs(out, topo, driver, dargs, knobs, why, notes, pred, an, args, input_opt) + return 0 + + +def verify(knobs, why, notes, pred, an, probe, topo, driver, dargs, args, out, budget, input_opt, val, extra): + """Run the tuned configuration on the probe inputs; back off the riskiest change while it fails. + + Failure: non-zero exit (retried once: some tasks crash at shutdown at random), fewer TFs than the + probe, a hang (more than 3x the probe wall time), or a measured peak memory above the budget. + Back-off order: extra readers when READERS_GUARD applies, then pipeline lanes, then extra readers, + then half of the extra TFs in flight. + """ + timeout = int(max(120, 3 * (probe["wall_s"] or 60))) + for attempt in range(1, 5): + if not why: + break + rundir = os.path.join(out, f"verify{attempt}") + bad = None + for retry in range(2): + rd = rundir + ("" if retry == 0 else "-retry") + prepare_rundir(rd, args.stage, args.clone_dir) + v = make_inputs(rd, args.inputs, args.probe_files, input_opt)[1] if args.inputs else val + rtopo, rargs = apply_knobs(topo, dargs, knobs, input_opt, v, extra) + print(f"verify {attempt}: {json.dumps(knobs)}", flush=True) + res = run_topology(rtopo, driver, rargs, rd, args.env, args.monitoring, timeout, args.lock) + pmf = os.path.join(rd, "performanceMetrics.json") + van = analyse(json.load(open(pmf)), os.path.join(rd, "mem.tsv"), res["wall_s"]) if os.path.exists(pmf) else None + if res["rc"] == -9: + bad = f"hung: killed after {timeout} s (probe: {probe['wall_s']:.0f} s)" + elif van is None or van["ntf"] < an["ntf"]: + bad = f"processed {van['ntf'] if van else 0} TFs, the probe {an['ntf']}" + elif res["rc"] != 0: + bad = f"exit code {res['rc']}" + elif res["peak_mem_bytes"] > budget: + bad = f"peak memory {fmt_bytes(res['peak_mem_bytes'])} above the budget" + else: + bad = None + if bad is None or not bad.startswith("exit code"): + break + if bad is None: + s_per_tf = van["window_s"] / van["tf_in_window"] + notes.append(f"verified on the probe inputs ({rundir}): wall {res['wall_s']:.1f} s vs {probe['wall_s']:.1f} s, " + f"steady state {s_per_tf:.3f} s/TF vs {pred['tau_obs_s']:.3f} (predicted {pred.get('tau_pred_s', 0):.3f}), " + f"peak memory {fmt_bytes(res['peak_mem_bytes'])} vs {fmt_bytes(probe['peak_mem_bytes'])} " + f"(predicted {fmt_bytes(pred.get('mem_pred_bytes'))})") + pred["verified"] = {"wall_s": res["wall_s"], "s_per_tf": s_per_tf, "peak_mem_bytes": res["peak_mem_bytes"]} + # judged on the wall time of the whole probe: with more TFs in flight the first-to-last-completed + # window starts later (several TFs are half done when the first completes), so its s/TF is biased + if res["wall_s"] > 0.95 * probe["wall_s"]: + notes.append("the tuned configuration is not faster on the probe (wall time): changes withdrawn") + return {"global": {}, "pipeline": {}}, [], notes + return knobs, why, notes + notes.append(f"verification {attempt} failed ({bad}) with {json.dumps(knobs)}") + g, pl = knobs["global"], knobs["pipeline"] + if args.readers_guard and "--readers" in g and "--aod-memory-rate-limit" in g: + g.pop("--readers") + why = [w for w in why if w[0] != "--readers"] + notes.append("backed off: --readers (readers guard: --readers > 1 with --aod-memory-rate-limit " + "deadlocked in the O2 versions tested)") + elif pl: + k = max(pl, key=pl.get) + pl.pop(k) + why = [w for w in why if not (w[0] == "--pipeline" and str(w[1]).startswith(k + ":"))] + notes.append(f"backed off: --pipeline {k}") + elif "--readers" in g: + g.pop("--readers") + why = [w for w in why if w[0] != "--readers"] + notes.append("backed off: --readers") + elif "--aod-memory-rate-limit" in g: + old = int(get_opt(dargs, "--aod-memory-rate-limit") or 0) + new = (g["--aod-memory-rate-limit"] + old) // 2 + if new <= old * 1.2: + g.pop("--aod-memory-rate-limit") + why = [w for w in why if w[0] != "--aod-memory-rate-limit"] + else: + g["--aod-memory-rate-limit"] = new + why = [(k, new if k == "--aod-memory-rate-limit" else v, r + f" [halved after a failed verification]" + if k == "--aod-memory-rate-limit" else r) for k, v, r in why] + notes.append("backed off: half of the extra AOD memory") + else: + notes.append("nothing left to back off: configuration unchanged") + return {"global": {}, "pipeline": {}}, [], notes + if why: + notes.append("not verified after 4 attempts: changes withdrawn") + return {"global": {}, "pipeline": {}}, [], notes + return knobs, why, notes + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/Framework/Core/scripts/dpl-tune/pyproject.toml b/Framework/Core/scripts/dpl-tune/pyproject.toml new file mode 100644 index 0000000000000..76abd551f3da8 --- /dev/null +++ b/Framework/Core/scripts/dpl-tune/pyproject.toml @@ -0,0 +1,16 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "dpl-tune" +version = "0.1.0" +description = "Tune the runtime configuration of a DPL workflow from a short probe run" +requires-python = ">=3.9" +dependencies = [] + +[project.scripts] +dpl-tune = "dpl_tune:main" + +[tool.hatch.build.targets.wheel] +include = ["dpl_tune.py"]