#!/usr/bin/env python3 """Rotated fresh-process time-to-first-embedding benchmark.""" from __future__ import annotations import argparse import json import os import resource import statistics import subprocess import sys import time from pathlib import Path APP_RESOURCES = Path("/Applications/oMLX.app/Contents/Resources") APP_SITE_PACKAGES = ( APP_RESOURCES / "Python/framework-mlx-base/lib/python3.11/site-packages" ) for dependency_path in (APP_RESOURCES, APP_SITE_PACKAGES): sys.path.insert(0, str(dependency_path)) def worker(args: argparse.Namespace) -> int: import mlx.core as mx import numpy as np from mlx_lm import load if hasattr(mx, "reset_peak_memory"): mx.reset_peak_memory() started = time.perf_counter() model, tokenizer = load(args.model) token_ids = tokenizer.encode( "Instruct: Retrieve a passage for local file search\n" "Query:Which process owns this localhost port?" ) hidden = model.model(mx.array([token_ids])) if isinstance(hidden, tuple): hidden = hidden[0] vector = hidden[0, -1].astype(mx.float32) vector /= mx.maximum(mx.sqrt(mx.sum(vector * vector)), mx.array(1e-12)) mx.eval(vector) elapsed = time.perf_counter() - started result = { "label": args.label, "model": args.model, "internal_seconds": elapsed, "token_count": len(token_ids), "vector_dimension": int(vector.shape[0]), "vector_norm": float(np.linalg.norm(np.asarray(vector))), "mlx_peak_bytes": ( int(mx.get_peak_memory()) if hasattr(mx, "get_peak_memory") else 0 ), "process_peak_rss": int(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss), } print(json.dumps(result, separators=(",", ":")), flush=True) return 0 def percentile(values: list[float], pct: float) -> float: ordered = sorted(values) rank = (len(ordered) - 1) * pct / 100.0 low = int(rank) high = min(low + 1, len(ordered) - 1) fraction = rank - low return ordered[low] * (1 - fraction) + ordered[high] * fraction def summary(values: list[float]) -> dict: return { "n": len(values), "median": statistics.median(values), "mean": statistics.fmean(values), "min": min(values), "max": max(values), "p95": percentile(values, 95), } def parse_worker_output(stdout: str) -> dict: for line in reversed(stdout.splitlines()): try: return json.loads(line) except json.JSONDecodeError: continue raise RuntimeError(f"worker returned no JSON record: {stdout[-1000:]}") def run_all(args: argparse.Namespace) -> int: models = [] for item in args.models: if "=" not in item: raise ValueError(f"expected label=path, got {item}") label, path = item.split("=", 1) models.append((label, path)) records = [] script = str(Path(__file__).resolve()) for round_index in range(args.rounds): rotation = models[round_index % len(models) :] + models[: round_index % len(models)] for position, (label, model_path) in enumerate(rotation): command = [ args.python, script, "worker", "--label", label, "--model", model_path, ] wall_started = time.perf_counter() completed = subprocess.run(command, text=True, capture_output=True) wall_seconds = time.perf_counter() - wall_started if completed.returncode != 0: raise RuntimeError( f"{label} worker failed: {completed.stderr}\n{completed.stdout}" ) record = parse_worker_output(completed.stdout) record.update( { "round": round_index + 1, "position": position + 1, "wall_seconds": wall_seconds, } ) records.append(record) print( f"round={round_index + 1} position={position + 1} " f"label={label} first={record['internal_seconds']:.3f}s", flush=True, ) summaries = {} for label, _ in models: selected = [record for record in records if record["label"] == label] summaries[label] = { "internal_seconds": summary( [record["internal_seconds"] for record in selected] ), "wall_seconds": summary([record["wall_seconds"] for record in selected]), "mlx_peak_bytes": summary( [float(record["mlx_peak_bytes"]) for record in selected] ), } result = { "method": ( "Fresh model process per observation; rotated format order; warm " "filesystem cache; time includes model load, lazy materialization, " "tokenization, and first embedding." ), "rounds": args.rounds, "records": records, "summaries": summaries, } Path(args.output).write_text(json.dumps(result, indent=2) + "\n") print(json.dumps({"output": args.output, "summaries": summaries}, indent=2)) return 0 def parser() -> argparse.ArgumentParser: root = argparse.ArgumentParser() commands = root.add_subparsers(dest="command", required=True) one = commands.add_parser("worker") one.add_argument("--label", required=True) one.add_argument("--model", required=True) one.set_defaults(func=worker) all_runs = commands.add_parser("all") all_runs.add_argument("--output", required=True) all_runs.add_argument("--rounds", type=int, default=5) all_runs.add_argument("--python", required=True) all_runs.add_argument("--models", nargs="+", required=True) all_runs.set_defaults(func=run_all) return root if __name__ == "__main__": parsed = parser().parse_args() raise SystemExit(parsed.func(parsed))