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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions experiments/nautilus_worker_headroom/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# How much fit time can two-worker scheduling recover?

Keep the native scheduler on this phase 0a fixture. Across 14 traced fits, an ideal two-worker schedule could save at most **0.39–0.51% of complete fit wall time** with the measured per-proposal service times. The predeclared threshold for a live scheduling experiment was 5%. Even removing the entire submit-to-collection interval would save only 0.65–1.44%. [Phase issue and decision rule](https://github.com/PyAutoLabs/autofit_profiling/issues/28).

The source was a 5D analytic Gaussian with two persistent likelihood workers, native update interval 200 and logical batches of 100. Fixed and parameter-correlated costs each have three seeds per adapter. The synthetic random-cost case has one. Each row below gives the range across its seeds. All percentages in the last three columns use the full **traced** fit as denominator.

| Adapter | Cost | Fits | Worker occupancy inside maps | Entire map | Ideal scheduling ceiling | Single-point chunk prediction |
|---|---|---:|---:|---:|---:|---:|
| direct | fixed | 3 | 29.7–32.7% | 0.65–0.72% | 0.44–0.51% | 0.003–0.005% |
| direct | correlated | 3 | 44.1–45.6% | 0.76–0.81% | 0.43–0.44% | 0.013–0.015% |
| direct | random | 1 | 68.3% | 1.38% | 0.44% | 0.033% |
| pyautofit | fixed | 3 | 54.6–56.0% | 0.92–0.96% | 0.41–0.43% | 0.007–0.014% |
| pyautofit | correlated | 3 | 59.0–60.7% | 0.98–1.01% | 0.40–0.41% | 0.010–0.019% |
| pyautofit | random | 1 | 72.6% | 1.44% | 0.39% | 0.023% |

## Reading the estimates

Worker occupancy is the sum of elapsed per-proposal service times divided by the capacity of two workers over the observed map interval. It includes time a worker might be descheduled during service. The map occupies a small fraction of the total fit, so even low occupancy can coexist with little wall time to recover.

For each batch, the replay measures wall time from the common submission timestamp to collection of the ordered results. With two workers and indivisible proposals, the earliest possible completion is bounded below by the longer of the slowest individual service time and half the sum of all service times. Subtracting that floor from the map interval deliberately lets dispatch, queue gaps and collection overhead vanish. The resulting bound is optimistic and can exceed the gain physically attainable by chunk scheduling. Summation uses disjoint map intervals and keeps parent work, proposal order and the complete-batch adaptation boundary fixed.

The last column compares two zero-overhead queue simulations. Each assigns the next contiguous chunk to the earliest available worker. One uses the native CPython chunk size of 13, the other uses one proposal per chunk. Each simulation reuses the same recorded service intervals and assumes they are independent of assignment. The predicted reductions span 0.003–0.033% of full-fit wall. Actual fine-grained dispatch would incur overhead. The records provide no measured speedup for either a changed scheduler or asynchronous adaptation.

## Inputs and verification

The manifest selects all 14 included two-worker traced fits. All 356 logical batches and 35,600 proposal IDs reconciled against the native likelihood counts. The two original compressed examples remain in the baseline results. The other 12 original traces are included in this directory so the full replay runs from a clean checkout. Every input is checked against its compressed SHA-256 in the pinned manifest. The replay also checks timestamp order, nonoverlap, one result per proposal, assignment of contiguous native chunks to individual workers and the two-worker lower bound. [Baseline manifest and controls](../../results/analytic_gaussian/nautilus/pilot_runs.json) · [Per-fit replay including raw nanosecond totals](result.json).

Run from the producer root with Python 3.10 or later.

```sh
python3 experiments/nautilus_worker_headroom/replay.py
python3 experiments/nautilus_worker_headroom/replay.py --examples-only
```

An optional `--archive PATH` verifies original run-ID directories against the same manifest. The replay starts no workers or samplers. The conclusion applies to the recorded cheap two-worker fits on the shared WSL host. An expensive or more variable target requires its own map share before extrapolation. The phase 0b dimension and accuracy work remains open. [Canonical profiling producer task](https://github.com/PyAutoLabs/PyAutoPulse/blob/main/tasks/autofit_profiling_bootstrap.md).
134 changes: 134 additions & 0 deletions experiments/nautilus_worker_headroom/replay.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
"""Replay two-worker phase 0a batches using their recorded service times."""

import argparse
import gzip
import hashlib
import json
import math
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
HERE = Path(__file__).resolve().parent
BASELINE = ROOT / "results" / "analytic_gaussian" / "nautilus"
MANIFEST_SHA256 = "7370d4a1a86d216e7c100c1b1f601ec329230bb84a5821ae451870dfbc04ec60"
sys.path.insert(0, str(ROOT / "scripts" / "misc"))

from profiling.nautilus_trace import reconcile


def greedy_makespan(durations, chunk):
"""Assign the next contiguous chunk to the first of two available workers."""
free = [0, 0]
for i in range(0, len(durations), chunk):
worker = 0 if free[0] <= free[1] else 1
free[worker] += sum(durations[i : i + chunk])
return max(free)


def replay_batch(events):
events = sorted(events, key=lambda e: e["id"][1])
submits = {e["submit_ns"] for e in events}
collects = {e["collect_ns"] for e in events}
if len(submits) != 1 or len(collects) != 1 or len({e["pid"] for e in events}) != 2:
raise ValueError("Expected one pooled map with two observed workers")
# CPython Pool.map_async defaults to ceil(n / (4 * workers)).
chunk = math.ceil(len(events) / 8)
for i in range(0, len(events), chunk):
if len({e["pid"] for e in events[i : i + chunk]}) != 1:
raise ValueError("Observed assignments split a native-sized chunk")
durations = [e["finish_ns"] - e["start_ns"] for e in events]
window = max(collects) - min(submits)
span = max(e["finish_ns"] for e in events) - min(e["start_ns"] for e in events)
floor = max(max(durations), (sum(durations) + 1) // 2)
native = greedy_makespan(durations, chunk)
single = greedy_makespan(durations, 1)
if not (floor <= span <= window and floor <= min(native, single)):
raise ValueError("Impossible two-worker schedule")
return dict(
map_ns=window,
service_ns=sum(durations),
floor_ns=floor,
edge_ns=window - span,
native_model_ns=native,
single_model_ns=single,
)


def replay(record, compressed):
result, case = record["result"], record["case"]
sha = hashlib.sha256(compressed).hexdigest()
if sha != result["timeline"]["sha256"]:
raise ValueError(f"Wrong timeline for {case['id']}")
trace = json.loads(gzip.decompress(compressed))
batches = trace["batches"]
by_batch = reconcile(trace["events"], batches)
ordered = sorted(batches, key=lambda b: b["start_ns"])
if len(by_batch) != len(batches) or any(
a["finish_ns"] > b["start_ns"] for a, b in zip(ordered, ordered[1:])
):
raise ValueError("Missing, duplicate or overlapping batch windows")
if len(trace["events"]) != result["n_like"]:
raise ValueError("Proposal count disagrees with native likelihood count")
windows = [replay_batch(by_batch[b["id"]]) for b in ordered]
totals = {key: sum(batch[key] for batch in windows) for key in windows[0]}
wall_ns = result["wall_s"] * 1e9
if totals["map_ns"] > wall_ns:
raise ValueError("Map windows exceed full fit")
return {
"id": case["id"],
"adapter": case["adapter"],
"cost": case["cost_profile"],
"seed": case["seed"],
"native_update": result["resolved_constructor"]["n_update"],
"source_sha256": sha,
"fit_wall_s": result["wall_s"],
"batches": len(windows),
"proposals": len(trace["events"]),
**totals,
"observed_occupancy_pct": 50 * totals["service_ns"] / totals["map_ns"],
"all_map_pct_fit": 100 * totals["map_ns"] / wall_ns,
"scheduling_ceiling_pct_fit": 100 * (totals["map_ns"] - totals["floor_ns"]) / wall_ns,
"single_vs_native_model_pct_fit": 100
* (totals["native_model_ns"] - totals["single_model_ns"])
/ wall_ns,
}


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--archive", type=Path, help="read original run-ID directories")
parser.add_argument(
"--examples-only", action="store_true", help="replay the two original public examples"
)
args = parser.parse_args()
raw = (BASELINE / "pilot_runs.json").read_bytes()
if hashlib.sha256(raw).hexdigest() != MANIFEST_SHA256:
raise ValueError("Phase 0a manifest changed")
examples = {
hashlib.sha256(p.read_bytes()).hexdigest(): p for p in BASELINE.glob("*-timeline.json.gz")
}
rows = []
for record in json.loads(raw)["runs"]:
case = record["case"]
if not (
case.get("included_in_analysis") and case["workers"] == 2 and case["trace"] == "on"
):
continue
if case["status"] != "success":
raise ValueError(f"Incomplete selected case: {case['id']}")
path = examples.get(record["result"]["timeline"]["sha256"])
if args.examples_only and path is None:
continue
if args.archive:
path = args.archive / case["id"] / "timeline.json.gz"
elif path is None:
path = HERE / "timelines" / (case["id"] + ".json.gz")
rows.append(replay(record, path.read_bytes()))
if len(rows) != (2 if args.examples_only else 14):
raise ValueError("Unexpected selected case count")
print(json.dumps({"manifest_sha256": MANIFEST_SHA256, "runs": rows}, indent=2, allow_nan=False))


if __name__ == "__main__":
main()
Loading
Loading