File size: 6,054 Bytes
ffdd9aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#!/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))