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
42 changes: 42 additions & 0 deletions experiments/nautilus_gpu_feed/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Do CPU workers feeding a single GPU shorten a complete Nautilus fit?

On this RTX 2060 laptop, two CPU feeder threads gave no repeatable whole-fit speedup on either workload. With the 100-point Gaussian profile, the feeder was 14.6% faster than the full-batch GPU control on seed 1 and 7.4% slower on seed 2. With 64 copies of the observations it was 2.6% faster and 11.2% slower, respectively. Neither workload met the registered requirement of at least 5% faster on both seeds and a win over the serial split control. Retain native serial training and the existing execution defaults. [Phase protocol](https://github.com/PyAutoLabs/autofit_profiling/issues/42).

| Likelihood observations | Seed | CPU only | GPU, full batch | GPU, serial half batches | GPU, worker-fed half batches |
|---|---:|---:|---:|---:|---:|
| 100 | 1 | 44.76 s | 70.12 s | 52.16 s | 59.86 s |
| 100 | 2 | 47.88 s | 55.01 s | 47.50 s | 59.07 s |
| 6,400 | 1 | 40.35 s | 46.52 s | 44.16 s | 45.32 s |
| 6,400 | 2 | 48.57 s | 38.93 s | 55.70 s | 43.28 s |

The primary clock includes the complete PyAutoFit `search.fit`, first objective compilation, worker lifecycle, normal output and checkpointing. The receipt also includes elapsed time for the fresh Python process from launch to exit. The CPU baseline uses the same FP64 JAX objective as the GPU arms. The 6,400-point diagnostic repeats the original data 64 times and averages the log likelihood, increasing the work per call while preserving the mathematical target. It is a synthetic cost change on the same model. [All case results and paired comparisons](result.json).

## Where the fit spent its time

Full-width GPU likelihood evaluation took 0.50–0.72 s per complete fit, or 0.78–1.61% of wall time. This includes the prior transform, first compilation, device dispatch and collection through host-visible likelihood values. At 100 observations the median warm logical batch took 3.99–4.01 ms with a serial GPU host and 5.51–6.70 ms with feeders. At 6,400 observations it took 6.76–7.00 ms and 8.07–8.16 ms, respectively. The CPU-only warm batch medians were 0.48 ms at 100 observations and 1.11–1.35 ms at 6,400. Feeding could also affect read-only sampler geometry. The faster whole-fit times in individual pairs cannot be attributed to it from the end-to-end clock alone.

The full-width GPU runs spent 15.6–25.3 s in native neural training. The measurements used one shared WSL laptop and two seeds with reversed run orders. The first fit also built the Matplotlib font cache. Device-wide one-second polling recorded 91–99 MiB at peak across the GPU runs. The kernels were short relative to that sampling interval. Per-batch timings provide the finer measurement. This pilot leaves GPU-heavy observational models, CPU/GPU co-evaluation and multi-GPU execution open.

## Execution and numerical checks

All 16 fits ran sequentially with the same four physical CPU cores available, one numerical-library thread, 200 live points, an update interval of 200, logical batches of 100 and four native networks trained serially. The controller owned all RNG state and waited for the complete logical batch before admitting results. CPU-only and full-width GPU evaluated one vector of 100. Both half-width arms evaluated two ordered vectors of 50. For the feeder, two persistent CPU threads applied the native prior transform to the preselected proposals. They also split read-only neural membership checks on candidate arrays of at least 1,000 points. The controller alone owned the GPU and called the existing PyAutoFit objective. The two sub-batches could be outstanding within one logical batch. The result does not measure speculative proposal generation across adaptive boundaries.

The feeder uses PyAutoFit’s existing `chunk_slices` contract. It repeats the last physical row to maintain a fixed device width and discards padded outputs before admission. Each scored fit used one cached compiled batched objective. All native batches happened to be full in these fits. Separate CPU and RTX 2060 probes exercised lengths 1, 17, 50, 99, 100 and 137 at both widths against the canonical `evaluate_in_chunks` helper and a NumPy reference, including points near the fitted peak. [Existing variable-batch task](https://github.com/PyAutoLabs/PyAutoMind/blob/main/draft/bug/autofit/vmap_jit_recompiles_per_nautilus_batch_length.md) · [Hardware probes](probes.json).

All 119,200 admitted values passed the independent FP64 likelihood audit (absolute tolerance 1e-8, relative tolerance 5e-12). The largest absolute difference was 2.8e-9. All proposal hashes matched within each seed and workload. Paired log evidence agreed within 7.2e-15 and marginal means within 2.4e-12 posterior standard deviations. Native ESS was about 1,301 and 1,381 for seeds 1 and 2. All 16 native completion markers and per-fit likelihood counts reconciled.

A preliminary attempt ended on the first batch because the cache counter was read from the wrapper. The corrected driver reads the compiled callable through `__wrapped__`. All scored cases started in fresh directories. PyAutoFit reported a nonfatal visualization warm-up warning in all arms. Quick updates were disabled and normal fit output completed.

## Reproduction

The measured host used an Intel i9-10885H, one NVIDIA GeForce RTX 2060 Max-Q (6 GiB), WSL2, Python 3.12.10, JAX and jaxlib 0.12.0.1, Nautilus 1.0.5, NumPy 2.2.6, SciPy 1.17.1 and scikit-learn 1.5.1. Make the pinned PyAutoFit and PyAutoNerves checkouts available on `PYTHONPATH` in a CUDA-capable JAX environment. Choose four CPU IDs on distinct physical cores. Use a new output directory. [PyAutoFit revision](https://github.com/PyAutoLabs/PyAutoFit/tree/911fe05e1c6b570df51789f0ab5b2cbf54c1f43a) · [PyAutoNerves revision](https://github.com/PyAutoLabs/PyAutoNerves/tree/7f3055b7f3d1967f372bdb41ee732135bca0e68d).

```sh
export JAX_ENABLE_X64=true XLA_PYTHON_CLIENT_PREALLOCATE=false JAX_ENABLE_COMPILATION_CACHE=false
JAX_PLATFORMS=cpu python experiments/nautilus_gpu_feed/probe.py cpu-probe.json
JAX_PLATFORMS=cuda python experiments/nautilus_gpu_feed/probe.py cuda-probe.json
taskset -c 0,2,4,6 python experiments/nautilus_gpu_feed/pilot.py /path/to/fresh-output
python experiments/nautilus_gpu_feed/compare.py /path/to/fresh-output
```

The supervisor enforces one platform per process, retains the case logs and emits device names, software version, CPU time, sampled device usage, model counts, posterior summaries and fit times. This local phase uses the [canonical profiling producer task](https://github.com/PyAutoLabs/PyAutoPulse/blob/main/tasks/autofit_profiling_bootstrap.md).
102 changes: 102 additions & 0 deletions experiments/nautilus_gpu_feed/compare.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
"""Audit all admitted likelihoods against NumPy and compare full-fit timings by seed."""

import argparse
import hashlib
import json
from pathlib import Path

import numpy as np


def audit_draws(raw, row, x, data, noise):
case = raw / f"r{row['repeats']}-s{row['seed']}-{row['arm']}"
with np.load(case / "draws.npz") as saved:
points = saved["points"]
values = saved["log_l"]
assert points.shape == (row["calls"], 3) and len(values) == row["calls"]
assert hashlib.sha256(points.tobytes()).hexdigest() == row["proposal_sha256"]
bounds = {"centre": 100, "normalization": 50, "sigma": 50}
physical = dict(
zip(row["names"], (points * np.array([bounds[n] for n in row["names"]])).T, strict=True)
)
sigma = physical["sigma"][:, None]
prediction = (
physical["normalization"][:, None]
/ (sigma * np.sqrt(2 * np.pi))
* np.exp(-0.5 * ((x - physical["centre"][:, None]) / sigma) ** 2)
)
expected = -0.5 * np.square((data - prediction) / noise).sum(axis=1)
np.testing.assert_allclose(values, expected, atol=1e-8, rtol=5e-12)
info = json.loads(next(case.rglob("samples_info.json")).read_text())
assert row["logz"] == info["log_evidence"] and row["calls"] == info["total_samples"]
assert row["native"] == {"n_live": 200, "n_update": 200, "n_networks": 4, "n_batch": 100}
assert row["ess"] >= 500 and len(list(case.rglob(".completed"))) == 1
assert (
row["objective_cache_sizes"] == [1]
and row["device_chunks"] * row["width"] == row["calls"] + row["padding"]
)
if row["arm"] == "feed":
assert row["membership_jobs"] > 0 and row["wait_for_prepare_s"] > 0
return float(np.max(np.abs(expected - values)))


def compare(raw):
runs = json.loads((raw / "runs.json").read_text())
groups = {(row["repeats"], row["seed"], row["arm"]): row for row in runs}
if len(runs) != 16 or len(groups) != 16:
raise ValueError("Expected four distinct arms per seed and data size")
x = np.arange(100)
noise = 0.01
data = 25 / (10 * np.sqrt(2 * np.pi)) * np.exp(
-0.5 * ((x - 50) / 10) ** 2
) + np.random.RandomState(1).normal(0, noise, 100)
for row in runs:
row["max_abs_numpy_error"] = audit_draws(raw, row, x, data, noise)
pairs = []
for repeats in (1, 64):
for seed in (1, 2):
rows = {arm: groups[repeats, seed, arm] for arm in ("cpu", "gpu", "split", "feed")}
gpu = rows["gpu"]
feed = rows["feed"]
flags = {}
for arm, row in rows.items():
flags[arm] = {
"trajectory_equal": row["proposal_sha256"] == gpu["proposal_sha256"],
"logz_delta": row["logz"] - gpu["logz"],
"max_mean_shift_sd": float(
np.max(np.abs(np.array(row["mean"]) - gpu["mean"]) / gpu["std"])
),
"ess_relative_delta": row["ess"] / gpu["ess"] - 1,
}
parity = all(
abs(f["logz_delta"]) <= 0.1
and f["max_mean_shift_sd"] <= 0.1
and abs(f["ess_relative_delta"]) <= 0.1
for f in flags.values()
)
saved = {
arm: 100 * (1 - feed["fit_wall_s"] / rows[arm]["fit_wall_s"])
for arm in ("cpu", "gpu", "split")
}
pairs.append(
dict(
repeats=repeats,
seed=seed,
parity=flags,
parity_pass=parity,
feed_saving_pct=saved,
advances=bool(parity and saved["gpu"] >= 5 and saved["split"] > 0),
)
)
return dict(
runs=runs,
pairs=pairs,
advance={str(r): all(p["advances"] for p in pairs if p["repeats"] == r) for r in (1, 64)},
)


if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("raw", type=Path)
args = parser.parse_args()
print(json.dumps(compare(args.raw), indent=2, allow_nan=False))
114 changes: 114 additions & 0 deletions experiments/nautilus_gpu_feed/pilot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
"""Run the local four-arm comparison sequentially in fresh processes."""

import argparse
import json
import os
import shutil
import statistics
import subprocess
import sys
import threading
import time
from pathlib import Path

HERE = Path(__file__).resolve().parent


def monitor_gpu(stream, samples):
for line in stream:
fields = line.strip().split(",")
if len(fields) == 2 and all(f.strip().isdigit() for f in fields):
samples.append((time.time(), *map(int, fields)))


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("directory", type=Path)
args = parser.parse_args()
raw = args.directory.resolve()
raw.mkdir(parents=True, exist_ok=False)
cores = os.sched_getaffinity(0)
topology = Path("/sys/devices/system/cpu")
if (
len(cores) != 4
or len({(topology / f"cpu{c}/topology/thread_siblings_list").read_text() for c in cores})
!= 4
):
parser.error("Pin the pilot to four different physical cores with taskset")
order = ("gpu", "feed", "split", "cpu")
runs = []
for seed in (1, 2):
for repeats in (1, 64):
for arm in order if (seed == 1) == (repeats == 1) else order[::-1]:
name = f"r{repeats}-s{seed}-{arm}"
folder = raw / name
env = {
**os.environ,
"JAX_PLATFORMS": "cpu" if arm == "cpu" else "cuda",
"JAX_ENABLE_X64": "true",
"XLA_PYTHON_CLIENT_PREALLOCATE": "false",
"JAX_ENABLE_COMPILATION_CACHE": "false",
"OPENBLAS_NUM_THREADS": "1",
"MKL_NUM_THREADS": "1",
"OMP_NUM_THREADS": "1",
}
samples = []
monitor = None
if arm != "cpu":
smi = shutil.which("nvidia-smi") or "/usr/lib/wsl/lib/nvidia-smi"
monitor = subprocess.Popen(
[
smi,
"--query-gpu=utilization.gpu,memory.used",
"--format=csv,noheader,nounits",
"-l",
"1",
],
stdout=subprocess.PIPE,
text=True,
)
reader = threading.Thread(target=monitor_gpu, args=(monitor.stdout, samples))
reader.start()
try:
tic = time.perf_counter()
with (raw / (name + ".log")).open("w") as log:
subprocess.run(
[
sys.executable,
str(HERE / "run.py"),
str(folder),
arm,
str(seed),
str(repeats),
],
stdout=log,
stderr=subprocess.STDOUT,
check=True,
timeout=600,
env=env,
)
process_wall = time.perf_counter() - tic
finally:
if monitor is not None:
monitor.terminate()
monitor.wait(timeout=10)
reader.join()
monitor.stdout.close()
row = json.loads((folder / "case.json").read_text())
row["fresh_process_s"] = process_wall
if monitor is not None:
usage = [
(u, m) for t, u, m in samples if row["start_epoch"] <= t <= row["end_epoch"]
]
row["gpu_samples"] = len(usage)
row["device_util_mean_pct"] = (
statistics.mean(u for u, _ in usage) if usage else None
)
row["peak_device_memory_mib"] = max((m for _, m in usage), default=None)
runs.append(row)
(raw / "runs.json").write_text(json.dumps(runs, indent=2, allow_nan=False) + "\n")
print(name, round(row["fit_wall_s"], 2), row["objective_cache_sizes"], flush=True)


if __name__ == "__main__":
main()
63 changes: 63 additions & 0 deletions experiments/nautilus_gpu_feed/probe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
"""Check CPU/GPU likelihoods and tail masking before the timed fits."""

import json
import sys
from pathlib import Path

import jax
import jax.numpy as jnp
import numpy as np
from autofit.non_linear.objective import evaluate_in_chunks
from run import Profile, baseline, prepare


def probe():
x, data, noise = baseline.make_dataset()
rng = np.random.default_rng(4702)
theta = rng.uniform([1, 0.1, 1], [99, 45, 49], size=(137, 3))
theta[:21] = rng.normal([50.034, 25.063, 10.0], [0.04, 0.08, 0.04], size=(21, 3))
expected = np.array(
[
-0.5 * np.sum(((data - baseline.Gaussian(*p).model_data_from(x)) / noise) ** 2)
for p in theta
]
)
rows = []
for repeats in (1, 64):
analysis = Profile(repeats)
for width in (50, 100):
fun = jax.jit(
jax.vmap(
lambda p, analysis=analysis: analysis.log_likelihood_function(
baseline.Gaussian(*p)
)
)
)
for length in (1, 17, 50, 99, 100, 137):
vals = np.asarray(evaluate_in_chunks(fun, theta[:length], width))
np.testing.assert_allclose(vals, expected[:length], rtol=5e-12, atol=1e-8)
host = []
for start in range(0, length, width):
real = theta[start : min(start + width, length)]
padded, _ = prepare(np.asarray, real, width - len(real))
host.extend(np.asarray(fun(padded))[: len(real)])
np.testing.assert_allclose(host, vals, rtol=5e-12, atol=1e-8)
assert fun._cache_size() in (1, 2) # NumPy and explicitly placed JAX inputs
rows.append(
dict(
repeats=repeats,
width=width,
max_abs_error=float(np.max(np.abs(vals - expected))),
lengths=[1, 17, 50, 99, 100, 137],
)
)
return dict(
device=jax.devices()[0].device_kind,
backend=jax.default_backend(),
fp64=jax.config.jax_enable_x64,
checks=rows,
)


if __name__ == "__main__":
Path(sys.argv[1]).write_text(json.dumps(probe(), indent=2) + "\n")
Loading
Loading