From 6659619e23f8fa7f1e0d44315e578dd2bed9867d Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 30 Oct 2026 14:43:44 +0000 Subject: [PATCH 1/2] feat(campaign): evidence readers with grades, campaign plan and pilot (hpc-campaign p3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit autofit.campaign.evidence reads profiling-summary@3 (or the PyAutoPulse snapshot wrapping it), walltime-validation@1 and inference-summary@2 by path or URL; stages declare opaque match keys under evidence.keys in campaign.yaml. Every match is graded measured-current / provisional / analogue (instrument or regime differs, said which) / superseded; a stage with no keys matches nothing. 'Optimal' comes only from a PyAutoPulse designation decision (decisions.yaml kind: designation); Pulse's provisional_optimal marker is restated without the word. autofit.campaign.plan proposes per stage CPUs (shrunk to a power of two below 60 % median CPU efficiency), memory (peak RSS x 1.25, 4 GB steps), wall time (p95 + 25 % per size bin, 15 min steps, capped at max_time; timeouts kept at their limit and a censored p95 flagged), throttle (50 % of idle CPUs), ETA, disk and an energy placeholder for phase 4 — every number a graded value with its sources; plan.json + plan.md. autofit.campaign.pilot writes a stratified pilot.json (never submitted). CLI: plan, pilot. Refs #1745 Co-Authored-By: Claude Opus 5.5 --- autofit/campaign/__init__.py | 7 +- autofit/campaign/__main__.py | 84 ++++ autofit/campaign/evidence.py | 437 +++++++++++++++++++ autofit/campaign/pilot.py | 121 ++++++ autofit/campaign/plan.py | 671 +++++++++++++++++++++++++++++ autofit/campaign/spec.py | 50 ++- test_autofit/campaign/test_plan.py | 539 +++++++++++++++++++++++ 7 files changed, 1906 insertions(+), 3 deletions(-) create mode 100644 autofit/campaign/evidence.py create mode 100644 autofit/campaign/pilot.py create mode 100644 autofit/campaign/plan.py create mode 100644 test_autofit/campaign/test_plan.py diff --git a/autofit/campaign/__init__.py b/autofit/campaign/__init__.py index 3da298bef..a385983d2 100644 --- a/autofit/campaign/__init__.py +++ b/autofit/campaign/__init__.py @@ -9,9 +9,12 @@ - ``collector``: accounting joined with status records → ``digest`` (``digest.json``, a ≤2 KB ``digest.md``, ``tasks.jsonl``, ``failed_.txt``); - ``proposals``: resubmit and pending-update proposals (never acted on); -- ``retro``: the digest of a finished campaign from a ``sacct`` dump alone. +- ``retro``: the digest of a finished campaign from a ``sacct`` dump alone; +- ``evidence``: profiling / inference summaries, read and graded per stage; +- ``plan``: proposed resources, wall time, ETA and disk, every number graded; +- ``pilot``: a stratified subset of the manifest to measure first. -Command line: ``python -m autofit.campaign {validate,submit,status,resubmit,retro}``; +Command line: ``python -m autofit.campaign {validate,submit,status,resubmit,retro,plan,pilot}``; in Python, ``autofit.campaign.submit.submit(campaign, scheduler)`` and ``autofit.campaign.retro.retro(dump, ...)``. diff --git a/autofit/campaign/__main__.py b/autofit/campaign/__main__.py index 1c4c4da2e..fc83878e8 100644 --- a/autofit/campaign/__main__.py +++ b/autofit/campaign/__main__.py @@ -20,6 +20,14 @@ retro --sacct DUMP [--workdir-prefix DIR ...] [--name-regex RE] [--stage-regex RE] [--other-stage NAME] [--status-root DIR] [--site NAME] [--name NAME] [--output DIR] The digest of a finished campaign from a ``sacct --parsable2`` dump alone. +plan [--evidence SRC ...] [--pilot TASKS] [--decisions YAML] + [--idle-cpus [PARTITION=]N ...] [--capacity-source TEXT] [--results-index DIR] [--output DIR] + Propose each stage's resources, wall time, ETA and disk from a pilot and the + profiling / inference summaries, every number graded (``autofit.campaign.plan``). +pilot [--fraction F] [--size-field NAME | --size-path TEMPLATE] [--bins N] + [--seed S] [--output DIR] + Write ``pilot.json``: a stratified subset of the manifest to measure first. Nothing + is submitted. """ import argparse import json @@ -164,6 +172,61 @@ def _retro(arguments) -> int: return 0 +def _idle_cpus(values, source): + from autofit.campaign.plan import graded + + idle = {} + for value in values or (): + partition, _, number = value.rpartition("=") + idle[partition or "*"] = graded(int(number), "estimated", [source or "stated on the command line"]) + return idle + + +def _plan(arguments) -> int: + from autofit.campaign.evidence import read_designations, read_evidence + from autofit.campaign.plan import build_plan, plan_markdown, read_pilot, read_results_index, write_plan + + try: + campaign = Campaign.load(arguments.campaign) + except CampaignException as exception: + print(exception, file=sys.stderr) + return 1 + plan = build_plan( + campaign, + evidence=[read_evidence(source) for source in arguments.evidence or ()], + pilot=read_pilot(arguments.pilot) if arguments.pilot else None, + pilot_source=arguments.pilot, + designations=read_designations(arguments.decisions), + idle_cpus=_idle_cpus(arguments.idle_cpus, arguments.capacity_source), + results_index=read_results_index(arguments.results_index) if arguments.results_index else None, + decisions_source=arguments.decisions, + ) + write_plan(arguments.output or campaign.directory, plan) + print(plan_markdown(plan), end="") + return 0 + + +def _pilot(arguments) -> int: + from autofit.campaign.pilot import pilot_indices, write_pilot + + try: + campaign = Campaign.load(arguments.campaign) + except CampaignException as exception: + print(exception, file=sys.stderr) + return 1 + pilot = pilot_indices( + campaign, + fraction=arguments.fraction, + size_field=arguments.size_field, + size_path=arguments.size_path, + bins=arguments.bins, + seed=arguments.seed, + ) + path = write_pilot(arguments.output or campaign.directory, campaign, pilot, arguments.campaign) + print(path.read_text()) + return 0 + + def main(argv=None) -> int: parser = argparse.ArgumentParser(prog="python -m autofit.campaign") commands = parser.add_subparsers(dest="command", required=True) @@ -202,6 +265,27 @@ def main(argv=None) -> int: retro.add_argument("--output", help="Write the digest files here.") retro.set_defaults(handler=_retro) + plan = commands.add_parser("plan", help="Propose resources from evidence (never submits).") + plan.add_argument("campaign") + plan.add_argument("--evidence", action="append", help="A profiling / inference summary (path or URL).") + plan.add_argument("--pilot", help="Pilot outcomes: a tasks.jsonl or the directory holding one.") + plan.add_argument("--decisions", help="PyAutoPulse decisions.yaml (designations).") + plan.add_argument("--idle-cpus", action="append", help="[PARTITION=]N idle CPUs (repeatable).") + plan.add_argument("--capacity-source", help="Where the idle-CPU figure comes from.") + plan.add_argument("--results-index", help="A results index, for the disk forecast.") + plan.add_argument("--output", help="Write plan.json / plan.md here.") + plan.set_defaults(handler=_plan) + + pilot = commands.add_parser("pilot", help="Choose a stratified pilot (never submits).") + pilot.add_argument("campaign") + pilot.add_argument("--fraction", type=float, default=0.02) + pilot.add_argument("--size-field", help="Manifest field holding each object's size.") + pilot.add_argument("--size-path", help="Path template whose file size is the object's size.") + pilot.add_argument("--bins", type=int, default=5) + pilot.add_argument("--seed", type=int, default=0) + pilot.add_argument("--output", help="Write pilot.json here.") + pilot.set_defaults(handler=_pilot) + arguments = parser.parse_args(argv) return arguments.handler(arguments) diff --git a/autofit/campaign/evidence.py b/autofit/campaign/evidence.py new file mode 100644 index 000000000..51dae7a9e --- /dev/null +++ b/autofit/campaign/evidence.py @@ -0,0 +1,437 @@ +""" +Evidence for planning a campaign: measured costs read from the profiling and inference +summaries, each number graded by how well it fits the campaign's stage. + +Three published summaries are read, by path or URL, never modified: + +- ``profiling-summary@3`` (``autolens_profiling/dashboard/catalogue.json``, or the + PyAutoPulse snapshot that wraps it under ``summary``): per-likelihood measurements + (``runtime``, ``memory_host``, ``compile`` ...) per setup and host class; +- ``walltime-validation@1`` (``autolens_inference/dashboard/walltime_validation.json``): + whole Nautilus stages, with wall time, likelihood evaluations and the implied cost + per evaluation; +- ``inference-summary@2`` (``autolens_inference/dashboard/catalogue.json``): full + pipeline runs, with their execution status and timings. + +A stage names what it is in ``campaign.yaml`` under ``evidence.keys``. The keys +(``dataset_type``, ``variant``, ``instrument``, ``regime``, ``setup_id``, +``host_class``, ``model_variant``, ``stage``) are opaque to PyAutoFit: they are compared +for equality with the same fields of each record and nothing is inferred from them. + +Every number carries one **grade**, best first: + +- ``measured-current``: a current measurement with exactly the stage's keys (a + walltime-validation or completed inference run, or a profiling record whose class + is designated by a Pulse decision); +- ``provisional``: current and exact, but its class is not designated (profiling + records are ``secondary`` with ``provisional_optimal`` until a human designation + decision exists, which today is all of them); +- ``analogue``: current, but the instrument or regime differs (which is said); +- ``superseded``: an exact match whose record a newer one replaced; +- ``estimated``: from a pilot or a previous run of the campaign itself, or scaled + from other numbers (e.g. evaluations × cost per evaluation); +- ``unsupported``: no record says anything. + +The word *optimal* is never derived here. A setup is called optimal only when a Pulse +designation decision (``decisions.yaml``, ``kind: designation``) names it for the +stage's likelihood, regime and hardware class; ``designation_for`` finds one. +""" +import json +import urllib.request +from dataclasses import dataclass, field +from pathlib import Path +from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Union + +import yaml + +GRADES = ( + "measured-current", + "provisional", + "analogue", + "superseded", + "estimated", + "unsupported", +) + +KEYS = ( + "dataset_type", + "variant", + "instrument", + "regime", + "setup_id", + "host_class", + "model_variant", + "stage", +) + +ANALOGUE_KEYS = ("instrument", "regime") +"""The keys that may differ for an ``analogue`` match; every other declared key must +be equal.""" + +HARDWARE_CLASS = { + "hpc_ral_cpu": "cpu_many_core", + "hpc_a100": "gpu_a100", + "local_gpu": "gpu_a100", + "local_laptop": "laptop", +} +"""Profiling host classes to the hardware classes of Pulse designation decisions.""" + +PER_CALL_KEYS = ( + "warm_iid_median_s", + "vmap.per_call", + "single_jit_median", + "single_jit_block", +) +"""Which ``values`` of a profiling ``runtime`` record is the cost of one likelihood +call, in order of preference when the record names none.""" + + +def grade_rank(grade: str) -> int: + return GRADES.index(grade) + + +def worst(*grades: str) -> str: + """ + The weakest of ``grades`` (a number built from several is no better than its + weakest input). + """ + return max(grades, key=grade_rank) + + +@dataclass +class EvidenceRecord: + """ + One record of a summary, reduced to what planning reads. + """ + + id: str + schema: str + keys: Dict[str, Optional[str]] + status: str + measurement: Optional[str] = None + values: Dict[str, float] = field(default_factory=dict) + unit: Optional[str] = None + record_class: Optional[str] = None + decision_id: Optional[str] = None + limitations: List[str] = field(default_factory=list) + measured_at: Optional[str] = None + source: Optional[str] = None + extra: Dict = field(default_factory=dict) + + @property + def provisional_class(self) -> bool: + return self.record_class != "optimal" or not self.decision_id + + +@dataclass +class EvidenceSet: + schema: str + version: int + source: str + generated_at: Optional[str] + records: List[EvidenceRecord] + + +@dataclass +class Match: + record: EvidenceRecord + grade: str + differs: Dict[str, Tuple[Optional[str], Optional[str]]] = field(default_factory=dict) + + def describe(self) -> str: + text = f"{self.record.id} [{self.grade}]" + if self.differs: + text += " (" + ", ".join( + f"{key} not recorded" if got is None else f"{key} {got} not {wanted}" + for key, (wanted, got) in self.differs.items() + ) + ")" + return text + + +def _read(source: Union[str, Path]) -> Dict: + source = str(source) + if source.startswith(("http://", "https://")): + with urllib.request.urlopen(source, timeout=60) as response: + return json.loads(response.read().decode("utf-8")) + return json.loads(Path(source).read_text()) + + +def _number_values(values) -> Dict[str, float]: + if not isinstance(values, dict): + return {} + return { + k: float(v) for k, v in values.items() if isinstance(v, (int, float)) and not isinstance(v, bool) + } + + +def _profiling_record(raw: Dict, source: str) -> EvidenceRecord: + likelihood = raw.get("likelihood") or {} + resources = raw.get("resources") or {} + throughput = raw.get("projected_node_throughput") or {} + return EvidenceRecord( + id=raw["id"], + schema="profiling-summary", + keys={ + "dataset_type": likelihood.get("dataset_type"), + "variant": likelihood.get("variant"), + "instrument": raw.get("instrument"), + "regime": raw.get("regime"), + "setup_id": raw.get("setup_id"), + "host_class": raw.get("host_class"), + "model_variant": raw.get("model_variant"), + "stage": None, + }, + status=raw.get("status") or "current", + measurement=raw.get("measurement"), + values=_number_values(raw.get("values")), + unit=raw.get("unit"), + record_class=raw.get("class"), + decision_id=raw.get("decision_id"), + limitations=[str(item) for item in raw.get("limitations") or []], + measured_at=raw.get("measured_at"), + source=source, + extra={ + "metric": raw.get("metric"), + "per_call_s": throughput.get("per_call_s"), + "per_call_source": throughput.get("per_call_source"), + "cpus_per_eval": resources.get("cpus_per_eval"), + "peak_rss_gb": resources.get("peak_rss_gb"), + }, + ) + + +def _walltime_record(raw: Dict, source: str) -> EvidenceRecord: + likelihood = raw.get("likelihood") or {} + values = { + key: raw[key] + for key in ("wall_s", "likelihood_evals", "implied_s_per_eval", "cores") + if isinstance(raw.get(key), (int, float)) + } + return EvidenceRecord( + id=raw["id"], + schema="walltime-validation", + keys={ + "dataset_type": likelihood.get("dataset_type"), + "variant": likelihood.get("variant"), + "instrument": raw.get("instrument"), + "regime": None, + "setup_id": raw.get("setup_id"), + "host_class": raw.get("host_class"), + "model_variant": raw.get("model_variant"), + "stage": raw.get("stage"), + }, + status="current", + measurement="stage_walltime", + values=_number_values(values), + unit="s", + source=source, + extra={ + "sampler": raw.get("sampler"), + "release_pin": raw.get("release_pin"), + "source_pixels": raw.get("source_pixels"), + "profiling_status": raw.get("profiling_status"), + }, + ) + + +def _inference_record(raw: Dict, source: str) -> Optional[EvidenceRecord]: + execution = raw.get("execution") or {} + if execution.get("completed") is not True: + # A failed or unknown run measures nothing a plan can use. + return None + likelihood = raw.get("likelihood") or {} + dataset = raw.get("dataset") or {} + timings = raw.get("timings") or {} + work = raw.get("work") or {} + configuration = raw.get("configuration") or {} + values = {} + for key in ("sampling_s", "wall_s", "fit_s"): + if isinstance(timings.get(key), (int, float)): + values[key] = timings[key] + if isinstance(work.get("likelihood_evaluations"), (int, float)): + values["likelihood_evaluations"] = work["likelihood_evaluations"] + return EvidenceRecord( + id=raw["id"], + schema="inference-summary", + keys={ + "dataset_type": likelihood.get("dataset_type"), + "variant": likelihood.get("variant"), + "instrument": dataset.get("instrument"), + "regime": None, + "setup_id": configuration.get("config_name"), + "host_class": raw.get("host_class"), + "model_variant": raw.get("model_variant"), + "stage": raw.get("stage"), + }, + status="superseded" if raw.get("archived") else "current", + measurement="pipeline_run", + values=_number_values(values), + unit="s", + measured_at=raw.get("measured_at"), + source=source, + ) + + +def read_evidence(source: Union[str, Path]) -> EvidenceSet: + """ + The records of a ``profiling-summary@3``, ``walltime-validation@1`` or + ``inference-summary@2`` file or URL (a PyAutoPulse snapshot is unwrapped). + + Raises + ------ + ValueError + If the document is none of the three, or another version of one of them. + """ + document = _read(source) + if "summary" in document and isinstance(document["summary"], dict): + document = document["summary"] + schema = document.get("schema") + version = document.get("version") + supported = { + ("profiling-summary", 3): _profiling_record, + ("walltime-validation", 1): _walltime_record, + ("inference-summary", 2): _inference_record, + } + reader = supported.get((schema, version)) + if reader is None: + raise ValueError( + f"{source}: {schema}@{version} is not a supported evidence schema " + f"({', '.join(f'{s}@{v}' for s, v in supported)})." + ) + records = [] + for raw in document.get("records") or []: + record = reader(raw, str(source)) + if record is not None: + records.append(record) + return EvidenceSet( + schema=schema, + version=version, + source=str(source), + generated_at=document.get("generated_at"), + records=records, + ) + + +def read_designations(source: Optional[Union[str, Path]]) -> List[Dict]: + """ + The ``kind: designation`` entries of a PyAutoPulse ``decisions.yaml`` (none when + ``source`` is ``None`` or the index holds none). + """ + if source is None: + return [] + raw = yaml.safe_load(Path(source).read_text()) or {} + return [ + entry + for entry in raw.get("decisions") or [] + if isinstance(entry, dict) and entry.get("kind") == "designation" + ] + + +def designation_for(keys: Dict[str, str], designations: Sequence[Dict]) -> Optional[Dict]: + """ + The designation decision covering ``keys`` (likelihood, regime and hardware class), + or ``None``. Only through this may a plan call a setup optimal. + """ + likelihood = f"{keys.get('dataset_type')}/{keys.get('variant')}" + hardware = HARDWARE_CLASS.get(keys.get("host_class") or "", keys.get("host_class")) + current = [ + d + for d in designations + if d.get("likelihood") == likelihood + and d.get("regime") == keys.get("regime") + and d.get("hardware_class") == hardware + ] + replaced = {d.get("supersedes") for d in current if d.get("supersedes")} + current = [d for d in current if d.get("id") not in replaced] + return current[-1] if current else None + + +def grade_of( + record: EvidenceRecord, + wanted: Dict[str, str], + designations: Sequence[Dict] = (), +) -> Optional[Match]: + """ + The match of ``record`` against the stage keys ``wanted`` (only the keys the stage + declares are compared), or ``None`` when it does not match even as an analogue. + """ + differs = {} + for key, value in wanted.items(): + if value is None or key not in KEYS: + continue + got = record.keys.get(key) + if got == value: + continue + if got is None and key == "stage" and record.schema == "profiling-summary": + # A profiling record is the cost of one likelihood call, which holds for + # every stage that runs that likelihood. + continue + if key in ANALOGUE_KEYS: + # Includes a schema that does not carry the key (walltime records have no + # regime): not a mismatch, but not a match either. + differs[key] = (value, got) + continue + return None + + if record.status in ("superseded", "archived"): + return None if differs else Match(record, "superseded") + if differs: + return Match(record, "analogue", differs) + return Match(record, _current_grade(record, designations)) + + +def _current_grade(record: EvidenceRecord, designations: Sequence[Dict]) -> str: + if record.schema != "profiling-summary": + return "measured-current" + if record.decision_id and any(d.get("id") == record.decision_id for d in designations): + return "measured-current" + return "provisional" + + +def matches( + evidence: Iterable[EvidenceSet], + wanted: Dict[str, str], + measurement: Optional[str] = None, + designations: Sequence[Dict] = (), +) -> List[Match]: + """ + Every record of ``evidence`` matching ``wanted`` (optionally one measurement kind), + best grade first, then newest. A stage that declares no keys matches nothing: with + nothing compared, any record would match. + """ + if not any(value is not None for key, value in wanted.items() if key in KEYS): + return [] + found = [] + for evidence_set in evidence: + for record in evidence_set.records: + if measurement is not None and record.measurement != measurement: + continue + match = grade_of(record, wanted, designations) + if match is not None: + found.append(match) + # Newest first (undated last), then a stable sort by grade. + found.sort(key=lambda m: m.record.measured_at or "", reverse=True) + found.sort(key=lambda m: grade_rank(m.grade)) + return found + + +def per_call_s(record: EvidenceRecord) -> Optional[float]: + """ + The cost of one likelihood call recorded by a profiling ``runtime`` record. + """ + if record.extra.get("per_call_s"): + return float(record.extra["per_call_s"]) + for key in PER_CALL_KEYS: + if key in record.values: + return record.values[key] + return None + + +def describe_limitation(text: str) -> str: + """ + A record's limitation as a plan may quote it: Pulse's ``provisional_optimal`` marker + is restated without the word, since only a designation decision may use it. + """ + if text.strip().startswith("provisional_optimal"): + return "provisional: no designation decision exists for this key" + return text diff --git a/autofit/campaign/pilot.py b/autofit/campaign/pilot.py new file mode 100644 index 000000000..eb1b6f6ee --- /dev/null +++ b/autofit/campaign/pilot.py @@ -0,0 +1,121 @@ +""" +``campaign pilot``: a small, stratified subset of a campaign to measure before the rest. + +The pilot is a list of campaign indices — a fraction of the manifest (default 2 %) +drawn evenly from bins of input size, so the large and small objects that set the +p95 wall time and the peak memory are both in it. Sizes come from a manifest field +(``size_field``) or from the size on disk of a templated path (``size_path``, filled +from the manifest fields like a success check); with neither, the draw is uniform. + +``write_pilot`` writes ``pilot.json`` (the indices, as a Slurm array spec, with the +bins they came from). **Nothing is submitted**: the file ends with the command a human +runs once they approve it, ``submit --indices ``, after which +``status`` measures the pilot and ``plan --pilot`` reads it. +""" +import json +import math +import random +from pathlib import Path +from typing import Dict, List, Optional + +from autofit.campaign.units import array_spec +from autofit.tools.util import open_atomic + +DEFAULT_FRACTION = 0.02 +DEFAULT_BINS = 5 + + +def object_sizes(campaign, size_field: Optional[str] = None, size_path: Optional[str] = None) -> Dict[int, float]: + """ + The size of each manifest object: a numeric manifest field, or the bytes on disk of + ``size_path`` formatted with the object's fields. Objects whose size cannot be read + are left out. + """ + sizes = {} + for index in campaign.indices(): + fields = campaign.fields(index) + try: + if size_field: + sizes[index] = float(fields[size_field]) + elif size_path: + sizes[index] = float(campaign.path(size_path.format(**fields)).stat().st_size) + except (KeyError, ValueError, OSError): + continue + return sizes + + +def pilot_indices( + campaign, + fraction: float = DEFAULT_FRACTION, + size_field: Optional[str] = None, + size_path: Optional[str] = None, + bins: int = DEFAULT_BINS, + seed: int = 0, +) -> Dict: + """ + A stratified pilot of ``campaign``: ``fraction`` of its objects (at least one per + size bin), drawn with ``seed`` so the same call gives the same pilot. + """ + indices = campaign.indices() + rng = random.Random(seed) + sizes = object_sizes(campaign, size_field, size_path) if (size_field or size_path) else {} + total = max(1, math.ceil(len(indices) * fraction)) + + if not sizes: + chosen = sorted(rng.sample(indices, min(total, len(indices)))) + return { + "indices": chosen, + "fraction": fraction, + "seed": seed, + "stratified_by": None, + "bins": [{"objects": len(indices), "chosen": len(chosen)}], + } + + ordered = sorted(sizes, key=lambda index: (sizes[index], index)) + bins = max(1, min(bins, len(ordered))) + strata = [ordered[len(ordered) * b // bins : len(ordered) * (b + 1) // bins] for b in range(bins)] + per_bin = max(1, math.ceil(total / bins)) + chosen = [] + summary = [] + for stratum in strata: + picked = rng.sample(stratum, min(per_bin, len(stratum))) + chosen += picked + summary.append( + { + "size_range": [sizes[stratum[0]], sizes[stratum[-1]]], + "objects": len(stratum), + "chosen": len(picked), + } + ) + return { + "indices": sorted(chosen), + "fraction": fraction, + "seed": seed, + "stratified_by": size_field or size_path, + "unsized_objects": len(indices) - len(sizes), + "bins": summary, + } + + +def write_pilot(directory, campaign, pilot: Dict, campaign_file: Optional[str] = None) -> Path: + """ + Write ``pilot.json`` into ``directory`` with the array spec and the (unrun) command + that would submit it. + """ + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + spec = array_spec(pilot["indices"]) + document = dict( + pilot, + campaign=campaign.name, + tasks=len(pilot["indices"]), + array_spec=spec, + submit_command=( + f"python -m autofit.campaign submit {campaign_file or campaign.source} --indices {spec}" + ), + note="Not submitted. Run the command once the pilot is approved.", + ) + path = directory / "pilot.json" + with open_atomic(path, "w") as f: + json.dump(document, f, indent=1) + return path diff --git a/autofit/campaign/plan.py b/autofit/campaign/plan.py new file mode 100644 index 000000000..3bdafcf0b --- /dev/null +++ b/autofit/campaign/plan.py @@ -0,0 +1,671 @@ +""" +``campaign plan``: what a campaign will need, before it is submitted, from evidence. + +For every stage the plan reads two kinds of evidence: + +- a **pilot**: the outcomes of tasks of this campaign (or a previous run of it) on this + site, as a ``tasks.jsonl`` written by ``status`` or ``retro``. Its numbers are graded + ``estimated`` (measured, but on a sample); +- the **published summaries** (``autofit.campaign.evidence``): the cost of one + likelihood call, host memory, and whole-stage wall times measured by the profiling + and inference projects, graded by how well their keys fit the stage. + +and proposes, per stage, the request a task should make: + +- **CPUs**: kept, unless the pilot's median CPU efficiency is below + ``CPU_EFFICIENCY_SHRINK``; then the largest power of two not above the CPUs it used; +- **memory**: the pilot's peak RSS × ``MEMORY_MARGIN``, rounded up to ``MEMORY_STEP_MB`` + (memory is a hard limit, so the maximum, not a quantile, sets it); +- **wall time**: the p95 of finished tasks × (1 + ``TIME_MARGIN``), per size bin when + the stage names a manifest ``size_field``, rounded up to ``TIME_STEP_S`` and capped at + the partition's ``max_time``. Timed-out tasks are kept at their limit (a lower bound), + so a p95 at the old limit is reported as censored rather than trusted; +- **throttle**: at most ``THROTTLE_FRACTION`` of the idle CPUs, in tasks. + +plus ETA (remaining CPU-hours ÷ the CPUs the throttle allows, times the pilot's +rerun factor), a disk forecast, and an energy placeholder that phase 4 (carbon) +fills. ``plan.json`` lists every record used with its grade; ``plan.md`` is the same +for a human to approve. Nothing is submitted. + +Every number is a ``Graded`` value: ``{"value": ..., "grade": ..., "sources": [...]}``. +""" +import json +import math +from collections import defaultdict +from datetime import datetime, timezone +from pathlib import Path +from typing import Dict, Iterable, List, Optional, Sequence + +from autofit.campaign.digest import TaskOutcome, percentile, read_outcomes +from autofit.campaign.evidence import ( + GRADES, + EvidenceSet, + designation_for, + describe_limitation, + matches, + per_call_s, + worst, +) +from autofit.campaign.lint import split_partitions +from autofit.campaign.units import format_time, parse_time +from autofit.tools.util import open_atomic + +SCHEMA = 1 + +CPU_EFFICIENCY_SHRINK = 0.6 +MEMORY_MARGIN = 1.25 +MEMORY_STEP_MB = 4096 +TIME_MARGIN = 0.25 +TIME_STEP_S = 900 +THROTTLE_FRACTION = 0.5 +SIZE_BINS = 3 + + +def graded(value, grade: str, sources: Sequence[str] = (), note: Optional[str] = None) -> Dict: + """ + A number with its evidence grade and the records or files it came from. + """ + entry = {"value": value, "grade": grade, "sources": list(sources)} + if note: + entry["note"] = note + return entry + + +def unsupported(note: str) -> Dict: + return graded(None, "unsupported", [], note) + + +def _round_up(value: float, step: float) -> int: + return int(math.ceil(value / step) * step) + + +def read_pilot(path) -> List[TaskOutcome]: + """ + The outcomes of a pilot: a ``tasks.jsonl``, or a directory holding one (the output + of ``status`` or ``retro``). + """ + path = Path(path) + return read_outcomes(path / "tasks.jsonl" if path.is_dir() else path) + + +def pilot_stats(outcomes: List[TaskOutcome], stage: str, source: str) -> Optional[Dict]: + """ + What a stage's pilot tasks measured: wall time over finished tasks (timeouts kept + at their limit, counted as censored), peak memory and CPU efficiency over completed + tasks, and the rerun factor (CPU-hours of every attempt over successful ones). + """ + tasks = [o for o in outcomes if o.stage == stage] + completed = [o for o in tasks if o.state == "completed"] + if not completed: + return None + timeouts = [o for o in tasks if o.state == "timeout"] + finished = completed + timeouts + walls = [o.elapsed_s for o in finished if o.elapsed_s] + rss = [o.max_rss_mb for o in completed if o.max_rss_mb] + efficiency = [o.cpu_efficiency for o in completed if o.cpu_efficiency is not None] + cpus = percentile([o.cpus for o in tasks if o.cpus], 50) + successful = sum(o.elapsed_s * o.cpus for o in completed if o.elapsed_s and o.cpus) + every = sum(o.cpu_s_all_attempts for o in tasks) + sizes = [o.bytes for o in completed if o.bytes] + limit = min((o.time_limit_s for o in timeouts if o.time_limit_s), default=None) + wall_p95 = percentile(walls, 95) + return { + "source": f"{source}#{stage}", + "tasks": len(tasks), + "completed": len(completed), + "timeouts": len(timeouts), + "cpus": cpus, + "wall_s": { + "p50": percentile(walls, 50), + "p95": wall_p95, + "max": max(walls) if walls else None, + }, + "wall_censored": bool(limit and wall_p95 and wall_p95 >= limit), + "rss_mb": { + "p50": percentile(rss, 50), + "p95": percentile(rss, 95), + "max": max(rss) if rss else None, + }, + "cpu_efficiency_p50": percentile(efficiency, 50), + "rerun_factor": (every / successful) if successful and every else None, + "bytes_per_result": (sum(sizes) / len(sizes)) if sizes else None, + "by_index": { + o.index: o.elapsed_s for o in finished if o.index is not None and o.elapsed_s + }, + } + + +def evidence_stats( + keys: Dict[str, str], + evidence: Sequence[EvidenceSet], + designations: Sequence[Dict] = (), + evals: Optional[float] = None, +) -> Dict: + """ + What the published summaries say about a stage with match keys ``keys``: the best + graded per-call cost, host memory, whole-stage wall time, and their scaling. + """ + stats = {"keys": keys} + used: List[Dict] = [] + + def note(match): + used.append( + { + "id": match.record.id, + "schema": match.record.schema, + "grade": match.grade, + "differs": {k: list(v) for k, v in match.differs.items()}, + "limitations": [describe_limitation(t) for t in match.record.limitations], + } + ) + + runtime = [m for m in matches(evidence, keys, "runtime", designations) if per_call_s(m.record)] + if runtime: + best = runtime[0] + note(best) + stats["per_call_s"] = graded(per_call_s(best.record), best.grade, [best.record.id]) + else: + stats["per_call_s"] = unsupported("no profiling runtime record matches the stage keys") + + memory = matches(evidence, keys, "memory_host", designations) + if memory and memory[0].record.values: + best = memory[0] + note(best) + value = next(iter(best.record.values.values())) + mb = value * 1.048576 if (best.record.unit or "").lower() == "mib" else value + stats["host_peak_rss_mb"] = graded(round(mb), best.grade, [best.record.id]) + elif runtime and runtime[0].record.extra.get("peak_rss_gb"): + # A runtime record's own resources block (sacct MaxRSS of the profiling leg). + best = runtime[0] + stats["host_peak_rss_mb"] = graded( + round(best.record.extra["peak_rss_gb"] * 1024), best.grade, [best.record.id], + "peak RSS recorded with the runtime measurement", + ) + else: + stats["host_peak_rss_mb"] = unsupported("no profiling memory record matches") + + walltime = [ + m for m in matches(evidence, keys, "stage_walltime", designations) if m.record.values.get("wall_s") + ] + if walltime: + best = walltime[0] + note(best) + values = best.record.values + stats["stage_wall_s"] = graded(values["wall_s"], best.grade, [best.record.id]) + stats["likelihood_evals"] = graded( + values.get("likelihood_evals"), best.grade, [best.record.id] + ) + stats["implied_s_per_eval"] = graded( + values.get("implied_s_per_eval"), best.grade, [best.record.id] + ) + else: + stats["stage_wall_s"] = unsupported("no walltime-validation record matches the stage") + + # Scaling: evaluations × cost per evaluation is an estimate whatever its inputs. + n_evals = ( + graded(evals, "estimated", ["campaign.yaml evidence.evals"]) + if evals + else stats.get("likelihood_evals") + ) + cost = stats.get("implied_s_per_eval") or stats["per_call_s"] + if n_evals and n_evals.get("value") and cost.get("value"): + stats["scaled_wall_s"] = graded( + n_evals["value"] * cost["value"], + worst(n_evals["grade"], cost["grade"], "estimated"), + n_evals["sources"] + cost["sources"], + "likelihood evaluations × cost per evaluation", + ) + else: + stats["scaled_wall_s"] = unsupported("needs both a number of evaluations and a cost per evaluation") + + designation = designation_for(keys, designations) + stats["designation"] = ( + {"decision": designation["id"], "optimal": designation.get("optimal")} + if designation + else None + ) + stats["records"] = used + return stats + + +def _size_bins(campaign, stage, pilot, n_bins: int = SIZE_BINS) -> Optional[List[Dict]]: + field_name = stage.evidence.get("size_field") + if not field_name or not pilot or not pilot["by_index"]: + return None + sizes = {} + for index in campaign.indices(): + try: + sizes[index] = float(campaign.fields(index)[field_name]) + except (KeyError, ValueError): + continue + if not sizes: + return None + ordered = sorted(sizes.values()) + edges = [ordered[min(len(ordered) - 1, int(len(ordered) * i / n_bins))] for i in range(1, n_bins)] + bins = defaultdict(list) + population = defaultdict(int) + + def bin_of(size): + return sum(1 for edge in edges if size > edge) + + for index, size in sizes.items(): + population[bin_of(size)] += 1 + for index, wall in pilot["by_index"].items(): + if index in sizes: + bins[bin_of(sizes[index])].append(wall) + lows = [ordered[0]] + edges + highs = edges + [ordered[-1]] + result = [] + for number in range(n_bins): + walls = bins.get(number, []) + p95 = percentile(walls, 95) + result.append( + { + "bin": number, + "size_range": [lows[number], highs[number]], + "objects": population.get(number, 0), + "pilot_tasks": len(walls), + "wall_p95_s": p95, + } + ) + return result + + +def _max_time(stage, site) -> Optional[int]: + if site is None: + return None + limits = [] + for name in split_partitions(stage.resources.partition): + partition = site.partitions.get(name) + if partition is not None and partition.max_time: + limits.append(parse_time(partition.max_time)) + return min(limits) if limits else None + + +def _proposed_time(wall_p95, max_time) -> int: + seconds = _round_up(wall_p95 * (1 + TIME_MARGIN), TIME_STEP_S) + return min(seconds, max_time) if max_time else seconds + + +def propose(stage, pilot: Optional[Dict], evidence: Dict, site=None, idle_cpus: Optional[Dict] = None) -> Dict: + """ + The proposed request for ``stage`` (see the module docstring for the rules), each + value graded by what it rests on. + """ + request = stage.resources + proposal = {} + pilot_source = [pilot["source"]] if pilot else [] + + # CPUs. + efficiency = pilot["cpu_efficiency_p50"] if pilot else None + if pilot and efficiency is not None and efficiency < CPU_EFFICIENCY_SHRINK: + used = (pilot["cpus"] or request.cpus) * efficiency + cpus = 2 ** int(math.floor(math.log2(max(used, 1.0)))) + proposal["cpus"] = graded( + cpus, "estimated", pilot_source, + f"median CPU efficiency {efficiency:.2f} < {CPU_EFFICIENCY_SHRINK}: {used:.1f} CPUs used; " + f"wall times were measured at {pilot['cpus'] or request.cpus:g} CPUs, so re-pilot at {cpus}", + ) + elif pilot: + proposal["cpus"] = graded(int(pilot["cpus"] or request.cpus), "estimated", pilot_source) + else: + proposal["cpus"] = graded(request.cpus, "unsupported", [], "the stage's own request; no pilot") + cpus = proposal["cpus"]["value"] + + # Memory. + peak = pilot["rss_mb"]["max"] if pilot else None + if peak: + mem = _round_up(peak * MEMORY_MARGIN, MEMORY_STEP_MB) + proposal["mem_mb"] = graded(mem, "estimated", pilot_source, f"peak {peak:.0f} MB × {MEMORY_MARGIN}") + elif evidence["host_peak_rss_mb"]["value"]: + host = evidence["host_peak_rss_mb"] + mem = _round_up(host["value"] * MEMORY_MARGIN, MEMORY_STEP_MB) + proposal["mem_mb"] = graded(mem, worst(host["grade"], "estimated"), host["sources"], "host peak × margin") + else: + proposal["mem_mb"] = graded(request.mem_mb, "unsupported", [], "the stage's own request") + if proposal["mem_mb"]["value"]: + proposal["mem_per_cpu_mb"] = dict( + proposal["mem_mb"], value=int(-(-proposal["mem_mb"]["value"] // cpus)) + ) + + # Wall time. + max_time = _max_time(stage, site) + if pilot and pilot["wall_s"]["p95"]: + seconds = _proposed_time(pilot["wall_s"]["p95"], max_time) + note = f"p95 {format_time(pilot['wall_s']['p95'])} + {TIME_MARGIN:.0%}" + if pilot["wall_censored"]: + note += "; censored: the p95 is at the old time limit, so the real p95 is higher — re-pilot at the new limit" + proposal["time_s"] = graded(seconds, "estimated", pilot_source, note) + else: + basis = evidence["stage_wall_s"] if evidence["stage_wall_s"]["value"] else evidence["scaled_wall_s"] + if basis["value"]: + seconds = _proposed_time(basis["value"], max_time) + proposal["time_s"] = graded( + seconds, worst(basis["grade"], "estimated"), basis["sources"], + "one measured stage + margin: no spread is known, so re-pilot", + ) + else: + proposal["time_s"] = graded(request.time_s, "unsupported", [], "the stage's own request") + if max_time and proposal["time_s"]["value"] and proposal["time_s"]["value"] >= max_time: + proposal["time_s"]["note"] = (proposal["time_s"].get("note", "") + f"; capped at the partition max_time").strip("; ") + proposal["time"] = dict(proposal["time_s"], value=format_time(proposal["time_s"]["value"])) + + # Throttle. + idle = idle_cpus or {} + partition = split_partitions(request.partition)[0] if request.partition else None + idle_entry = idle.get(partition) or idle.get("*") + if idle_entry and idle_entry["value"]: + throttle = max(1, int(idle_entry["value"] * THROTTLE_FRACTION // cpus)) + proposal["throttle"] = graded( + throttle, worst(idle_entry["grade"], "estimated"), idle_entry["sources"], + f"{THROTTLE_FRACTION:.0%} of {idle_entry['value']} idle CPUs", + ) + else: + proposal["throttle"] = graded(request.throttle, "unsupported", [], "no capacity snapshot") + return proposal + + +def _eta(n_tasks, pilot, evidence, proposal) -> Dict: + if pilot and pilot["wall_s"]["p50"]: + wall = graded(pilot["wall_s"]["p50"], "estimated", [pilot["source"]]) + elif evidence["stage_wall_s"]["value"]: + wall = evidence["stage_wall_s"] + else: + wall = evidence["scaled_wall_s"] + cpus = proposal["cpus"]["value"] + rerun = (pilot or {}).get("rerun_factor") or 1.0 + if not wall["value"] or not cpus: + return {"cpu_h": unsupported("no wall time"), "eta_s": unsupported("no wall time")} + cpu_h = n_tasks * wall["value"] * cpus * rerun / 3600 + sources = wall["sources"] + result = { + "cpu_h": graded(round(cpu_h, 1), worst(wall["grade"], "estimated"), sources, + f"{n_tasks} tasks × p50 wall × {cpus} CPUs × rerun factor {rerun:.2f}"), + } + throttle = proposal["throttle"] + if throttle["value"]: + concurrent = throttle["value"] * cpus + result["eta_s"] = graded( + round(cpu_h * 3600 / concurrent), + worst(result["cpu_h"]["grade"], throttle["grade"]), + sources + throttle["sources"], + f"at {concurrent} CPUs at once", + ) + else: + result["eta_s"] = unsupported("no throttle: no capacity snapshot") + return result + + +def _disk(n_tasks, pilot, results_index: Optional[Dict], stage) -> Dict: + if pilot and pilot.get("bytes_per_result"): + per = graded(pilot["bytes_per_result"], "estimated", [pilot["source"]]) + else: + names = set(stage.evidence.get("result_names") or [stage.name]) + sizes = (results_index or {}).get("sizes", {}) + found = [size for name in names for size in sizes.get(name, [])] + if not found: + return {"bytes": unsupported("no pilot sizes and no results index for the stage")} + per = graded(sum(found) / len(found), "estimated", [f"{results_index['source']} ({len(found)} results)"]) + return { + "bytes_per_result": dict(per, value=int(per["value"])), + "bytes": dict(per, value=int(per["value"] * n_tasks)), + } + + +def read_results_index(path) -> Dict: + """ + Result sizes per search name from a results index (``python -m autofit.results + index``): its per-result JSON records under ``records/``, read as plain JSON. + """ + path = Path(path) + sizes = defaultdict(list) + for record_path in sorted((path / "records").glob("*.json")): + try: + record = json.loads(record_path.read_text()) + except (OSError, ValueError): + continue + if record.get("state") == "completed" and record.get("bytes"): + sizes[record.get("name")].append(record["bytes"]) + return {"source": str(path), "sizes": dict(sizes)} + + +def build_plan( + campaign, + evidence: Sequence[EvidenceSet] = (), + pilot: Optional[List[TaskOutcome]] = None, + pilot_source: Optional[str] = None, + designations: Sequence[Dict] = (), + idle_cpus: Optional[Dict] = None, + results_index: Optional[Dict] = None, + decisions_source: Optional[str] = None, + now: Optional[datetime] = None, +) -> Dict: + """ + The plan of ``campaign`` (see the module docstring). + + Parameters + ---------- + evidence + Summaries read by ``autofit.campaign.evidence.read_evidence``. + pilot + Pilot outcomes (``read_pilot``) and the file they came from. + designations + Pulse designation decisions (``read_designations``). + idle_cpus + Idle CPUs per partition (or ``"*"``) as graded values, from a live capacity + snapshot or stated by hand. + results_index + Result sizes per search name (``read_results_index``), for the disk forecast. + """ + site = campaign.site if campaign.site_name else None + n_tasks = len(campaign.indices()) + stages = {} + records: Dict[str, Dict] = {} + for name in campaign.order(): + stage = campaign.stages[name] + keys = dict((stage.evidence or {}).get("keys") or {}) + stage_pilot = pilot_stats(pilot, name, pilot_source or "pilot") if pilot else None + ev = evidence_stats(keys, evidence, designations, stage.evidence.get("evals")) + proposal = propose(stage, stage_pilot, ev, site=site, idle_cpus=idle_cpus) + eta = _eta(n_tasks, stage_pilot, ev, proposal) + bins = _size_bins(campaign, stage, stage_pilot) + if bins: + max_time = _max_time(stage, site) + for entry in bins: + if entry["wall_p95_s"]: + entry["time"] = graded( + format_time(_proposed_time(entry["wall_p95_s"], max_time)), + "estimated", [stage_pilot["source"]], + ) + else: + entry["time"] = unsupported("no pilot task in this bin") + cpu_h = eta["cpu_h"] + mem = proposal["mem_mb"]["value"] + energy = { + "status": "placeholder: hpc-campaign phase 4 (carbon) fills energy from these", + "cpu_h": cpu_h, + "mem_gb_h": graded( + round(cpu_h["value"] / proposal["cpus"]["value"] * mem / 1024, 1) + if cpu_h["value"] and mem else None, + worst(cpu_h["grade"], proposal["mem_mb"]["grade"]), + cpu_h["sources"] + proposal["mem_mb"]["sources"], + ), + } + for record in ev["records"]: + records[record["id"]] = record + stages[name] = { + "keys": keys, + "request": { + "cpus": stage.resources.cpus, + "mem_mb": stage.resources.mem_mb, + "time": format_time(stage.resources.time_s), + "partition": stage.resources.partition, + "throttle": stage.resources.throttle, + }, + "pilot": {k: v for k, v in (stage_pilot or {}).items() if k != "by_index"} or None, + "evidence": {k: v for k, v in ev.items() if k != "records"}, + "proposal": proposal, + "size_bins": bins, + "eta": eta, + "disk": _disk(n_tasks, stage_pilot, results_index, stage), + "energy": energy, + } + + graded_values = list(_graded_values(stages)) + counts = {grade: sum(1 for g in graded_values if g == grade) for grade in GRADES} + etas = [s["eta"]["eta_s"] for s in stages.values()] + total_eta = ( + graded( + sum(e["value"] for e in etas), + worst(*(e["grade"] for e in etas)), + sorted({src for e in etas for src in e["sources"]}), + "stages one after another: an upper bound, since aftercorr overlaps them", + ) + if etas and all(e["value"] for e in etas) + else unsupported("a stage has no ETA") + ) + return { + "schema": SCHEMA, + "campaign": campaign.name, + "created": (now or datetime.now(timezone.utc)).strftime("%Y-%m-%dT%H:%M:%SZ"), + "objects": n_tasks, + "inputs": { + "evidence": [ + {"source": e.source, "schema": f"{e.schema}@{e.version}", "generated_at": e.generated_at, + "records": len(e.records)} + for e in evidence + ], + "pilot": pilot_source, + "decisions": decisions_source, + "designations": len(designations), + }, + "stages": stages, + "totals": { + "eta_s": total_eta, + "cpu_h": graded( + round(sum(s["eta"]["cpu_h"]["value"] or 0 for s in stages.values()), 1), + worst(*(s["eta"]["cpu_h"]["grade"] for s in stages.values())) if stages else "unsupported", + sorted({src for s in stages.values() for src in s["eta"]["cpu_h"]["sources"]}), + ), + }, + "grade_counts": counts, + "records": sorted(records.values(), key=lambda r: r["id"]), + } + + +def _graded_values(node): + if isinstance(node, dict): + if "grade" in node and "value" in node: + yield node["grade"] + return + for value in node.values(): + yield from _graded_values(value) + elif isinstance(node, list): + for value in node: + yield from _graded_values(value) + + +def _cell(entry: Optional[Dict], render=lambda v: v) -> str: + if not entry: + return "-" + if entry.get("value") is None: + return f"— ({entry['grade']})" + return f"{render(entry['value'])} ({entry['grade']})" + + +def _hours(seconds) -> str: + return f"{seconds / 3600:.1f} h" + + +def plan_markdown(plan: Dict) -> str: + """ + ``plan`` for a human to read and approve. + """ + lines = [ + f"# Plan: {plan['campaign']} — {plan['created']}", + "", + f"{plan['objects']} objects. Every number carries its evidence grade " + f"({', '.join(GRADES)}); nothing here is submitted.", + "", + "| stage | CPUs | memory | time | throttle | CPU-h | ETA |", + "|---|---|---|---|---|---|---|", + ] + for name, stage in plan["stages"].items(): + proposal = stage["proposal"] + lines.append( + f"| {name} | {_cell(proposal['cpus'])} | " + f"{_cell(proposal['mem_mb'], lambda v: f'{v / 1024:.0f} GB')} | " + f"{_cell(proposal['time'])} | {_cell(proposal['throttle'])} | " + f"{_cell(stage['eta']['cpu_h'], lambda v: f'{v:,.0f}')} | " + f"{_cell(stage['eta']['eta_s'], _hours)} |" + ) + totals = plan["totals"] + lines += [ + "", + f"Total: {_cell(totals['cpu_h'], lambda v: f'{v:,.0f} CPU-h')}; " + f"ETA {_cell(totals['eta_s'], _hours)} ({totals['eta_s'].get('note', '')}).", + "", + "Grades used: " + ", ".join(f"{g} {n}" for g, n in plan["grade_counts"].items() if n) + ".", + ] + for name, stage in plan["stages"].items(): + lines += ["", f"## {name}", ""] + request = stage["request"] + lines.append( + f"Requested now: {request['cpus']} CPUs, " + f"{(request['mem_mb'] or 0) / 1024:.0f} GB, {request['time']}, " + f"partition {request['partition']}." + ) + for key, entry in stage["proposal"].items(): + if key in ("time_s", "mem_per_cpu_mb"): + continue + note = f" — {entry['note']}" if entry.get("note") else "" + lines.append(f"- {key}: {_cell(entry)}{note}") + ev = stage["evidence"] + lines.append( + f"- evidence: per-call {_cell(ev['per_call_s'], lambda v: f'{v:.3g} s')}, " + f"host memory {_cell(ev['host_peak_rss_mb'], lambda v: f'{v} MB')}, " + f"stage wall {_cell(ev['stage_wall_s'], _hours)}, " + f"scaled wall {_cell(ev['scaled_wall_s'], _hours)}" + ) + if ev["designation"]: + lines.append( + f"- optimal setup per Pulse decision {ev['designation']['decision']}: " + f"{ev['designation']['optimal']}" + ) + else: + lines.append("- designation: none recorded for these keys") + if stage["size_bins"]: + lines.append( + "- by size: " + + "; ".join( + f"{b['size_range'][0]:g}–{b['size_range'][1]:g} ({b['objects']} objects): {_cell(b['time'])}" + for b in stage["size_bins"] + ) + ) + disk = stage["disk"] + lines.append(f"- disk: {_cell(disk['bytes'], lambda v: f'{v / 1e9:.1f} GB')}") + if plan["records"]: + lines += ["", "## Records used", ""] + for record in plan["records"]: + differs = ", ".join( + f"{k} not recorded (wanted {v[0]})" if v[1] is None else f"{k} {v[1]} not {v[0]}" + for k, v in record["differs"].items() + ) + lines.append( + f"- `{record['id']}` ({record['schema']}, {record['grade']})" + + (f" — differs: {differs}" if differs else "") + ) + return "\n".join(lines) + "\n" + + +def write_plan(directory, plan: Dict) -> Path: + """ + Write ``plan.json`` and ``plan.md`` into ``directory`` (atomically, each). + """ + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + with open_atomic(directory / "plan.json", "w") as f: + json.dump(plan, f, indent=1, default=str) + with open_atomic(directory / "plan.md", "w") as f: + f.write(plan_markdown(plan)) + return directory diff --git a/autofit/campaign/spec.py b/autofit/campaign/spec.py index f64563c6c..ebc950bda 100644 --- a/autofit/campaign/spec.py +++ b/autofit/campaign/spec.py @@ -31,6 +31,14 @@ ``CAMPAIGN_INDEX = CAMPAIGN_OFFSET + SLURM_ARRAY_TASK_ID``, so per-index dependencies (``aftercorr``) line up between stages chunk by chunk. +``evidence`` names what a stage is, for ``python -m autofit.campaign plan`` +(``autofit.campaign.evidence``): ``keys`` are opaque match keys compared with the +profiling and inference summaries (``dataset_type``, ``variant``, ``instrument``, +``regime``, ``setup_id``, ``host_class``, ``model_variant``, ``stage``), ``size_field`` +a manifest field to bin wall times by, ``evals`` the likelihood evaluations a fit of the +stage takes (to scale a per-call cost), and ``result_names`` the search names of its +results (for the disk forecast). + ``retry`` is a policy for *proposals* only: the collector proposes resubmits sized from the failed tasks' own measurements and a human approves every one. """ @@ -57,7 +65,18 @@ "stages", "note", } -STAGE_FIELDS = {"script", "env", "resources", "after", "seed", "success", "retry", "note"} +STAGE_FIELDS = { + "script", + "env", + "resources", + "after", + "seed", + "success", + "retry", + "evidence", + "note", +} +EVIDENCE_FIELDS = {"keys", "size_field", "evals", "result_names"} RESOURCE_FIELDS = { "cpus", "mem_per_cpu_mb", @@ -145,6 +164,7 @@ class Stage: seed: Optional[str] = None success: Success = field(default_factory=Success) retry: Dict[str, Dict] = field(default_factory=dict) + evidence: Dict = field(default_factory=dict) class Campaign: @@ -186,6 +206,7 @@ def __init__(self, raw: Dict, source: Optional[Path] = None): members=list(success.get("members") or []), ), retry=dict(stage.get("retry") or {}), + evidence=dict(stage.get("evidence") or {}), ) self._site = None self._manifest = None @@ -407,6 +428,7 @@ def validate(self) -> List[str]: f"{where}.after.{upstream}: {kind!r} is not one of " f"{sorted(DEPENDENCY_KINDS)}" ) + errors += _evidence_errors(where, raw_stage.get("evidence")) for failure, policy in (raw_stage.get("retry") or {}).items(): if failure not in RETRY_CLASSES: errors.append(f"{where}.retry: unknown failure class {failure!r}") @@ -465,3 +487,29 @@ def _resource_errors(self, where: str, stage: Stage, site) -> List[str]: if not verdict.ok: errors.append(f"{where}.resources.partition: " + "; ".join(verdict.reasons)) return errors + + +def _evidence_errors(where: str, evidence) -> List[str]: + if evidence is None: + return [] + if not isinstance(evidence, dict): + return [f"{where}.evidence: must be a mapping"] + from autofit.campaign.evidence import KEYS + + errors = [] + unknown = set(evidence) - EVIDENCE_FIELDS + if unknown: + errors.append(f"{where}.evidence: unknown keys {sorted(unknown)}") + keys = evidence.get("keys") or {} + if not isinstance(keys, dict): + errors.append(f"{where}.evidence.keys: must be a mapping") + else: + unknown = set(keys) - set(KEYS) + if unknown: + errors.append( + f"{where}.evidence.keys: unknown keys {sorted(unknown)} (one of {list(KEYS)})" + ) + evals = evidence.get("evals") + if evals is not None and (not isinstance(evals, (int, float)) or evals <= 0): + errors.append(f"{where}.evidence.evals: must be a positive number") + return errors diff --git a/test_autofit/campaign/test_plan.py b/test_autofit/campaign/test_plan.py new file mode 100644 index 000000000..7a2a3f15e --- /dev/null +++ b/test_autofit/campaign/test_plan.py @@ -0,0 +1,539 @@ +""" +Evidence grades, ``campaign plan`` and ``campaign pilot``. + +The DR1 repack test rebuilds the measurements behind the 2026-09-25/27 RAL repack +(vis_lp peak 4.1 GB at 53 % of 8 CPUs; vis_pix 11 GB at 83 %; SED 3.7 GB at 72 %) as a +``sacct`` dump and checks that ``plan`` proposes what the human chose by hand (vis_lp +12 GB / 4 CPUs, vis_pix 16 GB / 8, SED 8 GB / 8) within the stated tolerance: CPUs +exact, memory within one ``MEMORY_STEP_MB`` rounding step. +""" +import json +import re + +import pytest + +from autofit.campaign.__main__ import main +from autofit.campaign.digest import write_digest +from autofit.campaign.evidence import ( + designation_for, + grade_of, + matches, + read_designations, + read_evidence, + worst, +) +from autofit.campaign.pilot import pilot_indices, write_pilot +from autofit.campaign.plan import ( + MEMORY_STEP_MB, + build_plan, + plan_markdown, + read_pilot, + write_plan, +) +from autofit.campaign.retro import retro +from autofit.campaign.spec import Campaign +from test_autofit.campaign.conftest import write_campaign +from test_autofit.campaign.test_sacct import HEADER + +PROFILING = { + "schema": "profiling-summary", + "version": 3, + "generated_at": "2026-10-29T09:46:25Z", + "records": [ + { + "id": "lifecycle/euclid-mge-current", + "class": "secondary", + "decision_id": None, + "status": "current", + "measurement": "runtime", + "metric": "single_jit_block", + "unit": "s", + "likelihood": {"dataset_type": "imaging", "variant": "mge"}, + "instrument": "euclid", + "regime": "standard", + "setup_id": "jax_cpu_dense_fp64", + "host_class": "hpc_ral_cpu", + "model_variant": "default", + "limitations": ["provisional_optimal: true"], + "measured_at": "2026-10-20T00:00:00Z", + "values": {"single_jit_block": 0.2, "vmap.per_call": 0.05}, + "projected_node_throughput": {"per_call_s": 0.05, "per_call_source": "vmap.per_call"}, + "resources": {"cpus_per_eval": 1, "peak_rss_gb": 2.0}, + }, + { + "id": "lifecycle/euclid-mge-old", + "class": "secondary", + "status": "superseded", + "measurement": "runtime", + "unit": "s", + "likelihood": {"dataset_type": "imaging", "variant": "mge"}, + "instrument": "euclid", + "regime": "standard", + "setup_id": "jax_cpu_dense_fp64", + "host_class": "hpc_ral_cpu", + "model_variant": "default", + "values": {"vmap.per_call": 0.09}, + }, + { + "id": "lifecycle/hst-mge-current", + "class": "secondary", + "status": "current", + "measurement": "runtime", + "unit": "s", + "likelihood": {"dataset_type": "imaging", "variant": "mge"}, + "instrument": "hst", + "regime": "standard", + "setup_id": "jax_cpu_dense_fp64", + "host_class": "hpc_ral_cpu", + "model_variant": "default", + "values": {"vmap.per_call": 0.08}, + }, + { + "id": "lifecycle/euclid-mge-memory", + "class": "secondary", + "status": "current", + "measurement": "memory_host", + "metric": "host_peak_rss", + "unit": "MiB", + "likelihood": {"dataset_type": "imaging", "variant": "mge"}, + "instrument": "euclid", + "regime": "standard", + "setup_id": "jax_cpu_dense_fp64", + "host_class": "hpc_ral_cpu", + "model_variant": "default", + "values": {"host_peak_rss": 3000.0}, + }, + { + "id": "lifecycle/euclid-rect-gpu", + "class": "secondary", + "status": "current", + "measurement": "runtime", + "unit": "s", + "likelihood": {"dataset_type": "imaging", "variant": "rectangular"}, + "instrument": "euclid", + "regime": "standard", + "setup_id": "jax_gpu_dense_fp64", + "host_class": "hpc_a100", + "model_variant": "default", + "values": {"vmap.per_call": 0.01}, + }, + ], +} + +WALLTIME = { + "schema": "walltime-validation", + "version": 1, + "generated_at": "2026-10-28T00:00:00Z", + "records": [ + { + "id": "imaging/mge/hst/default/jax_cpu_dense_fp64/hpc_ral_cpu/nautilus:source_lp[1]/seed_1", + "likelihood": {"dataset_type": "imaging", "variant": "mge"}, + "instrument": "hst", + "setup_id": "jax_cpu_dense_fp64", + "host_class": "hpc_ral_cpu", + "model_variant": "default", + "stage": "source_lp[1]", + "wall_s": 3600.0, + "likelihood_evals": 40000, + "implied_s_per_eval": 0.09, + "cores": 8, + } + ], +} + +INFERENCE = { + "schema": "inference-summary", + "version": 2, + "records": [ + {"id": "run/failed", "execution": {"completed": None}, "likelihood": {}, "dataset": {}}, + { + "id": "run/done", + "execution": {"completed": True}, + "likelihood": {"dataset_type": "imaging", "variant": "mge"}, + "dataset": {"instrument": "euclid"}, + "host_class": "hpc_ral_cpu", + "model_variant": "default", + "stage": "source_lp[1]", + "configuration": {"config_name": "jax_cpu_dense_fp64"}, + "timings": {"sampling_s": 1200.0}, + "work": {"likelihood_evaluations": None}, + }, + ], +} + +DESIGNATIONS = """ +decisions: +- id: some-other-decision + title: not a designation +- id: imaging-mge-standard-cpu + kind: designation + likelihood: imaging/mge + regime: standard + hardware_class: cpu_many_core + optimal: jax_cpu_dense_fp64 + secondary: [] + evidence: [lifecycle/euclid-mge-current] + rule: one sentence + supersedes: null +""" + +KEYS = { + "dataset_type": "imaging", + "variant": "mge", + "instrument": "euclid", + "regime": "standard", + "setup_id": "jax_cpu_dense_fp64", + "host_class": "hpc_ral_cpu", + "model_variant": "default", +} + + +def _write(tmp_path, name, document): + path = tmp_path / name + path.write_text(json.dumps(document)) + return path + + +@pytest.fixture(name="evidence") +def make_evidence(tmp_path): + return [ + read_evidence(_write(tmp_path, "profiling.json", PROFILING)), + read_evidence(_write(tmp_path, "walltime.json", WALLTIME)), + read_evidence(_write(tmp_path, "inference.json", INFERENCE)), + ] + + +def test_read_evidence_schemas_and_pulse_snapshot(tmp_path, evidence): + assert [e.schema for e in evidence] == [ + "profiling-summary", + "walltime-validation", + "inference-summary", + ] + # A failed inference run measures nothing. + assert [r.id for r in evidence[2].records] == ["run/done"] + snapshot = read_evidence(_write(tmp_path, "lens.json", {"instance": "lens", "summary": PROFILING})) + assert len(snapshot.records) == 5 + with pytest.raises(ValueError, match="not a supported evidence schema"): + read_evidence(_write(tmp_path, "v2.json", dict(PROFILING, version=2))) + + +def test_grades(evidence): + found = {m.record.id: m for m in matches(evidence, KEYS)} + assert found["lifecycle/euclid-mge-current"].grade == "provisional" + assert found["lifecycle/euclid-mge-old"].grade == "superseded" + hst = found["lifecycle/hst-mge-current"] + assert hst.grade == "analogue" + assert hst.differs == {"instrument": ("euclid", "hst")} + # Setup and host class are not analogue keys: a GPU record does not match. + assert "lifecycle/euclid-rect-gpu" not in found + # Best first. + assert matches(evidence, KEYS, "runtime")[0].record.id == "lifecycle/euclid-mge-current" + + +def test_stage_key_and_missing_regime(evidence): + keys = dict(KEYS, stage="source_lp[1]") + found = {m.record.id: m for m in matches(evidence, keys)} + # A profiling record is per call, so the stage key does not exclude it. + assert found["lifecycle/euclid-mge-current"].grade == "provisional" + # Walltime records carry no regime and are HST here: analogue, saying both. + walltime = found[WALLTIME["records"][0]["id"]] + assert walltime.grade == "analogue" + assert set(walltime.differs) == {"instrument", "regime"} + # The completed inference run matches exactly except the regime it lacks. + assert found["run/done"].grade == "analogue" + + +def test_designation_turns_provisional_into_measured_current(tmp_path, evidence): + designations = read_designations(_write_text(tmp_path, "decisions.yaml", DESIGNATIONS)) + assert [d["id"] for d in designations] == ["imaging-mge-standard-cpu"] + assert designation_for(KEYS, designations)["optimal"] == "jax_cpu_dense_fp64" + assert designation_for(dict(KEYS, host_class="hpc_a100"), designations) is None + + record = evidence[0].records[0] + record.record_class, record.decision_id = "optimal", "imaging-mge-standard-cpu" + assert grade_of(record, KEYS, designations).grade == "measured-current" + assert grade_of(record, KEYS, []).grade == "provisional" + + +def test_no_keys_match_nothing(evidence): + assert matches(evidence, {}) == [] + assert matches(evidence, {"colour": "red"}) == [] + + +def test_worst(): + assert worst("provisional", "analogue", "measured-current") == "analogue" + assert worst("estimated", "unsupported") == "unsupported" + + +def _write_text(tmp_path, name, text): + path = tmp_path / name + path.write_text(text) + return path + + +# --- the DR1 repack, from a sacct fixture ------------------------------------------- + +REPACK = { + # stage: (tasks, peak RSS MB at the largest task, CPU efficiency, wall h) + "vis_lp": (40, 4198, 0.53, 1.5), + "vis_pix": (40, 11264, 0.83, 9.1), + "sed": (40, 3789, 0.72, 0.2), +} +CHOSEN = {"vis_lp": (4, 12288), "vis_pix": (8, 16384), "sed": (8, 8192)} + + +def _clock(seconds): + seconds = int(seconds) + days, rest = divmod(seconds, 86400) + clock = f"{rest // 3600:02d}:{rest % 3600 // 60:02d}:{rest % 60:02d}" + return f"{days}-{clock}" if days else clock + + +def repack_dump(path): + rows = [HEADER] + job = 100 + for stage, (n, peak, efficiency, hours) in REPACK.items(): + job += 1 + for task in range(n): + scale = 0.7 + 0.3 * task / (n - 1) # the last task is the largest + wall = hours * 3600 * scale + rss = peak * scale + cpu = wall * 8 * efficiency + raw = job * 1000 + task + common = f"|ral|COMPLETED|0:0|2026-09-25T00:00:00|2026-09-25T00:00:00|2026-09-25T10:00:00|{_clock(wall)}" + rows.append( + f"{job}_{task}|{raw}|euclid_dr1_{stage}_n5k{common}|1-00:00:00|8|65536M|||" + f"{_clock(cpu)}|{_clock(wall * 8)}|1|n1|cpu=8|cpu=8|/m/euclid_dr1/hpc" + ) + rows.append( + f"{job}_{task}.batch|{raw}.batch|batch{common}||8||{rss:.0f}M|{rss:.0f}M|" + f"{_clock(cpu)}|{_clock(wall * 8)}|1|n1||cpu=8|" + ) + path.write_text("\n".join(rows) + "\n") + return path + + +REPACK_CAMPAIGN = """ +campaign: dr1_repack +project_root: {root} +manifest: manifest.txt +manifest_fields: [sample, tile, pixels] +chunk: 1000 +site: ral +stages: + vis_lp: + script: scripts/fit.py --stage=vis_lp + resources: {{cpus: 8, mem_mb: 65536, time: "18:00:00", partition: ral}} + vis_pix: + after: {{vis_lp: aftercorr}} + script: scripts/fit.py --stage=vis_pix + resources: {{cpus: 8, mem_mb: 65536, time: "24:00:00", partition: ral}} + sed: + after: {{vis_lp: aftercorr}} + script: scripts/fit.py --stage=sed + resources: {{cpus: 8, mem_mb: 65536, time: "03:00:00", partition: ral}} +""" + + +@pytest.fixture(name="repack") +def make_repack(tmp_path, ral): + root = tmp_path / "project" + write_campaign(root, REPACK_CAMPAIGN) + (root / "manifest.txt").write_text( + "\n".join(f"dr1 Tile{i:03d} {100 + i}" for i in range(200)) + "\n" + ) + campaign = Campaign.load(root / "campaign.yaml", site=ral) + digest, outcomes = retro( + repack_dump(tmp_path / "dump.psv"), + stage_regex=r"euclid_dr1_(?Pvis_lp|vis_pix|sed)", + site=ral, + ) + write_digest(tmp_path / "pilot", digest, outcomes) + return campaign, tmp_path / "pilot" + + +def test_plan_reproduces_the_dr1_repack(repack): + campaign, pilot_dir = repack + plan = build_plan(campaign, pilot=read_pilot(pilot_dir), pilot_source=str(pilot_dir)) + for stage, (cpus, mem_mb) in CHOSEN.items(): + proposal = plan["stages"][stage]["proposal"] + assert proposal["cpus"]["value"] == cpus, stage + assert abs(proposal["mem_mb"]["value"] - mem_mb) <= MEMORY_STEP_MB, stage + assert proposal["mem_mb"]["grade"] == "estimated" + assert proposal["mem_mb"]["sources"] == [f"{pilot_dir}#{stage}"] + # The two the human sized at measured peak × ~1.5 come out exactly. + assert plan["stages"]["vis_pix"]["proposal"]["mem_mb"]["value"] == 16384 + assert plan["stages"]["sed"]["proposal"]["mem_mb"]["value"] == 8192 + # p95 of the tasks (9.1 h × 0.985) + 25 % = 11.2 h, rounded up to 15 min. + assert plan["stages"]["vis_pix"]["proposal"]["time"]["value"] == "11:15:00" + + +def test_every_number_is_graded_and_no_optimal_without_a_designation(repack, evidence, tmp_path): + campaign, pilot_dir = repack + campaign.stages["vis_lp"].evidence = {"keys": KEYS} + plan = build_plan( + campaign, + evidence=evidence, + pilot=read_pilot(pilot_dir), + pilot_source=str(pilot_dir), + idle_cpus={"ral": {"value": 3400, "grade": "estimated", "sources": ["snapshot"]}}, + ) + write_plan(tmp_path / "out", plan) + text = (tmp_path / "out" / "plan.md").read_text() + (tmp_path / "out" / "plan.json").read_text() + # The source records carry "provisional_optimal: true"; it is never repeated. + assert not re.search("optimal", text, re.IGNORECASE) + + def check(node, path="plan"): + if isinstance(node, dict): + if "value" in node and "grade" in node: + assert node["grade"] in ( + "measured-current", "provisional", "analogue", "superseded", "estimated", "unsupported", + ), path + assert node["value"] is None or node["grade"] != "unsupported" or "note" in node, path + return + for key, value in node.items(): + check(value, f"{path}.{key}") + elif isinstance(node, list): + for value in node: + check(value, path) + + for stage in plan["stages"].values(): + for key in ("proposal", "eta", "disk", "energy"): + check(stage[key]) + vis_lp = plan["stages"]["vis_lp"] + assert vis_lp["evidence"]["per_call_s"] == { + "value": 0.05, + "grade": "provisional", + "sources": ["lifecycle/euclid-mge-current"], + } + assert vis_lp["evidence"]["host_peak_rss_mb"]["value"] == round(3000 * 1.048576) + assert {r["id"] for r in plan["records"]} >= {"lifecycle/euclid-mge-current"} + assert vis_lp["proposal"]["throttle"]["value"] == 3400 // 2 // 4 + assert vis_lp["eta"]["eta_s"]["value"] > 0 + assert plan["totals"]["eta_s"]["value"] == sum( + s["eta"]["eta_s"]["value"] for s in plan["stages"].values() + ) + + +def test_designation_is_the_only_way_to_say_optimal(repack, evidence, tmp_path): + campaign, pilot_dir = repack + campaign.stages["vis_lp"].evidence = {"keys": KEYS} + designations = read_designations(_write_text(tmp_path, "decisions.yaml", DESIGNATIONS)) + plan = build_plan(campaign, evidence=evidence, designations=designations) + assert plan["stages"]["vis_lp"]["evidence"]["designation"] == { + "decision": "imaging-mge-standard-cpu", + "optimal": "jax_cpu_dense_fp64", + } + assert "optimal setup per Pulse decision imaging-mge-standard-cpu" in plan_markdown(plan) + + +def test_evidence_only_plan_scales_evaluations(repack, evidence): + campaign, _ = repack + campaign.stages["vis_lp"].evidence = {"keys": dict(KEYS, stage="source_lp[1]")} + plan = build_plan(campaign, evidence=evidence) + ev = plan["stages"]["vis_lp"]["evidence"] + # The HST walltime record: its wall time, and its evals × implied cost. + assert ev["stage_wall_s"]["grade"] == "analogue" + assert ev["scaled_wall_s"]["value"] == pytest.approx(40000 * 0.09) + assert ev["scaled_wall_s"]["grade"] == "estimated" + proposal = plan["stages"]["vis_lp"]["proposal"] + assert proposal["time"]["value"] == "01:15:00" + assert proposal["time"]["grade"] == "estimated" + # No pilot: CPUs and memory fall back to the request / host memory, graded so. + assert proposal["cpus"]["grade"] == "unsupported" + assert proposal["mem_mb"]["grade"] == "estimated" + # A stage with no evidence at all says so. + assert plan["stages"]["sed"]["proposal"]["time"]["grade"] == "unsupported" + + +def test_censored_wall_time_is_reported(tmp_path, ral): + from autofit.campaign.digest import TaskOutcome + from autofit.campaign.plan import pilot_stats + + outcomes = [ + TaskOutcome(stage="sed", key=f"1_{i}", state="completed", elapsed_s=600, cpus=8, + max_rss_mb=3000, total_cpu_s=600 * 8 * 0.7, cpu_s_all_attempts=600 * 8) + for i in range(10) + ] + [ + TaskOutcome(stage="sed", key=f"1_{i}", state="timeout", elapsed_s=10800, time_limit_s=10800, + cpus=8, cpu_s_all_attempts=10800 * 8) + for i in range(10, 13) + ] + stats = pilot_stats(outcomes, "sed", "pilot") + assert stats["timeouts"] == 3 + assert stats["wall_censored"] + assert stats["rerun_factor"] > 1 + + +def test_size_bins(repack): + campaign, pilot_dir = repack + campaign.stages["vis_pix"].evidence = {"size_field": "pixels"} + outcomes = read_pilot(pilot_dir) + for outcome in outcomes: + # Pilot tasks 0..39 are campaign indices 0..39; big wall for big index. + outcome.index = int(outcome.key.split("_")[1]) + plan = build_plan(campaign, pilot=outcomes, pilot_source="pilot") + bins = plan["stages"]["vis_pix"]["size_bins"] + assert len(bins) == 3 + assert sum(b["objects"] for b in bins) == 200 + assert bins[0]["pilot_tasks"] == 40 and bins[0]["time"]["grade"] == "estimated" + assert bins[2]["time"]["grade"] == "unsupported" + + +def test_pilot_is_stratified_and_never_submitted(repack, tmp_path): + campaign, _ = repack + pilot = pilot_indices(campaign, fraction=0.05, size_field="pixels", bins=5, seed=1) + assert len(pilot["indices"]) == 10 + assert [b["chosen"] for b in pilot["bins"]] == [2] * 5 + assert pilot["bins"][0]["size_range"][0] == 100 and pilot["bins"][-1]["size_range"][1] == 299 + assert pilot == pilot_indices(campaign, fraction=0.05, size_field="pixels", bins=5, seed=1) + + uniform = pilot_indices(campaign, fraction=0.01) + assert len(uniform["indices"]) == 2 and uniform["stratified_by"] is None + + path = write_pilot(tmp_path / "out", campaign, pilot, "campaign.yaml") + document = json.loads(path.read_text()) + assert document["submit_command"].startswith("python -m autofit.campaign submit campaign.yaml --indices ") + assert "Not submitted" in document["note"] + + +def test_cli_plan_and_pilot(repack, tmp_path, capsys): + campaign, pilot_dir = repack + out = tmp_path / "plan_out" + profiling = _write(tmp_path, "p.json", PROFILING) + assert main([ + "plan", str(campaign.source), "--evidence", str(profiling), "--pilot", str(pilot_dir), + "--idle-cpus", "ral=1000", "--capacity-source", "sinfo 2026-10-30", "--output", str(out), + ]) == 0 + text = capsys.readouterr().out + assert text.startswith("# Plan: dr1_repack") + plan = json.loads((out / "plan.json").read_text()) + assert plan["stages"]["sed"]["proposal"]["throttle"]["sources"] == ["sinfo 2026-10-30"] + assert main(["pilot", str(campaign.source), "--size-field", "pixels", "--output", str(out)]) == 0 + assert json.loads((out / "pilot.json").read_text())["tasks"] == 5 + + +def test_spec_validates_evidence(tmp_path): + root = tmp_path / "project" + text = REPACK_CAMPAIGN.replace( + 'script: scripts/fit.py --stage=sed', + 'script: scripts/fit.py --stage=sed\n evidence: {{keys: {{colour: red}}, evals: -1, bad: 1}}', + ) + write_campaign(root, text) + errors = Campaign(__import__("yaml").safe_load((root / "campaign.yaml").read_text())).validate() + assert any("evidence: unknown keys ['bad']" in e for e in errors) + assert any("evidence.keys: unknown keys ['colour']" in e for e in errors) + assert any("evidence.evals: must be a positive number" in e for e in errors) + + +def test_host_memory_falls_back_to_the_runtime_record(tmp_path): + from autofit.campaign.plan import evidence_stats + + document = dict(PROFILING, records=[r for r in PROFILING["records"] if r["measurement"] != "memory_host"]) + stats = evidence_stats(KEYS, [read_evidence(_write(tmp_path, "p.json", document))]) + assert stats["host_peak_rss_mb"] == { + "value": 2048, + "grade": "provisional", + "sources": ["lifecycle/euclid-mge-current"], + "note": "peak RSS recorded with the runtime measurement", + } From 32a9305d29c99e61357cd83bd8a454cb8881bf01 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 30 Oct 2026 15:03:05 +0000 Subject: [PATCH 2/2] =?UTF-8?q?fix(campaign):=20review=20findings=20?= =?UTF-8?q?=E2=80=94=20cores=20mismatch,=20deterministic=20evidence=20choi?= =?UTF-8?q?ce,=20cost=20fallback,=20graded=20pilot=20numbers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. A walltime-validation record measured on N cores is scaled by N/cpus for a task of cpus CPUs (perfect scaling, optimistic when fewer), graded estimated with a cores_mismatch limitation shown as a plan.md flag; CPU-hours come from measured core-seconds, not scaled wall x cpus. 2. Stage wall time and host memory take the largest value among the matching records of the best grade (ordered by id, so file order no longer decides), listing every contributing id and the spread. 3. The evaluations x cost scaling falls back to the per-call cost when the walltime record's implied cost per evaluation is null. 4. Pilot statistics and size bins sit under graded wrappers (estimated, pilot); size bins carry a censored flag like the pilot's p95. Also: a profiling record is measured-current only when its decision is the current, unsuperseded designation covering the record's own keys and names its setup. Refs #1745 Co-Authored-By: Claude Opus 5.5 --- autofit/campaign/evidence.py | 10 +- autofit/campaign/plan.py | 210 ++++++++++++++++++++++++----- test_autofit/campaign/test_plan.py | 190 +++++++++++++++++++++++++- 3 files changed, 370 insertions(+), 40 deletions(-) diff --git a/autofit/campaign/evidence.py b/autofit/campaign/evidence.py index 51dae7a9e..97f0869e0 100644 --- a/autofit/campaign/evidence.py +++ b/autofit/campaign/evidence.py @@ -383,7 +383,15 @@ def grade_of( def _current_grade(record: EvidenceRecord, designations: Sequence[Dict]) -> str: if record.schema != "profiling-summary": return "measured-current" - if record.decision_id and any(d.get("id") == record.decision_id for d in designations): + # The record's decision must be the current (not superseded) designation for the + # record's own likelihood, regime and hardware class, and name its setup. + designation = designation_for(record.keys, designations) if record.decision_id else None + if ( + designation is not None + and designation.get("id") == record.decision_id + and record.record_class == "optimal" + and designation.get("optimal") == record.keys.get("setup_id") + ): return "measured-current" return "provisional" diff --git a/autofit/campaign/plan.py b/autofit/campaign/plan.py index 3bdafcf0b..67f8f208b 100644 --- a/autofit/campaign/plan.py +++ b/autofit/campaign/plan.py @@ -132,9 +132,30 @@ def pilot_stats(outcomes: List[TaskOutcome], stage: str, source: str) -> Optiona "by_index": { o.index: o.elapsed_s for o in finished if o.index is not None and o.elapsed_s }, + "limit_by_index": { + o.index: o.time_limit_s + for o in timeouts + if o.index is not None and o.time_limit_s + }, } +def _best_group(found): + """ + The matches sharing the best grade of ``found`` (best first), in a deterministic + order: by record id. + """ + if not found: + return [] + return sorted((m for m in found if m.grade == found[0].grade), key=lambda m: m.record.id) + + +def _spread(values) -> Optional[Dict]: + if len(values) < 2: + return None + return {"n": len(values), "min": min(values), "max": max(values)} + + def evidence_stats( keys: Dict[str, str], evidence: Sequence[EvidenceSet], @@ -167,37 +188,59 @@ def note(match): else: stats["per_call_s"] = unsupported("no profiling runtime record matches the stage keys") - memory = matches(evidence, keys, "memory_host", designations) - if memory and memory[0].record.values: - best = memory[0] - note(best) - value = next(iter(best.record.values.values())) - mb = value * 1.048576 if (best.record.unit or "").lower() == "mib" else value - stats["host_peak_rss_mb"] = graded(round(mb), best.grade, [best.record.id]) - elif runtime and runtime[0].record.extra.get("peak_rss_gb"): + # Memory and stage wall time: several records may match (seeds, legs). The plan + # takes the largest of those sharing the best grade, deterministically, and keeps + # every contributing id and the spread. + memory = _best_group( + [m for m in matches(evidence, keys, "memory_host", designations) if m.record.values] + ) + fallback = _best_group([m for m in runtime if m.record.extra.get("peak_rss_gb")]) + if memory: + for match in memory: + note(match) + + def mb(record): + value = next(iter(record.values.values())) + return value * 1.048576 if (record.unit or "").lower() == "mib" else value + + values = [mb(m.record) for m in memory] + stats["host_peak_rss_mb"] = graded( + round(max(values)), memory[0].grade, [m.record.id for m in memory], + _spread_note(values, "MB"), + ) + elif fallback: # A runtime record's own resources block (sacct MaxRSS of the profiling leg). - best = runtime[0] + values = [m.record.extra["peak_rss_gb"] * 1024 for m in fallback] stats["host_peak_rss_mb"] = graded( - round(best.record.extra["peak_rss_gb"] * 1024), best.grade, [best.record.id], - "peak RSS recorded with the runtime measurement", + round(max(values)), fallback[0].grade, [m.record.id for m in fallback], + "; ".join( + filter(None, ["peak RSS recorded with the runtime measurement", _spread_note(values, "MB")]) + ), ) else: stats["host_peak_rss_mb"] = unsupported("no profiling memory record matches") - walltime = [ - m for m in matches(evidence, keys, "stage_walltime", designations) if m.record.values.get("wall_s") - ] + walltime = _best_group( + [m for m in matches(evidence, keys, "stage_walltime", designations) if m.record.values.get("wall_s")] + ) if walltime: - best = walltime[0] - note(best) - values = best.record.values - stats["stage_wall_s"] = graded(values["wall_s"], best.grade, [best.record.id]) + for match in walltime: + note(match) + chosen = max(walltime, key=lambda m: (m.record.values["wall_s"], m.record.id)) + ids = [m.record.id for m in walltime] + walls = [m.record.values["wall_s"] for m in walltime] + values = chosen.record.values + stats["stage_wall_s"] = graded(values["wall_s"], chosen.grade, ids, _spread_note(walls, "s")) + if values.get("cores"): + stats["stage_wall_s"]["cores"] = int(values["cores"]) stats["likelihood_evals"] = graded( - values.get("likelihood_evals"), best.grade, [best.record.id] - ) - stats["implied_s_per_eval"] = graded( - values.get("implied_s_per_eval"), best.grade, [best.record.id] + max((m.record.values.get("likelihood_evals") or 0 for m in walltime)) or None, + chosen.grade, ids, ) + implied = [m.record.values["implied_s_per_eval"] for m in walltime if m.record.values.get("implied_s_per_eval")] + stats["implied_s_per_eval"] = graded(max(implied) if implied else None, chosen.grade, ids) + if values.get("cores"): + stats["implied_s_per_eval"]["cores"] = int(values["cores"]) else: stats["stage_wall_s"] = unsupported("no walltime-validation record matches the stage") @@ -207,7 +250,8 @@ def note(match): if evals else stats.get("likelihood_evals") ) - cost = stats.get("implied_s_per_eval") or stats["per_call_s"] + implied = stats.get("implied_s_per_eval") + cost = implied if implied and implied.get("value") is not None else stats["per_call_s"] if n_evals and n_evals.get("value") and cost.get("value"): stats["scaled_wall_s"] = graded( n_evals["value"] * cost["value"], @@ -215,6 +259,8 @@ def note(match): n_evals["sources"] + cost["sources"], "likelihood evaluations × cost per evaluation", ) + if cost.get("cores"): + stats["scaled_wall_s"]["cores"] = cost["cores"] else: stats["scaled_wall_s"] = unsupported("needs both a number of evaluations and a cost per evaluation") @@ -228,6 +274,16 @@ def note(match): return stats +def _spread_note(values, unit: str) -> Optional[str]: + spread = _spread(values) + if spread is None: + return None + return ( + f"largest of {spread['n']} matching records " + f"({spread['min']:.0f}–{spread['max']:.0f} {unit})" + ) + + def _size_bins(campaign, stage, pilot, n_bins: int = SIZE_BINS) -> Optional[List[Dict]]: field_name = stage.evidence.get("size_field") if not field_name or not pilot or not pilot["by_index"]: @@ -250,9 +306,13 @@ def bin_of(size): for index, size in sizes.items(): population[bin_of(size)] += 1 + limits = defaultdict(list) for index, wall in pilot["by_index"].items(): if index in sizes: bins[bin_of(sizes[index])].append(wall) + for index, limit in pilot.get("limit_by_index", {}).items(): + if index in sizes: + limits[bin_of(sizes[index])].append(limit) lows = [ordered[0]] + edges highs = edges + [ordered[-1]] result = [] @@ -266,6 +326,9 @@ def bin_of(size): "objects": population.get(number, 0), "pilot_tasks": len(walls), "wall_p95_s": p95, + # As in ``pilot_stats``: timeouts are kept at their limit, so a p95 at + # or above the bin's smallest limit is a lower bound. + "censored": bool(p95 and limits.get(number) and p95 >= min(limits[number])), } ) return result @@ -337,13 +400,17 @@ def propose(stage, pilot: Optional[Dict], evidence: Dict, site=None, idle_cpus: note += "; censored: the p95 is at the old time limit, so the real p95 is higher — re-pilot at the new limit" proposal["time_s"] = graded(seconds, "estimated", pilot_source, note) else: - basis = evidence["stage_wall_s"] if evidence["stage_wall_s"]["value"] else evidence["scaled_wall_s"] + basis = evidence_wall(evidence, cpus) if basis["value"]: seconds = _proposed_time(basis["value"], max_time) proposal["time_s"] = graded( seconds, worst(basis["grade"], "estimated"), basis["sources"], - "one measured stage + margin: no spread is known, so re-pilot", + "; ".join( + filter(None, ["measured stage wall + margin: no spread is known, so re-pilot", basis.get("note")]) + ), ) + if basis.get("limitations"): + proposal["time_s"]["limitations"] = basis["limitations"] else: proposal["time_s"] = graded(request.time_s, "unsupported", [], "the stage's own request") if max_time and proposal["time_s"]["value"] and proposal["time_s"]["value"] >= max_time: @@ -365,23 +432,58 @@ def propose(stage, pilot: Optional[Dict], evidence: Dict, site=None, idle_cpus: return proposal +def evidence_wall(evidence: Dict, cpus: int) -> Dict: + """ + The evidence's stage wall time (a measured stage, else evaluations × cost) for a + task of ``cpus`` CPUs. A wall time measured on another number of cores is scaled by + cores / cpus — perfect scaling, which is optimistic when ``cpus`` is the smaller — + graded ``estimated`` and marked with a ``cores_mismatch`` limitation. + """ + basis = evidence["stage_wall_s"] if evidence["stage_wall_s"]["value"] else evidence["scaled_wall_s"] + cores = basis.get("cores") + if not basis["value"] or not cores or not cpus or cores == cpus: + return basis + limitation = ( + f"cores_mismatch: measured at {cores} cores, requested {cpus}; " + f"wall scaled by {cores}/{cpus} assuming perfect scaling" + + (" (optimistic)" if cpus < cores else "") + ) + return dict( + basis, + value=basis["value"] * cores / cpus, + grade=worst(basis["grade"], "estimated"), + note=limitation, + limitations=[limitation], + measured_wall_s=basis["value"], + ) + + def _eta(n_tasks, pilot, evidence, proposal) -> Dict: + cpus = proposal["cpus"]["value"] + rerun = (pilot or {}).get("rerun_factor") or 1.0 + core_s = None if pilot and pilot["wall_s"]["p50"]: wall = graded(pilot["wall_s"]["p50"], "estimated", [pilot["source"]]) - elif evidence["stage_wall_s"]["value"]: - wall = evidence["stage_wall_s"] else: - wall = evidence["scaled_wall_s"] - cpus = proposal["cpus"]["value"] - rerun = (pilot or {}).get("rerun_factor") or 1.0 + wall = evidence_wall(evidence, cpus) + if wall.get("cores") and wall["value"]: + # CPU-hours from what was measured (wall × the cores it ran on), not from + # a scaled wall time. + core_s = wall.get("measured_wall_s", wall["value"]) * wall["cores"] if not wall["value"] or not cpus: return {"cpu_h": unsupported("no wall time"), "eta_s": unsupported("no wall time")} - cpu_h = n_tasks * wall["value"] * cpus * rerun / 3600 sources = wall["sources"] + if core_s is not None: + cpu_h = n_tasks * core_s * rerun / 3600 + how = f"{n_tasks} tasks × measured wall × {wall['cores']} measured cores × rerun factor {rerun:.2f}" + else: + cpu_h = n_tasks * wall["value"] * cpus * rerun / 3600 + how = f"{n_tasks} tasks × p50 wall × {cpus} CPUs × rerun factor {rerun:.2f}" result = { - "cpu_h": graded(round(cpu_h, 1), worst(wall["grade"], "estimated"), sources, - f"{n_tasks} tasks × p50 wall × {cpus} CPUs × rerun factor {rerun:.2f}"), + "cpu_h": graded(round(cpu_h, 1), worst(wall["grade"], "estimated"), sources, how), } + if wall.get("limitations"): + result["cpu_h"]["limitations"] = wall["limitations"] throttle = proposal["throttle"] if throttle["value"]: concurrent = throttle["value"] * cpus @@ -469,16 +571,37 @@ def build_plan( proposal = propose(stage, stage_pilot, ev, site=site, idle_cpus=idle_cpus) eta = _eta(n_tasks, stage_pilot, ev, proposal) bins = _size_bins(campaign, stage, stage_pilot) + flags = [] if bins: max_time = _max_time(stage, site) + wrapped = [] for entry in bins: if entry["wall_p95_s"]: - entry["time"] = graded( + time = graded( format_time(_proposed_time(entry["wall_p95_s"], max_time)), "estimated", [stage_pilot["source"]], + "censored: a lower bound — re-pilot at a longer limit" if entry["censored"] else None, ) else: - entry["time"] = unsupported("no pilot task in this bin") + time = unsupported("no pilot task in this bin") + if entry["censored"]: + flags.append(f"censored wall time in size bin {entry['bin']}") + wrapped.append( + { + "measured": graded( + entry, "estimated", [stage_pilot["source"]], + "pilot tasks per size bin; sizes and object counts from the manifest", + ), + "time": time, + } + ) + bins = wrapped + if stage_pilot and stage_pilot["wall_censored"]: + flags.append("censored wall time: the pilot p95 is at the old time limit") + for entry in (proposal["time_s"], eta["cpu_h"]): + for limitation in entry.get("limitations") or []: + if limitation not in flags: + flags.append(limitation) cpu_h = eta["cpu_h"] mem = proposal["mem_mb"]["value"] energy = { @@ -502,7 +625,17 @@ def build_plan( "partition": stage.resources.partition, "throttle": stage.resources.throttle, }, - "pilot": {k: v for k, v in (stage_pilot or {}).items() if k != "by_index"} or None, + "pilot": graded( + { + k: v + for k, v in stage_pilot.items() + if k not in ("by_index", "limit_by_index", "source") + }, + "estimated", [stage_pilot["source"]], "pilot measurements", + ) + if stage_pilot + else None, + "flags": flags, "evidence": {k: v for k, v in ev.items() if k != "records"}, "proposal": proposal, "size_bins": bins, @@ -627,6 +760,8 @@ def plan_markdown(plan: Dict) -> str: f"stage wall {_cell(ev['stage_wall_s'], _hours)}, " f"scaled wall {_cell(ev['scaled_wall_s'], _hours)}" ) + for flag in stage.get("flags") or []: + lines.append(f"- **flag** {flag}") if ev["designation"]: lines.append( f"- optimal setup per Pulse decision {ev['designation']['decision']}: " @@ -638,8 +773,9 @@ def plan_markdown(plan: Dict) -> str: lines.append( "- by size: " + "; ".join( - f"{b['size_range'][0]:g}–{b['size_range'][1]:g} ({b['objects']} objects): {_cell(b['time'])}" + f"{m['size_range'][0]:g}–{m['size_range'][1]:g} ({m['objects']} objects): {_cell(b['time'])}" for b in stage["size_bins"] + for m in [b["measured"]["value"]] ) ) disk = stage["disk"] diff --git a/test_autofit/campaign/test_plan.py b/test_autofit/campaign/test_plan.py index 7a2a3f15e..1fd284b80 100644 --- a/test_autofit/campaign/test_plan.py +++ b/test_autofit/campaign/test_plan.py @@ -475,8 +475,11 @@ def test_size_bins(repack): plan = build_plan(campaign, pilot=outcomes, pilot_source="pilot") bins = plan["stages"]["vis_pix"]["size_bins"] assert len(bins) == 3 - assert sum(b["objects"] for b in bins) == 200 - assert bins[0]["pilot_tasks"] == 40 and bins[0]["time"]["grade"] == "estimated" + measured = [b["measured"]["value"] for b in bins] + assert all(b["measured"]["grade"] == "estimated" for b in bins) + assert sum(m["objects"] for m in measured) == 200 + assert measured[0]["pilot_tasks"] == 40 and bins[0]["time"]["grade"] == "estimated" + assert not measured[0]["censored"] assert bins[2]["time"]["grade"] == "unsupported" @@ -537,3 +540,186 @@ def test_host_memory_falls_back_to_the_runtime_record(tmp_path): "sources": ["lifecycle/euclid-mge-current"], "note": "peak RSS recorded with the runtime measurement", } + + +# --- review findings ------------------------------------------------------------- + +DELAUNAY_KEYS = { + "dataset_type": "imaging", + "variant": "delaunay", + "instrument": "hst", + "setup_id": "numba_cpu_sparse_fp64", + "host_class": "hpc_ral_cpu", + "stage": "mass_total[1]", +} + + +def _walltime_seed(seed, wall, evals, cores=8): + return { + "id": f"imaging/delaunay/hst/default/numba_cpu_sparse_fp64/hpc_ral_cpu/nautilus:mass_total[1]/seed_{seed}", + "likelihood": {"dataset_type": "imaging", "variant": "delaunay"}, + "instrument": "hst", + "setup_id": "numba_cpu_sparse_fp64", + "host_class": "hpc_ral_cpu", + "model_variant": "default", + "stage": "mass_total[1]", + "wall_s": wall, + "likelihood_evals": evals, + "implied_s_per_eval": wall / evals, + "cores": cores, + } + + +@pytest.fixture(name="seeds") +def make_seeds(tmp_path): + document = { + "schema": "walltime-validation", + "version": 1, + # File order puts the faster seed first: the plan must not depend on it. + "records": [_walltime_seed(2, 4564.0, 20000), _walltime_seed(1, 8648.0, 38660)], + } + return [read_evidence(_write(tmp_path, "w.json", document))] + + +def _one_stage_campaign(tmp_path, ral, cpus): + root = tmp_path / "one" + text = REPACK_CAMPAIGN.split(" vis_pix:")[0].replace( + "resources: {{cpus: 8, mem_mb: 65536", f"resources: {{{{cpus: {cpus}, mem_mb: 8192" + ) + write_campaign(root, text, n=10) + campaign = Campaign.load(root / "campaign.yaml", site=ral) + campaign.stages["vis_lp"].evidence = {"keys": DELAUNAY_KEYS} + return campaign + + +def test_review_1_cores_mismatch_scales_wall_and_cpu_hours(tmp_path, ral, seeds): + campaign = _one_stage_campaign(tmp_path, ral, cpus=1) + plan = build_plan(campaign, evidence=seeds) + stage = plan["stages"]["vis_lp"] + time = stage["proposal"]["time_s"] + # 8648 s measured at 8 cores, requested 1: scaled ×8 (perfect scaling), + 25 %. + assert time["value"] == -(-8648 * 8 * 1.25 // 900) * 900 + assert time["grade"] == "estimated" + assert time["limitations"] == [ + "cores_mismatch: measured at 8 cores, requested 1; wall scaled by 8/1 assuming perfect scaling (optimistic)" + ] + # CPU-hours from measured core-seconds: 10 × 8648 s × 8 cores. + assert stage["eta"]["cpu_h"]["value"] == round(10 * 8648 * 8 / 3600, 1) + assert any(f.startswith("cores_mismatch") for f in stage["flags"]) + assert "**flag** cores_mismatch: measured at 8 cores, requested 1" in plan_markdown(plan) + + same = build_plan(_one_stage_campaign(tmp_path / "b", ral, cpus=8), evidence=seeds) + assert "limitations" not in same["stages"]["vis_lp"]["proposal"]["time_s"] + assert same["stages"]["vis_lp"]["flags"] == [] + + +def test_review_2_largest_of_the_best_grade_with_every_id_and_spread(seeds): + from autofit.campaign.plan import evidence_stats + + stats = evidence_stats(DELAUNAY_KEYS, seeds) + wall = stats["stage_wall_s"] + assert wall["value"] == 8648.0 + assert wall["grade"] == "measured-current" + assert sorted(wall["sources"]) == sorted(r["id"] for r in [_walltime_seed(1, 1, 1), _walltime_seed(2, 1, 1)]) + assert wall["note"] == "largest of 2 matching records (4564–8648 s)" + assert stats["likelihood_evals"]["value"] == 38660 + # Same answer whatever the file order. + seeds[0].records.reverse() + assert evidence_stats(DELAUNAY_KEYS, seeds)["stage_wall_s"] == wall + + +def test_review_3_cost_falls_back_to_per_call_when_implied_is_missing(tmp_path): + from autofit.campaign.plan import evidence_stats + + walltime = {"schema": "walltime-validation", "version": 1, "records": [ + dict(WALLTIME["records"][0], instrument="euclid", implied_s_per_eval=None), + ]} + evidence = [ + read_evidence(_write(tmp_path, "p.json", PROFILING)), + read_evidence(_write(tmp_path, "w.json", walltime)), + ] + stats = evidence_stats(dict(KEYS, stage="source_lp[1]"), evidence) + assert stats["implied_s_per_eval"]["value"] is None + # 40000 evaluations × the profiling per-call cost (0.05 s). + assert stats["scaled_wall_s"]["value"] == pytest.approx(40000 * 0.05) + + +def test_review_4_every_number_in_plan_json_is_graded(repack, evidence, tmp_path): + campaign, pilot_dir = repack + campaign.stages["vis_lp"].evidence = {"keys": KEYS} + campaign.stages["vis_pix"].evidence = {"size_field": "pixels"} + outcomes = read_pilot(pilot_dir) + for outcome in outcomes: + outcome.index = int(outcome.key.split("_")[1]) + plan = build_plan( + campaign, evidence=evidence, pilot=outcomes, pilot_source="pilot", + idle_cpus={"*": {"value": 100, "grade": "estimated", "sources": ["x"]}}, + ) + write_plan(tmp_path / "out", plan) + document = json.loads((tmp_path / "out" / "plan.json").read_text()) + + bare = [] + + def walk(node, path, inside): + if isinstance(node, dict): + inside = inside or ("grade" in node and "value" in node) + for key, value in node.items(): + walk(value, f"{path}.{key}", inside) + elif isinstance(node, list): + for number, value in enumerate(node): + walk(value, f"{path}[{number}]", inside) + elif isinstance(node, (int, float)) and not isinstance(node, bool) and not inside: + bare.append(path) + + for name, stage in document["stages"].items(): + # The stage's own request is the campaign file's declaration, not evidence. + walk({k: v for k, v in stage.items() if k != "request"}, f"stages.{name}", False) + walk(document["totals"], "totals", False) + assert bare == [] + + +def test_review_4_censored_size_bin(repack): + from autofit.campaign.digest import TaskOutcome + + campaign, _ = repack + campaign.stages["sed"].evidence = {"size_field": "pixels"} + outcomes = [ + TaskOutcome(stage="sed", key=f"1_{i}", index=i, state="completed", elapsed_s=600, cpus=8, + max_rss_mb=3000, total_cpu_s=600 * 8 * 0.7, cpu_s_all_attempts=600 * 8) + for i in range(5) + ] + [ + TaskOutcome(stage="sed", key=f"1_{i}", index=i, state="timeout", elapsed_s=10800, + time_limit_s=10800, cpus=8, cpu_s_all_attempts=10800 * 8) + for i in range(5, 10) + ] + plan = build_plan(campaign, pilot=outcomes, pilot_source="pilot") + first = plan["stages"]["sed"]["size_bins"][0] + assert first["measured"]["value"]["censored"] + assert "censored" in first["time"]["note"] + assert "censored wall time in size bin 0" in plan["stages"]["sed"]["flags"] + + +def test_designation_must_cover_the_record_and_be_current(tmp_path, evidence): + text = DESIGNATIONS + """ +- id: imaging-mge-standard-cpu-v2 + kind: designation + likelihood: imaging/mge + regime: standard + hardware_class: cpu_many_core + optimal: jax_cpu_dense_fp64 + secondary: [] + evidence: [lifecycle/euclid-mge-current] + rule: one sentence + supersedes: imaging-mge-standard-cpu +""" + designations = read_designations(_write_text(tmp_path, "decisions.yaml", text)) + record = evidence[0].records[0] + record.record_class = "optimal" + # Citing the superseded decision is not enough. + record.decision_id = "imaging-mge-standard-cpu" + assert grade_of(record, KEYS, designations).grade == "provisional" + record.decision_id = "imaging-mge-standard-cpu-v2" + assert grade_of(record, KEYS, designations).grade == "measured-current" + # A designation for another hardware class does not cover this record. + record.keys["host_class"] = "hpc_a100" + assert grade_of(record, dict(KEYS, host_class="hpc_a100"), designations).grade == "provisional"