From 185a3707552ba7ba50182ab76d7eb0f1f9976dea Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 23 Oct 2026 16:07:34 +0100 Subject: [PATCH] feat(profiling): lifecycle template, profiling-summary@3 coverage grid, samplers 0C paths, Pulse/Insight read prose (likelihood-lifecycle 0E) (a) skills/profiling/lifecycle.md: the L0-L7 lifecycle as a phase-prompt template (one placeholder set; one fenced prompt block per step with owning repos, Brain door, human gate, witness and a full Mind header). Linked from the profiling skill, its command page and the conductor AGENTS.md. A test renders it for imaging/delaunay and judges the prompts with intake's own census. (b) Profiling conductor: a published profiling-summary@3 catalogue switches `campaign` to the lifecycle grid (likelihood x class x measurement; cells current / stale / superseded / missing), reads the mirrored results tree, refuses setup_ids off the R1 grammar (SetupIdError), never counts local_* hosts as current, reports class as declared. v2/absent catalogue: unchanged (live dry-run JSON byte-identical). (c) Samplers faculty: mature tier reads autolens_inference's scripts///samplers/ (path fallback; old searches/ shape kept for autofit_inference); validation/ leaves listed as their own tier. (d) Prose: optimal+current default reads, optimal is a Pulse designation, walltime-validation@1 / lens-walltime is Pulse's, Insight records setup_mode: auto with setup_resolved, Pulse selector order. Closes #535 Co-Authored-By: Claude Fable 5.1 --- agents/conductors/profiling/AGENTS.md | 29 +- agents/conductors/profiling/_catalogue.py | 154 ++++++++- agents/conductors/profiling/_profiling.py | 188 ++++++++++- agents/faculties/samplers/AGENTS.md | 34 +- agents/faculties/samplers/_samplers.py | 96 ++++-- skills/profiling/SKILL.md | 3 + skills/profiling/lifecycle.md | 367 +++++++++++++++++++++ skills/profiling/profiling.md | 34 +- skills/sampler_pipeline/SKILL.md | 8 +- skills/sampler_pipeline/reference.md | 10 +- tests/test_profiling_conductor.py | 151 +++++++++ tests/test_profiling_lifecycle_template.py | 92 ++++++ tests/test_samplers_surface.py | 46 +++ 13 files changed, 1164 insertions(+), 48 deletions(-) create mode 100644 skills/profiling/lifecycle.md create mode 100644 tests/test_profiling_lifecycle_template.py diff --git a/agents/conductors/profiling/AGENTS.md b/agents/conductors/profiling/AGENTS.md index d49a6bec..ba56c2b0 100644 --- a/agents/conductors/profiling/AGENTS.md +++ b/agents/conductors/profiling/AGENTS.md @@ -20,6 +20,7 @@ prompt, PyAutoMind `issued/profiling_agent.md`. | Mode | Question | Emits | |------|----------|-------| | `campaign` | Which grid runs are done / CPU-unusable / missing on this tier, and how do I dispatch the rest? | dispatch plan (local sweep flags incl. the per-run timeout; A100 submit list) | +| `campaign` on a `profiling-summary@3` catalogue | Per likelihood × class × measurement, which planned cells are current / stale / superseded / missing? | coverage rows, per-cell states, local-host and class-mismatch flags, a plan routed by `host_class` | | `ingest` | Which probe JSONs aren't in the vram tables yet, and which results have no pin? | table-update rows, pin list, baseline + dashboard steps | | `ingest --axis compile` | Which warm compile rows are unpinned, and which have drifted from their pin? | drifted rows (with pinned vs observed), unpinned keys, confirm/classify/re-pin steps | | `triage` | What do the pinned-drift findings mean? | per-finding classification: stale pin → re-pin here; library regression → `bug/` via intake | @@ -79,6 +80,29 @@ neither counts as grid coverage, and neither is silently dropped. instrument)` identity triple are reported as **sibling-instrument** records, not as malformed — only a record missing *some* of its key fields is corruption. +### The lifecycle grid (`profiling-summary@3`) + +When the published `dashboard/catalogue.json` is `profiling-summary@3`, +`campaign` diffs its `planned_cells` against its `records` instead of the sweep +grid. A cell is keyed (likelihood, instrument, `setup_id`, `host_class`, +`model_variant`, measurement) and is `current` (a current record on a +reference host), `stale` (that record's `release_pin` is behind the +catalogue's pin — the envelope's, else the newest record's), `superseded` +(only superseded records) or `missing`. The mirrored tree +`results//////` is +read when it exists, and a directory with no catalogue row is listed. +`setup_id` follows `___[_]`; +anything else is refused as `SetupIdError`. `local_*` host classes never count +as current and are flagged. The class is the producer's declaration from a +Pulse `designation` decision: this conductor reports it, flags a record whose +class disagrees with its planned cell, and never assigns one. The plan routes +CPU cells to `--partition=ral` and A100 cells to `gpu` with `--gres`. A v2 or +absent catalogue keeps the legacy grid byte-identical. + +The L0–L7 sequence a likelihood follows (register → figures → profile → +designate → validate → gradient → samplers → close) is the phase-prompt +template in [`skills/profiling/lifecycle.md`](../../../skills/profiling/lifecycle.md). + ## Fundamental principles - **The classification is the result** for CPU-unusable cells (the usability @@ -123,7 +147,10 @@ as malformed — only a record missing *some* of its key fields is corruption. versioned `profiling-summary` read contract, ingest receipts and the board. It validates the exchange contract only and never judges; this conductor (`triage`) stays the only judge of what a timing or a drift means, with the - human. The projects keep their producers, results, pins and drift policy. + human. Lookups read `class: optimal` + `status: current` unless asked + otherwise; `optimal` is always a Pulse `designation` decision. Full-fit + wall-time validation is Pulse's `walltime-validation@1` axis (instance + `lens-walltime`, producer autolens_inference), never PyAutoInsight's. The projects keep their producers, results, pins and drift policy. Same split as Heart ↔ vitals and Eyes ↔ the Eyes conductor. (Organ row born in PyAutoMind#463; its reader and board arrived in phase 2.) - **Where drift candidates are read** — the diff --git a/agents/conductors/profiling/_catalogue.py b/agents/conductors/profiling/_catalogue.py index 36315592..9866231a 100644 --- a/agents/conductors/profiling/_catalogue.py +++ b/agents/conductors/profiling/_catalogue.py @@ -46,12 +46,12 @@ def read_catalogue(ws: Path): if not isinstance(doc, dict): raise ValueError("Profiling catalogue must be an object") if source == published: - if doc.get("schema") != "profiling-summary" or doc.get("version") not in (1, 2): + if doc.get("schema") != "profiling-summary" or doc.get("version") not in (1, 2, 3): raise ValueError("Unsupported published profiling catalogue") if "script_routes" not in doc: return None - if doc["version"] != 2: - raise ValueError("Source routes require profiling-summary v2") + if doc["version"] not in (2, 3): + raise ValueError("Source routes require profiling-summary v2 or v3") doc = doc["script_routes"] if not isinstance(doc, dict) or doc.get("schema") != "profiling-script-routes" or doc.get("version") != 1: raise ValueError("Unsupported profiling script routes schema/version") @@ -119,3 +119,151 @@ def read_catalogue(ws: Path): "compile_probe": probe, "missing_sources": sorted(path for path in paths if not (ws / path).is_file()), } + + +# --------------------------------------------------------------------------- +# profiling-summary@3: the lifecycle catalogue (PyAutoPulse REFERENCE.md) +# --------------------------------------------------------------------------- +# +# The vocabulary below mirrors the Pulse contract's enumerations for the fields +# the conductor reads. Pulse validates the whole document; the conductor only +# refuses what it cannot place on its coverage grid. It REPORTS the producer's +# `class` and `status` and never assigns either. + +SETUP_ID_GRAMMAR = "___[_]" +SETUP_BACKENDS = ("numba", "jax") +SETUP_DEVICES = ("cpu", "gpu") +SETUP_OPERATORS = ("dense", "sparse", "na") +SETUP_PRECISIONS = ("fp64", "mixed") +# `na` is the absence of a transformer and is never spelled in a setup_id. +SETUP_TRANSFORMERS = ("dft", "nufft", "wtilde", "streaming") +DATASET_TYPES = ("imaging", "interferometer", "datacube", "point_source_image", + "point_source_source", "multi_galaxy", "group", "cluster", + "multi_dataset", "weak") +CLASSES = ("optimal", "secondary", "experimental") +# `archived` records leave `records[]` (counted in `archive_record_count`). +STATUSES = ("current", "superseded") +# Host classes with this prefix never qualify as `current` (reference-host rule). +LOCAL_HOST_PREFIX = "local_" +LIFECYCLE_SOURCE = "dashboard/catalogue.json" + + +class SetupIdError(ValueError): + """A `setup_id` that does not follow the canonical grammar.""" + + def __init__(self, value, where=""): + place = f" in {where}" if where else "" + super().__init__(f"SetupIdError: {value!r}{place} does not match {SETUP_ID_GRAMMAR}") + + +def parse_setup_id(value, where=""): + """`setup_id` -> {backend, device, operator, precision, transformer}. + + Refuses anything off the grammar with `SetupIdError`, including an explicit + `_na` transformer (the canonical form omits it).""" + parts = value.split("_") if isinstance(value, str) else [] + if len(parts) not in (4, 5): + raise SetupIdError(value, where) + backend, device, operator, precision = parts[:4] + transformer = parts[4] if len(parts) == 5 else "na" + if (backend not in SETUP_BACKENDS or device not in SETUP_DEVICES + or operator not in SETUP_OPERATORS or precision not in SETUP_PRECISIONS + or (len(parts) == 5 and transformer not in SETUP_TRANSFORMERS)): + raise SetupIdError(value, where) + return {"backend": backend, "device": device, "operator": operator, + "precision": precision, "transformer": transformer} + + +def is_local_host(host_class): + return isinstance(host_class, str) and host_class.startswith(LOCAL_HOST_PREFIX) + + +def pin_order(pin): + """Sortable form of a release pin (`2026.10.16.2`); None when unparsable.""" + if not isinstance(pin, str): + return None + try: + return tuple(int(part) for part in pin.split(".")) + except ValueError: + return None + + +def lifecycle_key(row, where): + """(dataset_type, variant, instrument, setup_id, host_class, model_variant, + measurement) — the Pulse one-current-per-key identity.""" + likelihood = row.get("likelihood") + if not isinstance(likelihood, dict): + raise ValueError(f"Lifecycle row without a likelihood: {where}") + dataset_type = _token(likelihood.get("dataset_type")) + if dataset_type not in DATASET_TYPES: + raise ValueError(f"Unknown dataset_type {dataset_type!r}: {where}") + setup_id = row.get("setup_id") + setup = parse_setup_id(setup_id, where) + declared = row.get("setup") + if isinstance(declared, dict) and any( + declared.get(field, setup[field]) != setup[field] for field in setup): + raise ValueError(f"setup does not match setup_id {setup_id!r}: {where}") + return (dataset_type, _token(likelihood.get("variant")), _token(row.get("instrument")), + setup_id, _token(row.get("host_class")), _token(row.get("model_variant")), + _token(row.get("measurement"))) + + +def read_lifecycle(ws: Path): + """The published `profiling-summary@3` catalogue, or None (v1/v2/absent). + + None keeps every caller on its pre-lifecycle path unchanged; an unreadable + published file is left to `read_catalogue`, which already owns that error. + A v3 document the grid cannot place is refused, never half-read. + """ + source = ws / LIFECYCLE_SOURCE + if not source.is_file(): + return None + raw = source.read_bytes() + try: + doc = json.loads(raw) + except (ValueError, UnicodeError): + return None + if not isinstance(doc, dict) or doc.get("schema") != "profiling-summary" or doc.get("version") != 3: + return None + records, planned = doc.get("records"), doc.get("planned_cells", []) + if not isinstance(records, list) or not isinstance(planned, list): + raise ValueError("profiling-summary@3 records and planned_cells must be lists") + rows = [] + for index, record in enumerate(records): + where = f"records[{index}]" + if not isinstance(record, dict): + raise ValueError(f"Invalid lifecycle record: {where}") + key = lifecycle_key(record, where) + if record.get("class") not in CLASSES: + raise ValueError(f"Unknown class {record.get('class')!r}: {where}") + if record.get("status") not in STATUSES: + raise ValueError(f"Status {record.get('status')!r} cannot be in records[]: {where}") + rows.append({"id": str(record.get("id", where)), "key": key, "class": record["class"], + "status": record["status"], "release_pin": record.get("release_pin")}) + cells = {} + for index, cell in enumerate(planned): + where = f"planned_cells[{index}]" + if not isinstance(cell, dict): + raise ValueError(f"Invalid planned cell: {where}") + key = lifecycle_key(cell, where) + if cell.get("class") not in CLASSES: + raise ValueError(f"Unknown class {cell.get('class')!r}: {where}") + if key in cells: + raise ValueError(f"Duplicate planned cell: {where}") + cells[key] = cell["class"] + # The pin a current record is judged against: the envelope's own when it + # declares one, else the newest pin the catalogue's records carry. + pin, pin_source = doc.get("release_pin"), "envelope" + if pin_order(pin) is None: + pins = [r["release_pin"] for r in rows if pin_order(r["release_pin"]) is not None] + pin, pin_source = (max(pins, key=pin_order), "newest record") if pins else (None, None) + return { + "source": LIFECYCLE_SOURCE, + "sha256": hashlib.sha256(raw).hexdigest(), + "version": 3, + "release_pin": pin, + "release_pin_source": pin_source, + "archive_record_count": doc.get("archive_record_count"), + "records": rows, + "planned": cells, + } diff --git a/agents/conductors/profiling/_profiling.py b/agents/conductors/profiling/_profiling.py index 18f7bc8d..326be20a 100644 --- a/agents/conductors/profiling/_profiling.py +++ b/agents/conductors/profiling/_profiling.py @@ -15,7 +15,9 @@ - **campaign** — diff the campaign grid (sweep CELLS × configs) against the results tree (done / CPU-unusable / missing) and emit the dispatch plan for the requested tier, honouring the CPU-usability policy (per-run timeout, - GPU-only markers). + GPU-only markers). On a published `profiling-summary@3` catalogue it + reports the lifecycle grid instead (planned cells x records, per + likelihood x class x measurement: current / stale / superseded / missing). - **ingest** — find probe JSONs not yet reflected in the vram batch tables, and campaign results whose instruments have no pinned value, and emit the table-update / pinning / baseline / dashboard plan. @@ -51,7 +53,10 @@ from _repo_paths import repo_path # noqa: E402 sys.path.insert(0, str(Path(__file__).resolve().parent)) -from _catalogue import read_catalogue # noqa: E402 +from _catalogue import ( # noqa: E402 + DATASET_TYPES, LOCAL_HOST_PREFIX, is_local_host, parse_setup_id, pin_order, + read_catalogue, read_lifecycle, +) PYAUTO_ROOT = _pyauto_root.pyauto_root() HEART_STATE_DIR = Path(os.environ.get("HEART_STATE_DIR", Path.home() / ".pyauto-heart")) @@ -256,6 +261,9 @@ def compile_tier_of(hardware: str | None) -> str: def campaign(ws: Path, tier: str) -> dict[str, Any]: if tier not in TIER_CONFIGS: return {"agent": "profiling", "mode": "campaign", "error": f"unknown tier {tier!r}"} + lifecycle = read_lifecycle(ws) + if lifecycle is not None: + return campaign_lifecycle(ws, tier, lifecycle) routing = grid_info(ws) grid = routing["grid"] runtime = ws / "results" / "runtime" @@ -321,6 +329,154 @@ def campaign(ws: Path, tier: str) -> dict[str, Any]: } +# Lifecycle grid (profiling-summary@3 + the mirrored results tree, report §3.7). +CELL_STATES = ("current", "stale", "superseded", "missing") +# The §3.7 per-cell scripts; a measurement with no entry has no declared script. +MEASUREMENT_SCRIPTS = { + "runtime": "likelihood_runtime.py", + "breakdown": "likelihood_breakdown.py", + "gradient": "gradient_breakdown.py", +} +# Where each reference host class is submitted. CPU work goes on `ral` only. +HOST_ROUTES = { + "hpc_ral_cpu": "RAL CPU: sbatch --partition=ral (never gpu)", + "hpc_a100": "RAL A100: sbatch --partition=gpu --gres=gpu:1", +} + + +def _cell_id(key) -> str: + dataset_type, variant, instrument, setup_id, host_class, model_variant, measurement = key + variant_note = "" if model_variant == "default" else f" {model_variant}" + return (f"{dataset_type}/{variant}/{instrument} {setup_id}@{host_class}" + f"{variant_note} [{measurement}]") + + +def lifecycle_tree(ws: Path) -> dict[tuple, Path]: + """`results//////` + directories present, keyed (dataset_type, variant, instrument, setup_id, + host_class). A setup directory off the grammar is refused (SetupIdError).""" + found: dict[tuple, Path] = {} + for dataset_type in DATASET_TYPES: + root = ws / "results" / dataset_type + if not root.is_dir(): + continue + for setup_dir in sorted(p for p in root.glob("*/*/*") if p.is_dir()): + variant, instrument, setup_id = setup_dir.relative_to(root).parts + parse_setup_id(setup_id, setup_dir.relative_to(ws).as_posix()) + for host_dir in sorted(p for p in setup_dir.iterdir() if p.is_dir()): + found[(dataset_type, variant, instrument, setup_id, host_dir.name)] = host_dir + return found + + +def campaign_lifecycle(ws: Path, tier: str, lifecycle: dict[str, Any]) -> dict[str, Any]: + """Coverage of a `profiling-summary@3` catalogue's planned cells. + + Per likelihood x class x measurement, each planned cell is `current` (a + current record on a reference host), `stale` (that record's release_pin is + behind the catalogue's pin), `superseded` (only superseded records) or + `missing`. The class is the producer's declaration, reported as given; a + `local_*` host class never counts as current. Plans only — never runs. + """ + pin = pin_order(lifecycle["release_pin"]) + by_key: dict[tuple, list[dict[str, Any]]] = {} + for record in lifecycle["records"]: + by_key.setdefault(record["key"], []).append(record) + tree = lifecycle_tree(ws) + + cells: list[dict[str, Any]] = [] + groups: dict[tuple, dict[str, int]] = {} + class_mismatches: list[dict[str, Any]] = [] + for key, declared_class in sorted(lifecycle["planned"].items()): + records = by_key.get(key, []) + current = [r for r in records if r["status"] == "current" and not is_local_host(key[4])] + record = current[0] if current else None + if record is not None: + behind = pin is not None and (pin_order(record["release_pin"]) or ()) < pin + state = "stale" if behind else "current" + if record["class"] != declared_class: + class_mismatches.append({"cell": _cell_id(key), "planned": declared_class, + "record": record["id"], "declared": record["class"]}) + else: + state = "superseded" if records else "missing" + host_dir = tree.get(key[:5]) + cells.append({ + "cell": _cell_id(key), + "likelihood": f"{key[0]}/{key[1]}", + "class": declared_class, + "measurement": key[6], + "state": state, + "record": record["id"] if record else None, + "tree": "absent" if host_dir is None else ( + "present" if (host_dir / f"{key[6]}.json").is_file() else "directory only"), + }) + group = groups.setdefault((f"{key[0]}/{key[1]}", declared_class, key[6]), + dict.fromkeys(CELL_STATES, 0)) + group[state] += 1 + + planned = lifecycle["planned"] + never_current = [r["id"] for r in lifecycle["records"] + if r["status"] == "current" and is_local_host(r["key"][4])] + unplanned = [{"record": r["id"], "class": r["class"], "status": r["status"]} + for r in lifecycle["records"] if r["key"] not in planned] + recorded = {r["key"][:5] for r in lifecycle["records"]} | {k[:5] for k in planned} + tree_unrecorded = sorted(path.relative_to(ws).as_posix() + for k, path in tree.items() if k not in recorded) + + dispatch: list[str] = [] + for cell, key in zip(cells, sorted(planned)): + if cell["state"] not in ("missing", "stale"): + continue + route = HOST_ROUTES.get(key[4]) + if route is None: + continue + script = MEASUREMENT_SCRIPTS.get(key[6]) + source = f"scripts/{key[0]}/{key[1]}/{script}" if script else "no declared script" + dispatch.append(f"{route} — {cell['cell']} ({cell['state']}; {source}; " + f"per-run cap {DEFAULT_PER_RUN_TIMEOUT}s)") + + counts = {state: sum(1 for c in cells if c["state"] == state) for state in CELL_STATES} + outstanding = counts["missing"] + counts["stale"] + return { + "agent": "profiling", + "mode": "campaign", + "catalogue": "profiling-summary@3", + "tier": tier, + "tier_note": "lifecycle grid: each cell is routed by its host_class, not by --tier", + "planned_cells": len(cells), + "cells_current": counts["current"], + "cells_stale": counts["stale"], + "cells_superseded": counts["superseded"], + "cells_missing": counts["missing"], + "records_superseded": sum(1 for r in lifecycle["records"] if r["status"] == "superseded"), + "coverage": [ + {"likelihood": lk, "class": cls, "measurement": m, **group} + for (lk, cls, m), group in sorted(groups.items()) + ], + "cells": cells, + "never_current": never_current, + "unplanned_records": unplanned, + "class_mismatches": class_mismatches, + "tree_unrecorded": tree_unrecorded, + "catalogue_evidence": {k: lifecycle[k] for k in ( + "source", "sha256", "version", "release_pin", "release_pin_source", + "archive_record_count")}, + "policy": ( + "Class and status are the producer's declarations, reported as given; " + "`optimal` is a Pulse designation decision, never inferred here. " + f"`{LOCAL_HOST_PREFIX}*` host classes never count as current. " + f"stale = a current record's release_pin behind the catalogue's pin. " + f"CPU-usability: per-run wall-clock cap {DEFAULT_PER_RUN_TIMEOUT}s; CPU runs on `ral` only." + ), + "evidence_qualification": "Catalogue presence is the producer's declaration, not a re-measured or accepted baseline.", + "dispatch_plan": dispatch, + "next_action": ( + f"dispatch the lifecycle plan ({outstanding} missing/stale planned cells)" + if outstanding else + "planned cells all current — proceed to ingest" + ), + } + + def campaign_compile(ws: Path, tier: str) -> dict[str, Any]: """Coverage of the jax_compile corpus against the science grid. @@ -903,6 +1059,34 @@ def emit_human(d: dict[str, Any]) -> None: print("Dispatch plan:") for s in d["dispatch_plan"]: print(f" - {s}") + elif d["mode"] == "campaign" and d.get("catalogue") == "profiling-summary@3": + ev = d["catalogue_evidence"] + print(f"Catalogue: {ev['source']} (profiling-summary@3, pin " + f"{ev['release_pin']} from {ev['release_pin_source']})") + print( + f"Planned cells: {d['cells_current']} current · {d['cells_stale']} stale · " + f"{d['cells_superseded']} superseded · {d['cells_missing']} missing " + f"(of {d['planned_cells']}; {d['records_superseded']} superseded record(s))" + ) + for row in d["coverage"]: + print(f" {row['likelihood']} {row['class']} {row['measurement']}: " + + " · ".join(f"{row[s]} {s}" for s in CELL_STATES)) + for cell in d["cells"]: + if cell["state"] != "current": + print(f" {cell['state']}: {cell['cell']} (tree {cell['tree']})") + for rid in d["never_current"]: + print(f" never current (local host): {rid}") + for m in d["class_mismatches"]: + print(f" class mismatch: {m['cell']} planned {m['planned']}, " + f"record {m['record']} declares {m['declared']}") + if d["unplanned_records"]: + print(f"Unplanned records: {len(d['unplanned_records'])}") + for path in d["tree_unrecorded"]: + print(f" tree without a catalogue row: {path}") + print(f"Policy: {d['policy']}") + print("Dispatch plan:") + for s in d["dispatch_plan"]: + print(f" - {s}") elif d["mode"] == "campaign": print(f"Tier: {d['tier']}") print( diff --git a/agents/faculties/samplers/AGENTS.md b/agents/faculties/samplers/AGENTS.md index 83bea4a6..4dab7339 100644 --- a/agents/faculties/samplers/AGENTS.md +++ b/agents/faculties/samplers/AGENTS.md @@ -34,7 +34,11 @@ samplers.sh [--json] experiment probes (autolens_workspace_developer/searches_minimal) experiment findings (the same tier's *_findings.md, name + verdict) mature (autolens_inference — one row per - sampler/dataset_class/model_type cell) + sampler/dataset_type/variant cell, from + scripts///samplers/) + wall-time validation (autolens_inference — one row per + scripts///validation/ + leaf; listed apart, never a sampler cell) mature (autofit_inference — its cells, plus one /: row per search catalogue cell, catalogue/search_catalogue.json) @@ -64,7 +68,15 @@ from its path — the two disagree on the live tree (the `cluster/searches/*/mge.py` leaves declare the `group` dataset class), and the declaration is what the runner acts on. `run_point_search` leaves take the runner's defaults (`nautilus`, `point_source`) for omitted keywords and their -stem as the model type, wherever they sit under `scripts/`. The lane tiers are +stem as the model type, wherever they sit under `scripts/`. A leaf with no +readable declaration falls back to its path: autolens_inference's +`scripts///samplers/.py` (or +`samplers//.py`) gives `//`; +autofit_inference's `scripts//searches//.py` +keeps its shape. `scripts///validation/` leaves are +full-fit wall-time validation — a PyAutoPulse evidence axis +(`walltime-validation@1`, instance `lens-walltime`), never a PyAutoInsight +artefact — and are listed in their own tier, not as cells. The lane tiers are inventory only; they feed no `gaps` rule. ## Judgment: matching sampler to likelihood @@ -133,15 +145,16 @@ and promote what matures: hand-rolled harnesses, env-knob objectives, findings docs (`*_findings.md`). This tier may bypass the `af` search wrapper to probe mechanisms; its artifacts are the campaign record, not the product. -2. **Mature** — `autolens_inference/scripts//searches//`: +2. **Mature** — `autolens_inference/scripts///samplers/`: when a configuration *works*, it becomes a first-class cell on the **library** `af` search, with the *why it works and what was learned* in the cell docstring and the section README. Never promote - `searches_minimal`-style hand-rolled loops. **Empty until - autolens-inference phase 3**: `autolens_profiling` held these cells until - its retired inference programme was scrapped (autolens_profiling#245), and - the successor repo has not built them yet — an empty mature tier is the - expected reading today, not a missing surface. + `searches_minimal`-style hand-rolled loops. The live tier holds the + imaging `delaunay`/`rectangular` sampler leaves and the + `point_source_source/source_plane` cells; the old + `scripts//searches/` paths are README pointers only. Insight + sampler campaigns run these cells under `setup_mode: auto`, recording + `setup_resolved` as provenance. 3. **User-facing** — `autolens_workspace/scripts/guides/modeling/searches.py` (and siblings): the lessons at user altitude — which settings matter and when, no campaign internals. @@ -173,8 +186,9 @@ not inventoried. and Brain plans, but never into public user-facing output (the memory faculty's AGENTS.md is the rule's home). - **Inference campaigns** — `autolens_inference` (A100/HPC search runs on - real lensing likelihoods); its `scripts//searches//` cells - are the mature tier of the findings lane above. `autolens_profiling` is + real lensing likelihoods); its `scripts///samplers/` + cells are the mature tier of the findings lane above, and its + `validation/` leaves feed PyAutoPulse's `lens-walltime` instance. `autolens_profiling` is likelihood timing only and holds no search cells. - **Real-likelihood search experiments** — `autolens_workspace_developer/searches_minimal/` (findings docs: diff --git a/agents/faculties/samplers/_samplers.py b/agents/faculties/samplers/_samplers.py index 92fb94df..47b8bd89 100755 --- a/agents/faculties/samplers/_samplers.py +++ b/agents/faculties/samplers/_samplers.py @@ -231,7 +231,8 @@ def manifest_integration(manifest: dict, test: Path | None) -> dict[str, bool]: SURFACE_FIT_INFERENCE = "autofit_inference" TIER_LENS_PROBES = "experiment probes (autolens searches_minimal)" TIER_LENS_FINDINGS = "experiment findings (autolens searches_minimal)" -TIER_LENS_MATURE = "mature (autolens_inference searches cells)" +TIER_LENS_MATURE = "mature (autolens_inference sampler cells)" +TIER_LENS_VALIDATION = "wall-time validation (autolens_inference validation leaves)" TIER_FIT_MATURE = "mature (autofit_inference searches cells)" TIER_FIT_CATALOGUE = "mature (autofit_inference search catalogue)" FIT_CATALOGUE = Path("catalogue") / "search_catalogue.json" @@ -316,42 +317,84 @@ def _declared_cell(leaf: Path) -> tuple[str, str, str] | None: return None -def tier_mature(inference: Path) -> list[str]: - """Mature tier: the (sampler x dataset_class x model_type) cell matrix. +# The lifecycle layout's two leaf kinds under `scripts///` +# (autolens_inference's mirrored tree): `samplers/` holds sampler cells, +# `validation/` holds full-fit wall-time validation runs (a PyAutoPulse evidence +# axis, `walltime-validation@1`) — never sampler cells. +SAMPLERS_DIR = "samplers" +VALIDATION_DIR = "validation" - Walks every `scripts/**/*.py` leaf under an inference checkout, skipping - the `misc/` framework directory and `_`-prefixed helpers, and keeps the - leaves that declare a cell through a RUNNERS call — wherever they live - (the point-source leaves sit at `scripts/point_source//`, not - under a `searches/` directory). A `scripts//searches// - .py` leaf with no parsable declaration falls back to its path - shape rather than vanishing. - - The tier is EMPTY until autolens-inference phase 3 builds these cells - (autolens_profiling#245 removed the retired inference programme's copies, - and this walk was repointed here rather than left pointing at a tree that - no longer exists). An absent or empty `scripts/` returns `[]` — never - raises — so an un-cloned or still-empty successor repo is reported as a - surface with no cells rather than a crash. + +def _path_cell(rel: tuple[str, ...], stem: str) -> tuple[str, str, str] | None: + """The cell a leaf's path implies, for leaves with no parsable declaration. + + Two shapes, both `(sampler, dataset, model-or-variant)`: + + - lifecycle layout: `//samplers/.py` or + `//samplers//.py` -> (sampler, + dataset_type, variant); + - the older shape, still autofit_inference's: `/searches// + .py` -> (sampler, dataset, model_type). """ + if len(rel) == 4 and rel[2] == SAMPLERS_DIR: + return stem, rel[0], rel[1] + if len(rel) == 5 and rel[2] == SAMPLERS_DIR: + return rel[3], rel[0], rel[1] + if len(rel) == 4 and rel[1] == "searches": + return rel[2], rel[0], stem + return None + + +def _leaves(inference: Path): + """Every non-helper `scripts/**/*.py` leaf outside `misc/`, with its parts.""" scripts = inference / "scripts" if not scripts.is_dir(): - return [] - cells = set() + return for leaf in scripts.rglob("*.py"): rel = leaf.relative_to(scripts).parts if leaf.stem.startswith("_") or rel[0] == "misc": continue - declared = _declared_cell(leaf) - if declared is None: - if len(rel) == 4 and rel[1] == "searches": - declared = (rel[2], rel[0], leaf.stem) - else: - continue - cells.add("/".join(declared)) + yield leaf, rel + + +def tier_mature(inference: Path) -> list[str]: + """Mature tier: the (sampler x dataset x model-or-variant) cell matrix. + + Walks every `scripts/**/*.py` leaf under an inference checkout, skipping + the `misc/` framework directory, `_`-prefixed helpers and the + `//validation/` leaves (wall-time validation, listed + by `tier_validation`), and keeps the leaves that declare a cell through a + RUNNERS call — wherever they live (the point-source leaves declare their + cell through `run_point_search`). A leaf with no parsable declaration falls + back to its path shape (`_path_cell`) rather than vanishing. + + autolens_inference's sampler cells live at + `scripts///samplers/` (the mirrored lifecycle + layout); autofit_inference keeps `scripts//searches//`. + An absent or empty `scripts/` returns `[]` — never raises — so an + un-cloned checkout is reported as a surface with no cells, not a crash. + """ + cells = set() + for leaf, rel in _leaves(inference): + if len(rel) >= 4 and rel[2] == VALIDATION_DIR: + continue + declared = _declared_cell(leaf) or _path_cell(rel, leaf.stem) + if declared is not None: + cells.add("/".join(declared)) return sorted(cells) +def tier_validation(inference: Path) -> list[str]: + """Wall-time validation leaves: `//` for every + `scripts///validation/.py`. + + Full-fit wall-time validation is a PyAutoPulse evidence axis + (`walltime-validation@1`), not a sampler cell, so these leaves are listed + apart from the mature tier and never enter its matrix.""" + return sorted(f"{rel[0]}/{rel[1]}/{leaf.stem}" for leaf, rel in _leaves(inference) + if len(rel) == 4 and rel[2] == VALIDATION_DIR) + + tier_lens_mature = tier_mature # the lens surface's name for the shared walk @@ -488,6 +531,7 @@ def digest(autofit, developer, test, lens_developer=None, inference=None, if inference and inference.is_dir(): d["surfaces_present"].append(SURFACE_INFERENCE) d["tiers"][TIER_LENS_MATURE] = tier_mature(inference) + d["tiers"][TIER_LENS_VALIDATION] = tier_validation(inference) if fit_inference and fit_inference.is_dir(): d["surfaces_present"].append(SURFACE_FIT_INFERENCE) d["tiers"][TIER_FIT_MATURE] = tier_mature(fit_inference) diff --git a/skills/profiling/SKILL.md b/skills/profiling/SKILL.md index a0daf7aa..1b8c1342 100644 --- a/skills/profiling/SKILL.md +++ b/skills/profiling/SKILL.md @@ -7,3 +7,6 @@ description: Plan PyAutoLens performance campaigns, ingest fresh profiling resul Follow [`profiling.md`](profiling.md) exactly. Keep measurement execution in the profiling workspace and use the Brain agent for campaign decisions. + +For a new or re-optimised likelihood, render the L0–L7 phase prompts from +[`lifecycle.md`](lifecycle.md). diff --git a/skills/profiling/lifecycle.md b/skills/profiling/lifecycle.md new file mode 100644 index 00000000..cdb786a5 --- /dev/null +++ b/skills/profiling/lifecycle.md @@ -0,0 +1,367 @@ +# Likelihood lifecycle — phase-prompt template + +The sequence every PyAutoLens likelihood follows from first registration to a +designated, validated, sampler-tested setup (report §3.9 of the +`likelihood-lifecycle` epic). This page is a **template**: each step below ends +in one fenced `prompt` block that renders, by plain placeholder substitution, +into one PyAutoMind phase prompt. Phase 8's `pyauto-brain profiling lifecycle` +verb renders it mechanically; until then a session renders it by hand and files +the prompts through `/intake`. + +## Placeholders + +One set, nothing else is substituted: + +| Placeholder | Value | +|---|---| +| `` | one of the ten dataset types (`imaging`, `interferometer`, `datacube`, `point_source_image`, `point_source_source`, `multi_galaxy`, `group`, `cluster`, `multi_dataset`, `weak`) | +| `` | the likelihood variant (`delaunay`, `mge`, `source_plane`, …) | +| `` | the reference instrument the cells are measured on (`hst`, `sma`, `simple`, …) | +| `` | the named size bin (`standard` where the type has one bin) | +| `` | `new` (a likelihood not yet registered) or `reoptimised` (an existing likelihood whose optimum may have changed) | + +## Rendering rules + +1. `` = `new` renders L0–L7. `` = `reoptimised` renders L2–L7 + and drops L2's `Blocked-by:` line; L2's new `current` records supersede the + prior ones. +2. L6 is rendered only when the human answers yes at the L3 gate to "could this + designation change which sampler is chosen?". When L6 is not rendered, L7's + `Blocked-by:` names Phase 5. +3. Each block is written to the path on its fence line, substituted the same + way. The folder after the work type is the census target, so it matches + `Target:`. +4. File prompts lazily, one phase at a time, after the previous phase ships + (ledger rule of the `likelihood-lifecycle` epic). When the previous phase's + issue exists at filing, `Blocked-by:` may carry its `Repo#N` ref instead. +5. The epic slug is `lifecycle--`; add it to Mind + `epics.md` when L0 (or L2 for `reoptimised`) is filed. + +Every rendered header passes the `pyauto-brain intake census` header check +(`tests/test_profiling_lifecycle_template.py` renders `imaging/delaunay`). + +## Reading Pulse and Insight + +- Lookups read `class: optimal` and `status: current` unless the request asks + for secondary, experimental or superseded rows. +- `optimal` is always a PyAutoPulse `designation` decision. The producer + declares `class` from that decision; no conductor infers or assigns it. +- Full-fit wall-time validation is a PyAutoPulse evidence axis + (`walltime-validation@1`, instance `lens-walltime`, producer + autolens_inference), never a PyAutoInsight artefact. +- PyAutoInsight sampler campaigns record `setup_mode: auto`, with + `setup_resolved` as provenance. +- Pulse selector order: Class → Likelihood → Instrument → Hardware class → + Measurement. + +## Steps + +| Step | Owning repos | Brain door | Human gate | Witness (short) | +|---|---|---|---|---| +| L0 register | autolens_profiling, PyAutoPulse | `/profiling`, `/intake` | approve regime bins and planned classes | planned cells listed as `missing` | +| L1 figures | autolens_visualization, PyAutoEyes | `/eyes` | sign off `fit.png` | `fit.png` signed off | +| L2 profile | autolens_profiling, PyAutoPulse | `/profiling` | RAL compute per batch | no missing/stale optimal or secondary runtime/breakdown cell | +| L3 designate | PyAutoPulse, autolens_profiling, PyAutoArray, PyAutoLens, autolens_workspace, autolens_assistant | `/profiling`, `/intake` | approve the designation | Pulse `designation` decision resolved by every optimal record | +| L4 validate | autolens_inference, PyAutoPulse | `/profiling` | RAL compute per batch | `walltime-validation@1` row per optimal setup | +| L5 gradient | autolens_profiling, PyAutoPulse | `/profiling` | RAL compute per batch | current `gradient` record with passing FD check | +| L6 samplers | autolens_inference, PyAutoInsight | `/sampler_pipeline` | protocol freeze; compute | ≥3-seed rows per sampler under `setup_mode: auto` | +| L7 close | PyAutoPulse, PyAutoMind, PyAutoCortex | `/cortex` | human closes the epic | Pulse task complete; Mind record; Cortex note | + +### L0 register + +Register the likelihood: the taxonomy row and source route in autolens_profiling +(`catalogue/script_routes.json`), the declared regime, and the Pulse +`planned_cells` with a class per setup. + +```prompt draft/feature/autolens_profiling/lifecycle___l0_register.md +# Lifecycle / L0 register: taxonomy row, regime and Pulse planned cells + +Type: feature +Target: autolens_profiling +Repos: +- autolens_profiling +- PyAutoPulse +Themes: +- profiling +- dashboard +Difficulty: small +Autonomy: supervised +Priority: normal +Status: formalised +Consequence: judge +Witness: `pyauto-brain profiling campaign` lists the `/` planned cells on `` (regime ``) as `missing` under their declared class, and `pyauto-pulse check` accepts the `profiling-summary@3` catalogue that declares them +Review-minutes: 10 +Unattended: never +Epic: lifecycle-- +Phase: 0 + +Lifecycle step L0 for `/` on ``, regime ``, trigger ``. + +- autolens_profiling: add the source route and runtime cell for `scripts///` to `catalogue/script_routes.json`; declare regime `` for ``. +- autolens_profiling catalogue: emit `planned_cells` for `/` on ``, one per setup and measurement (`runtime`, `breakdown`), each with the class the producer declares (`optimal`, `secondary` or `experimental`). +- Human gate: approve the regime bins and the planned classes before L2 measures anything. +- Door: `/profiling` (`campaign` shows the new cells); this prompt is filed through `/intake`. +``` + +### L1 figures + +Render `fit.png` for the likelihood through the visualization plotter and sign +it off (the Eyes loop when the figure is new). + +```prompt draft/feature/autolens_visualization/lifecycle___l1_figures.md +# Lifecycle / L1 figures: fit.png through the viz plotter, signed off + +Type: feature +Target: autolens_visualization +Repos: +- autolens_visualization +- PyAutoEyes +Themes: +- visualization +- profiling +Difficulty: small +Autonomy: supervised +Priority: normal +Status: formalised +Consequence: judge +Witness: `fit.png` for `/` on `` is rendered by the visualization harness, listed in `gallery/viz_manifest.yaml`, and signed off by the human in the `/eyes` loop +Review-minutes: 10 +Unattended: never +Epic: lifecycle-- +Phase: 1 +Blocked-by: lifecycle-- Phase 0 + +Lifecycle step L1 for `/` on ``, regime ``, trigger ``. + +- autolens_visualization: add or refresh the producer that renders `fit.png` for `/` on ``. +- PyAutoEyes: the figure appears on the Eyes board through the manifest; nothing is copied. +- Human gate: the human signs off `fit.png` in the `/eyes` loop. +- Door: `/eyes`. +``` + +### L2 profile + +Measure runtime and breakdown under the Optimal and Secondary candidates on +reference hosts with a parity witness; the new records become `current` and +the prior ones `superseded`. A `reoptimised` likelihood enters here. + +```prompt draft/research/autolens_profiling/lifecycle___l2_profile.md +# Lifecycle / L2 profile: runtime and breakdown under optimal and secondary candidates + +Type: research +Target: autolens_profiling +Repos: +- autolens_profiling +- PyAutoPulse +Themes: +- profiling +- hpc-gpu +Difficulty: medium +Autonomy: supervised +Priority: normal +Status: formalised +Consequence: judge +Witness: `pyauto-brain profiling campaign` reports zero `missing` and zero `stale` cells for `/` on `` across class optimal and secondary × measurement runtime and breakdown, each current record on a reference host class with a passing `parity.json`, prior records `superseded`, and the Pulse receipt ok +Review-minutes: 20 +Unattended: never +Epic: lifecycle-- +Phase: 2 +Blocked-by: lifecycle-- Phase 1 + +Lifecycle step L2 for `/` on ``, regime ``, trigger ``. + +- autolens_profiling: run `scripts///likelihood_runtime.py` and `likelihood_breakdown.py` for every planned optimal and secondary setup on reference host classes (`hpc_ral_cpu` on `--partition=ral`, `hpc_a100` with `--gres`); write `results//////` with `parity.json`. +- Catalogue: the new records are `current`; the records they replace are `superseded` with `superseded_by` set. `local_*` host rows are never `current`. +- Human gate: authorise each RAL batch. +- Door: `/profiling` (`campaign` gives the plan; it never runs). +``` + +### L3 designate + +Record which setup is Optimal and which are Secondary for the likelihood and +regime, and carry the decision into the library, the run-time estimates and +the user-facing text. + +```prompt draft/feature/pyautopulse/lifecycle___l3_designate.md +# Lifecycle / L3 designate: Pulse designation decision, rule table, estimates and text + +Type: feature +Target: pyautopulse +Repos: +- PyAutoPulse +- autolens_profiling +- PyAutoArray +- PyAutoLens +- autolens_workspace +- autolens_assistant +Themes: +- profiling +- assistants +Difficulty: medium +Autonomy: human-required +Priority: normal +Status: formalised +Consequence: judge +Witness: PyAutoPulse `decisions.yaml` has a `designation` row for `/` regime `` naming the optimal and secondary `setup_id`s with evidence record ids, every `class: optimal` current record cites it as `decision_id`, and the library rule-table parity test passes +Review-minutes: 25 +Unattended: never +Epic: lifecycle-- +Phase: 3 +Blocked-by: lifecycle-- Phase 2 + +Lifecycle step L3 for `/` on ``, regime ``, trigger ``. + +- PyAutoPulse: a `designation` decision (`decisions/.md` + `decisions.yaml`) with `likelihood`, `regime`, `hardware_class`, `optimal`, `secondary`, `evidence`, `rule`, `supersedes`. +- autolens_profiling: the wiki decision-rule note under `wiki/campaigns///`; catalogue records declare `class` from the decision. +- PyAutoArray: rule-table PR from the decision; PyAutoLens: `runtime_estimates` refresh. +- autolens_workspace and autolens_assistant: text that names the setup follows the decision. +- Human gate: the human approves the designation. `optimal` is never inferred by a conductor. +- Door: `/profiling` (`ingest`); library and workspace edits go through `/start_dev`. +``` + +### L4 validate + +Full-fit wall-time validation of the Optimal setups: autolens_inference +produces `walltime-validation@1` records that PyAutoPulse renders (instance +`lens-walltime`). + +```prompt draft/research/autolens_inference/lifecycle___l4_validate.md +# Lifecycle / L4 validate: full-fit wall-time validation on the optimal setups + +Type: research +Target: autolens_inference +Repos: +- autolens_inference +- PyAutoPulse +Themes: +- profiling +- hpc-gpu +Difficulty: medium +Autonomy: supervised +Priority: normal +Status: formalised +Consequence: judge +Witness: PyAutoPulse instance `lens-walltime` holds a `walltime-validation@1` record for every optimal setup of `/` on ``, each with `reference_runtime_record_id` resolving to the L2 current runtime record and `ratio_measured_over_predicted` declared +Review-minutes: 20 +Unattended: never +Epic: lifecycle-- +Phase: 4 +Blocked-by: lifecycle-- Phase 3 + +Lifecycle step L4 for `/` on ``, regime ``, trigger ``. + +- autolens_inference: run `scripts///validation/` for each optimal setup; results under `results////validation/`. +- PyAutoPulse: the `lens-walltime` receipt refreshes; Pulse renders the producer's derived numbers and computes none. +- Human gate: authorise each RAL batch. +- Door: `/profiling` (the conductor judges timing; PyAutoInsight is not involved). +``` + +### L5 gradient + +`value_and_grad` breakdown under each Optimal setup with a finite-difference +check, recorded as the `gradient` measurement. + +```prompt draft/research/autolens_profiling/lifecycle___l5_gradient.md +# Lifecycle / L5 gradient: value_and_grad breakdown with a finite-difference check + +Type: research +Target: autolens_profiling +Repos: +- autolens_profiling +- PyAutoPulse +Themes: +- jax-gradient +- profiling +Difficulty: medium +Autonomy: supervised +Priority: normal +Status: formalised +Consequence: judge +Witness: `pyauto-brain profiling campaign` reports a `current` `gradient` cell for every optimal setup of `/` on ``, each record carrying a passing finite-difference check +Review-minutes: 15 +Unattended: never +Epic: lifecycle-- +Phase: 5 +Blocked-by: lifecycle-- Phase 4 + +Lifecycle step L5 for `/` on ``, regime ``, trigger ``. + +- autolens_profiling: run `scripts///gradient_breakdown.py` under each optimal setup; write `gradient.json` beside the runtime record. +- Catalogue: `measurement: gradient` records, `current`, with the FD check in `values`. +- Human gate: authorise each RAL batch. +- Door: `/profiling`. +``` + +### L6 samplers + +A PyAutoInsight sampler campaign under `setup_mode: auto`, rendered only when +the designation could change which sampler is chosen (rendering rule 2). + +```prompt draft/research/autolens_inference/lifecycle___l6_samplers.md +# Lifecycle / L6 samplers: Insight campaign under setup_mode auto + +Type: research +Target: autolens_inference +Repos: +- autolens_inference +- PyAutoInsight +Themes: +- samplers +- hpc-gpu +Difficulty: large +Autonomy: supervised +Priority: normal +Status: formalised +Consequence: judge +Witness: PyAutoInsight shows at least three scored seeds per sampler for `/` on ``, every record with `setup_mode: auto` and `setup_resolved` recorded +Review-minutes: 25 +Unattended: never +Epic: lifecycle-- +Phase: 6 +Blocked-by: lifecycle-- Phase 5 + +Lifecycle step L6 for `/` on ``, regime ``, trigger ``. + +- autolens_inference: run `scripts///samplers/` under `setup_mode: auto`; results under `results////samplers///auto/seed_/`. +- PyAutoInsight: the receipt refreshes; `setup_resolved` is provenance, not identity. +- Human gate: freeze the protocol before compute; authorise each batch. +- Door: `/sampler_pipeline` (the samplers faculty lists the cells). +``` + +### L7 close + +Close the lifecycle: the Pulse campaign task completes, the Mind records the +epic, and the Cortex notes any change to the science. + +```prompt draft/maintenance/pyautopulse/lifecycle___l7_close.md +# Lifecycle / L7 close: Pulse task complete, Mind record, Cortex note + +Type: maintenance +Target: pyautopulse +Repos: +- PyAutoPulse +- PyAutoMind +- PyAutoCortex +Themes: +- dashboard +- mind-workflow +Difficulty: small +Autonomy: supervised +Priority: normal +Status: formalised +Consequence: glance +Witness: the PyAutoPulse campaign task for `/` is `complete`, PyAutoMind holds the epic's `complete/` record, and the PyAutoCortex ledger carries a note wherever the science changed +Review-minutes: 5 +Unattended: never +Epic: lifecycle-- +Phase: 7 +Blocked-by: lifecycle-- Phase 6 + +Lifecycle step L7 for `/` on ``, regime ``, trigger ``. + +- PyAutoPulse: mark the campaign task for `/` complete. +- PyAutoMind: write the epic's `complete/` record and retire it from `epics.md`. +- PyAutoCortex: a ledger note when the designation or validation changed the science. +- Human gate: the human closes the epic. +- Door: `/cortex` (check-in); merges go through `/prm`. +``` diff --git a/skills/profiling/profiling.md b/skills/profiling/profiling.md index 1254c0c6..621965b1 100644 --- a/skills/profiling/profiling.md +++ b/skills/profiling/profiling.md @@ -29,6 +29,27 @@ board: open that row, read the pair of records and their evidence paths, then judge with the `triage` verb (which takes no target — the key is where to look, not an argument). +## Reading Pulse and Insight + +- Research and check-in lookups read `class: optimal` + `status: current` + unless the request asks for secondary, experimental or superseded rows. +- `optimal` is always a PyAutoPulse `designation` decision. The producer + declares `class`; this command reports it and never infers or assigns it. +- Full-fit wall-time validation is a Pulse evidence axis + (`walltime-validation@1`, instance `lens-walltime`, producer + autolens_inference), never a PyAutoInsight artefact. +- PyAutoInsight sampler campaigns record `setup_mode: auto`, with + `setup_resolved` as provenance. +- The Pulse board's selector order is Class (Optimal by default) → Likelihood + → Instrument → Hardware class → Measurement. + +## Likelihood lifecycle + +A new likelihood, or a re-optimisation of an existing one, runs the L0–L7 +sequence in [`lifecycle.md`](lifecycle.md): render its phase prompts and file +them through `/intake`, one phase at a time. A new likelihood starts at L0; a +re-optimisation enters at L2. + The Profiling Agent **reasons; it never runs sweeps or edits source.** The classification is the result for CPU-unusable cells; full timings for those belong to the A100 rows. @@ -36,7 +57,7 @@ belong to the A100 rows. ## Source catalogue and evidence qualification Read the project's `catalogue/script_routes.json` first, then the published v2 -catalogue's `script_routes` extension. The conductor validates this stdlib-only +(or v3) catalogue's `script_routes` extension. The conductor validates this stdlib-only contract and reports its source/digest. Legacy sweep AST routing remains only for projects without the new producer; invalid new data is an error, not a fallback. @@ -44,6 +65,17 @@ Model-first source paths do not rename historical cell IDs or result paths. Archive coverage is unreviewed evidence, never baseline acceptance or a claim of current performance. Missing metadata stays unknown. An unavailable compile builder or absent canonical source suppresses dispatch, with the reason visible. +When the published `dashboard/catalogue.json` is `profiling-summary@3`, +`campaign` reports the lifecycle grid instead: per likelihood +(`/`) × class × measurement, each planned cell is +`current`, `stale` (its current record's `release_pin` is behind the +catalogue's), `superseded` or `missing`. It reads +`results//////` when +present, refuses a `setup_id` off the +`___[_]` grammar +(`SetupIdError`), and never counts a `local_*` host class as current. A v2 or +absent catalogue keeps the legacy grid unchanged. + Campaign commands are plans only; baseline measurement and acceptance require a separate human-authorized campaign. CPU caps and the RAL CPU partition policy remain unchanged. Pulse owns campaign intent, Cortex scientific records and Mind diff --git a/skills/sampler_pipeline/SKILL.md b/skills/sampler_pipeline/SKILL.md index e1a69841..a34fc76e 100644 --- a/skills/sampler_pipeline/SKILL.md +++ b/skills/sampler_pipeline/SKILL.md @@ -74,8 +74,12 @@ The prototype contract (what makes its row comparable): promotion argument — the 1D Gaussian alone never justifies promotion. - Record inference campaign intent and coverage through **PyAutoInsight**; keep protocols, per-search statuses and detailed results in the relevant - `*_inference` project. Record profiling campaigns and timing/drift evidence - through **PyAutoPulse**, with measurements in the `*_profiling` project. + `*_inference` project. Insight sampler campaigns record `setup_mode: auto`, + with `setup_resolved` as provenance. Record profiling campaigns and + timing/drift evidence through **PyAutoPulse**, with measurements in the + `*_profiling` project. Full-fit wall-time validation (autolens_inference + `validation/` leaves) is a Pulse evidence axis — `walltime-validation@1`, + instance `lens-walltime` — never an Insight artefact. - Keep only reusable methodological lessons and short links to those owners in **PyAutoMemory**. Durability alone is not a reason to copy campaign records there. Cortex retains scientific run records and human conclusions; Mind diff --git a/skills/sampler_pipeline/reference.md b/skills/sampler_pipeline/reference.md index 84b53a14..43e82c54 100644 --- a/skills/sampler_pipeline/reference.md +++ b/skills/sampler_pipeline/reference.md @@ -111,13 +111,17 @@ table. cache compiled closures. Full list: the faculty's AGENTS.md. - Real-likelihood evidence (required before any promotion argument): run the candidate on lensing use cases via `autolens_inference` — its - `scripts//searches//.py` cells are the mature + `scripts///samplers/` cells are the mature tier; A100/HPC runs go through that repo's conventions. Per-evaluation likelihood cost stays with the `/profile_likelihood` skill. - Record inference campaign intent and coverage through **PyAutoInsight**; keep protocols, per-search statuses and detailed results in the relevant - `*_inference` project. Record profiling campaigns and timing/drift evidence - through **PyAutoPulse**, with measurements in the `*_profiling` project. + `*_inference` project. Insight sampler campaigns record `setup_mode: auto`, + with `setup_resolved` as provenance. Record profiling campaigns and + timing/drift evidence through **PyAutoPulse**, with measurements in the + `*_profiling` project. Full-fit wall-time validation (autolens_inference + `validation/` leaves) is a Pulse evidence axis — `walltime-validation@1`, + instance `lens-walltime` — never an Insight artefact. - Keep only reusable methodological lessons and short links to those owners in **PyAutoMemory**. Durability alone is not a reason to copy campaign records there. Cortex retains scientific run records and human conclusions; Mind diff --git a/tests/test_profiling_conductor.py b/tests/test_profiling_conductor.py index 3d45f436..aec6040f 100644 --- a/tests/test_profiling_conductor.py +++ b/tests/test_profiling_conductor.py @@ -761,3 +761,154 @@ def test_compile_dispatch_uses_declared_probe_and_requires_its_source(tmp_path): d = json.loads(p.stdout) assert d["dispatch_plan"] assert all("python3 scripts/misc/jax_compile/alternative.py " in command for command in d["dispatch_plan"]) + + +# --------------------------------------------------------------------------- +# profiling-summary@3: the lifecycle grid over the mirrored results tree +# --------------------------------------------------------------------------- + +PIN = "2026.10.16.2" + + +def _key(dataset_type, variant, instrument, setup_id, host_class, measurement="runtime"): + return {"likelihood": {"dataset_type": dataset_type, "variant": variant}, + "instrument": instrument, "setup_id": setup_id, "host_class": host_class, + "model_variant": "default", "measurement": measurement} + + +def _v3_record(rid, key, cls, status, pin=PIN, superseded_by=None): + return {**key, "id": rid, "class": cls, "status": status, "release_pin": pin, + "superseded_by": superseded_by, "regime": "standard", + "metric": "single_call", "unit": "s", "values": {"single_call": 0.01}} + + +A100 = _key("imaging", "delaunay", "hst", "jax_gpu_dense_fp64", "hpc_a100") +RAL = _key("imaging", "delaunay", "hst", "numba_cpu_sparse_fp64", "hpc_ral_cpu") +EUCLID = _key("imaging", "delaunay", "euclid", "jax_gpu_dense_fp64", "hpc_a100") +SMA = _key("interferometer", "mge", "sma", "jax_cpu_dense_fp64_nufft", "hpc_ral_cpu") +LAPTOP = _key("imaging", "delaunay", "hst", "jax_cpu_dense_fp64", "local_laptop") + + +def _v3_catalogue(): + return { + "schema": "profiling-summary", "version": 3, "project": "fixture", + "planned_cells": [{**A100, "class": "optimal"}, {**RAL, "class": "secondary"}, + {**EUCLID, "class": "optimal"}, {**SMA, "class": "optimal"}], + "records": [ + _v3_record("a100-now", A100, "optimal", "current"), + _v3_record("a100-old", A100, "optimal", "superseded", superseded_by="a100-now"), + _v3_record("ral-now", RAL, "secondary", "current", pin="2026.10.4.1"), + _v3_record("sma-old", SMA, "optimal", "superseded", superseded_by="sma-gone"), + _v3_record("laptop", LAPTOP, "experimental", "current"), + ], + "archive_record_count": 2, + } + + +def _v3_workspace(tmp_path, catalogue=None): + """The legacy fixture plus a §3.7 mirrored tree and a published @3 catalogue, + so the test also proves the @3 grid wins over the legacy sweep grid.""" + ws = _workspace(tmp_path) + cell = ws / "results/imaging/delaunay/hst/jax_gpu_dense_fp64/hpc_a100" + cell.mkdir(parents=True) + (cell / "runtime.json").write_text("{}") + (ws / "results/imaging/delaunay/hst/numba_cpu_sparse_fp64/hpc_ral_cpu").mkdir(parents=True) + (ws / "results/imaging/delaunay/hst/jax_cpu_dense_fp64/local_laptop").mkdir(parents=True) + (ws / "dashboard").mkdir() + (ws / "dashboard/catalogue.json").write_text(json.dumps(catalogue or _v3_catalogue())) + return ws + + +def test_v3_catalogue_reports_class_by_measurement_coverage(tmp_path): + p = _run(["campaign", "--json"], _v3_workspace(tmp_path)) + assert p.returncode == 0, p.stderr + d = json.loads(p.stdout) + assert d["catalogue"] == "profiling-summary@3" + assert (d["planned_cells"], d["cells_current"], d["cells_stale"], + d["cells_superseded"], d["cells_missing"]) == (4, 1, 1, 1, 1) + assert d["records_superseded"] == 2 + assert d["coverage"] == [ + {"likelihood": "imaging/delaunay", "class": "optimal", "measurement": "runtime", + "current": 1, "stale": 0, "superseded": 0, "missing": 1}, + {"likelihood": "imaging/delaunay", "class": "secondary", "measurement": "runtime", + "current": 0, "stale": 1, "superseded": 0, "missing": 0}, + {"likelihood": "interferometer/mge", "class": "optimal", "measurement": "runtime", + "current": 0, "stale": 0, "superseded": 1, "missing": 0}, + ] + states = {c["cell"]: (c["state"], c["tree"]) for c in d["cells"]} + assert states["imaging/delaunay/hst jax_gpu_dense_fp64@hpc_a100 [runtime]"] == ("current", "present") + assert states["imaging/delaunay/hst numba_cpu_sparse_fp64@hpc_ral_cpu [runtime]"] == ( + "stale", "directory only") + assert states["imaging/delaunay/euclid jax_gpu_dense_fp64@hpc_a100 [runtime]"] == ("missing", "absent") + # R7: a laptop row is flagged and never counts, whatever its declared status + assert d["never_current"] == ["laptop"] + assert {"record": "laptop", "class": "experimental", "status": "current"} in d["unplanned_records"] + assert d["catalogue_evidence"]["release_pin"] == PIN + assert d["catalogue_evidence"]["release_pin_source"] == "newest record" + + +def test_v3_dispatch_routes_by_host_class_and_never_runs(tmp_path): + ws = _v3_workspace(tmp_path) + before = sorted(str(p) for p in ws.rglob("*")) + d = json.loads(_run(["campaign", "--json"], ws).stdout) + plan = d["dispatch_plan"] + assert len(plan) == 2 + assert any(s.startswith("RAL CPU: sbatch --partition=ral") and "stale" in s for s in plan) + assert any(s.startswith("RAL A100") and "euclid" in s and "missing" in s for s in plan) + assert all("scripts/imaging/delaunay/likelihood_runtime.py" in s for s in plan) + assert sorted(str(p) for p in ws.rglob("*")) == before + human = _run(["campaign"], ws) + assert human.returncode == 0 and "profiling-summary@3" in human.stdout + + +def test_v3_reports_class_as_declared_and_flags_mismatch(tmp_path): + cat = _v3_catalogue() + cat["records"][0]["class"] = "secondary" + d = json.loads(_run(["campaign", "--json"], _v3_workspace(tmp_path, cat)).stdout) + assert d["class_mismatches"] == [{ + "cell": "imaging/delaunay/hst jax_gpu_dense_fp64@hpc_a100 [runtime]", + "planned": "optimal", "record": "a100-now", "declared": "secondary"}] + + +def test_v3_envelope_pin_wins_and_marks_stale(tmp_path): + cat = {**_v3_catalogue(), "release_pin": "2026.11.1.1"} + d = json.loads(_run(["campaign", "--json"], _v3_workspace(tmp_path, cat)).stdout) + assert d["catalogue_evidence"]["release_pin_source"] == "envelope" + assert d["cells_current"] == 0 and d["cells_stale"] == 2 + + +def test_v2_published_catalogue_keeps_legacy_campaign_byte_identical(tmp_path): + ws = _workspace(tmp_path) + legacy = _run(["campaign", "--json"], ws).stdout + (ws / "dashboard").mkdir() + (ws / "dashboard/catalogue.json").write_text(json.dumps( + {"schema": "profiling-summary", "version": 2, "records": [], "planned_cells": []})) + assert _run(["campaign", "--json"], ws).stdout == legacy + assert "catalogue" not in json.loads(legacy) + + +def test_v3_bad_setup_id_grammar_is_refused_by_name(tmp_path): + for bad in ("jax_gpu_fp64", "jax_gpu_dense_fp64_na", "jax_tpu_dense_fp64", "jax_gpu_dense_fp32"): + cat = _v3_catalogue() + cat["records"][0]["setup_id"] = bad + p = _run(["campaign", "--json"], _v3_workspace(tmp_path / bad, cat)) + assert p.returncode == 4 + assert json.loads(p.stdout)["error"].startswith("SetupIdError:") + + +def test_v3_bad_tree_directory_grammar_is_refused_by_name(tmp_path): + ws = _v3_workspace(tmp_path) + (ws / "results/imaging/delaunay/hst/gpu_fast/hpc_a100").mkdir(parents=True) + p = _run(["campaign", "--json"], ws) + assert p.returncode == 4 + error = json.loads(p.stdout)["error"] + assert error.startswith("SetupIdError:") and "gpu_fast" in error + + +def test_v3_archived_record_and_unknown_class_are_refused(tmp_path): + for field, value in (("status", "archived"), ("class", "fastest")): + cat = _v3_catalogue() + cat["records"][0][field] = value + p = _run(["campaign", "--json"], _v3_workspace(tmp_path / value, cat)) + assert p.returncode == 4 + assert "records[0]" in json.loads(p.stdout)["error"] diff --git a/tests/test_profiling_lifecycle_template.py b/tests/test_profiling_lifecycle_template.py new file mode 100644 index 00000000..933c8ba6 --- /dev/null +++ b/tests/test_profiling_lifecycle_template.py @@ -0,0 +1,92 @@ +"""The likelihood-lifecycle template renders into census-clean Mind prompts. + +`skills/profiling/lifecycle.md` is rendered here the way phase 8's verb will: +plain placeholder substitution, one fenced `prompt ` block per step. The +rendered prompts are filed into a synthetic Mind and judged by the intake +conductor's own `census` — the check `pyauto-brain intake census` applies — so +the header rules are never restated in this file. +""" + +import importlib.util +import re +import sys +from pathlib import Path + +BRAIN_HOME = Path(__file__).resolve().parents[1] +TEMPLATE = BRAIN_HOME / "skills" / "profiling" / "lifecycle.md" +_spec = importlib.util.spec_from_file_location( + "_intake_lifecycle_under_test", + BRAIN_HOME / "agents" / "conductors" / "intake" / "_intake.py") +_intake = importlib.util.module_from_spec(_spec) +sys.modules["_intake_lifecycle_under_test"] = _intake +_spec.loader.exec_module(_intake) + +PLACEHOLDERS = ("", "", "", "", "") +BLOCK = re.compile(r"^```prompt (\S+)\n(.*?)^```$", re.M | re.S) +# The Mind vocabulary keywords the template uses (PyAutoMind themes.md). +THEMES = ("profiling", "dashboard", "visualization", "hpc-gpu", "assistants", + "jax-gradient", "samplers", "mind-workflow") + + +def _render(values): + text = TEMPLATE.read_text() + for placeholder, value in zip(PLACEHOLDERS, values): + text = text.replace(placeholder, value) + return BLOCK.findall(text) + + +def _file(mind, blocks): + (mind / "themes.md").write_text( + "# Themes\n\n## Vocabulary\n\n" + "".join(f"- `{t}`: x\n" for t in THEMES)) + for rel, body in blocks: + path = mind / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(body) + return _intake.census(mind) + + +def test_template_uses_one_placeholder_set_and_eight_steps(): + text = TEMPLATE.read_text() + blocks = BLOCK.findall(text) + assert len(blocks) == 8 + used = set(re.findall(r"<[a-z_]+>", "".join(path + body for path, body in blocks))) + # ``, ``, ``, ``, `` and + # `` are literal path grammar inside the prose, not placeholders. + assert used - {"", "", "", "", "", + ""} == set(PLACEHOLDERS) + + +def test_imaging_delaunay_render_passes_the_census_header_check(tmp_path): + blocks = _render(("imaging", "delaunay", "hst", "standard", "new")) + assert not any(p in path + body for path, body in blocks for p in PLACEHOLDERS) + c = _file(tmp_path, blocks) + assert len(c["records"]) == 8 + assert c["hygiene"] == [] and c["theme_flags"] == [] and c["drift"] == [] + assert c["witness_flags"] == [] + phases = [] + for r in c["records"]: + assert r["missing"] == [], r["path"] + assert r["epic"] == "lifecycle-imaging-delaunay" + assert isinstance(r["phase"], int) + assert r["witness"] + # the folder after the work type is the census target: it must agree + # with the prompt's own Type:/Target: header + assert r["header"]["type"] == r["work_type"] + assert r["header"]["target"] == r["target"] + assert ("blocked-by" in r["header"]) == (r["phase"] != 0) + phases.append(r["phase"]) + assert sorted(phases) == list(range(8)) + + +def test_reoptimised_render_starts_at_l2_unblocked(tmp_path): + blocks = [(path, body) for path, body in _render( + ("interferometer", "mge", "sma", "standard", "reoptimised")) + if not re.search(r"_l[01]_", path)] + # rendering rule 1: the entry step drops its Blocked-by line + blocks = [(p, re.sub(r"^Blocked-by: .*Phase 1\n", "", b, flags=re.M)) for p, b in blocks] + c = _file(tmp_path, blocks) + by_phase = {r["phase"]: r for r in c["records"]} + assert sorted(by_phase) == [2, 3, 4, 5, 6, 7] + assert "blocked-by" not in by_phase[2]["header"] + assert all(r["missing"] == [] for r in c["records"]) + assert "trigger `reoptimised`" in (tmp_path / by_phase[2]["path"]).read_text() diff --git a/tests/test_samplers_surface.py b/tests/test_samplers_surface.py index 67b91d1f..05247fdb 100644 --- a/tests/test_samplers_surface.py +++ b/tests/test_samplers_surface.py @@ -380,3 +380,49 @@ def test_fit_inference_without_catalogue_is_not_fatal(tmp_path): d = _digest("--fit-inference", str(root)) assert d["tiers"][_samplers.TIER_FIT_CATALOGUE] == [] assert "fit_inference_catalogue" not in d + + +# -------------------------------------------------------------------------- +# The mirrored lifecycle layout: scripts///{samplers,validation}/ +# -------------------------------------------------------------------------- + + +def _make_lifecycle(root: Path) -> Path: + """Two leaves under one likelihood: a sampler cell whose call names no + RUNNERS entry (so its path is its identity) and a wall-time validation run.""" + samplers = root / "scripts" / "imaging" / "delaunay" / "samplers" + validation = root / "scripts" / "imaging" / "delaunay" / "validation" + samplers.mkdir(parents=True) + validation.mkdir(parents=True) + (samplers / "nautilus.py").write_text( + "from experiments.run import main\n" + "main(setup_family=(\"imaging\", \"delaunay\"), sampler=\"nautilus\")\n") + (validation / "baseline_slam.py").write_text( + "from slam._runner import run_slam\n" + "run_slam(dataset_class=\"imaging\", default_instrument=\"hst\")\n") + return root + + +def test_lifecycle_sampler_leaf_is_a_mature_cell(tmp_path): + d = _digest("--inference", str(_make_lifecycle(tmp_path))) + assert d["tiers"][_samplers.TIER_LENS_MATURE] == ["nautilus/imaging/delaunay"] + + +def test_lifecycle_validation_leaves_are_listed_apart(tmp_path): + d = _digest("--inference", str(_make_lifecycle(tmp_path))) + assert d["tiers"][_samplers.TIER_LENS_VALIDATION] == ["imaging/delaunay/baseline_slam"] + # a validation leaf that happens to call a runner is still not a sampler cell + leaf = tmp_path / "scripts" / "imaging" / "delaunay" / "validation" / "declared.py" + leaf.write_text('run_search(sampler="emcee", dataset_class="imaging", model_type="x")\n') + d = _digest("--inference", str(tmp_path)) + assert d["tiers"][_samplers.TIER_LENS_MATURE] == ["nautilus/imaging/delaunay"] + + +def test_lifecycle_sampler_directory_shape_and_old_shape_coexist(tmp_path): + root = _make_mature(_make_lifecycle(tmp_path)) + nested = root / "scripts" / "interferometer" / "mge" / "samplers" / "emcee" + nested.mkdir(parents=True) + (nested / "seeded.py").write_text("# no runner call\n") + cells = _digest("--inference", str(root))["tiers"][_samplers.TIER_LENS_MATURE] + assert cells == ["emcee/interferometer/mge", "nautilus/group/mge", + "nautilus/imaging/delaunay", "nautilus/imaging/mge"]