a8nova's picture
nnopt port: YOLO11n-MLX
56fa795 verified
Raw History Blame Contribute Delete
4 kB
"""nnopt port contract v1 entry (vision_detection): YOLO11n on MLX.
sh ./run.sh --image IN.jpg [--image IN2.jpg ...] [--repeat R] --out OUT.json --metrics M.json
"""
import time
T0 = time.perf_counter()
import argparse
import json
import os
import resource
import cv2
import mlx.core as mx
import numpy as np
from yolo_mlx import YOLO11, letterbox, postprocess
def set_interactive_qos():
"""Ask macOS to keep this (GPU-feeding) thread on the performance cores.
MLX encodes every Metal kernel on the calling thread (~2.8 ms CPU per forward here). At the default QoS the
scheduler drifts the thread to slower cores over a few hundred requests and latency climbs from ~5 to ~17 ms;
QOS_CLASS_USER_INTERACTIVE keeps it flat. Callers embedding YOLO11 in their own process can do the same."""
try:
import ctypes
ctypes.CDLL("/usr/lib/libSystem.B.dylib").pthread_set_qos_class_self_np(0x21, 0) # QOS_CLASS_USER_INTERACTIVE
except (OSError, AttributeError):
pass
class KeepCoresAwake:
"""Spin one helper thread (libspin.dylib, see spin.c) while requests run, so the CPU clock that feeds the GPU
does not drop between kernel encodes. Disable with NNOPT_SPIN=0; silently off if the dylib is missing."""
def __init__(self):
self.flag, self.thread = None, None
lib = os.path.join(os.path.dirname(os.path.abspath(__file__)), "libspin.dylib")
if os.environ.get("NNOPT_SPIN", "1") != "0" and os.path.exists(lib):
import ctypes
import threading
self.flag = ctypes.c_int(1)
self.thread = threading.Thread(target=ctypes.CDLL(lib).spin_while, args=(ctypes.byref(self.flag),),
daemon=True)
def __enter__(self):
if self.thread is not None:
self.thread.start()
return self
def __exit__(self, *exc):
if self.thread is not None:
self.flag.value = 0
self.thread.join()
def detect(model, imgs):
"""Decoded BGR images -> per-image detection dicts (letterbox, model, NMS, box mapping)."""
batch = np.stack([letterbox(im) for im in imgs])
pred = model(mx.array(batch))
pred = np.array(pred, copy=False) # syncs the GPU
return [postprocess(pred[i], im.shape) for i, im in enumerate(imgs)]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--image", action="append", required=True)
ap.add_argument("--repeat", type=int, default=1)
ap.add_argument("--out", required=True)
ap.add_argument("--metrics", required=True)
ap.add_argument("--weights", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "yolo11n_fused.npz"))
a = ap.parse_args()
set_interactive_qos()
model = YOLO11(a.weights)
imgs = []
for p in a.image:
im = cv2.imread(p) # BGR, like the reference's cv2 loader
if im is None:
raise SystemExit(f"cannot decode {p}")
imgs.append(im)
with KeepCoresAwake():
# Warm-up: JIT-compiles the Metal kernels and traces mx.compile for this batch shape (part of loading).
blank = [np.full((640, 640, 3), 114, np.uint8)] * len(imgs)
for _ in range(2):
detect(model, blank)
load_ms = (time.perf_counter() - T0) * 1000
mx.reset_peak_memory()
runs, dets = [], None
for _ in range(max(1, a.repeat)):
t = time.perf_counter()
dets = detect(model, imgs)
runs.append({"total_ms": (time.perf_counter() - t) * 1000})
out = dets[0] if len(imgs) == 1 else {"images": dets}
with open(a.out, "w") as f:
json.dump(out, f)
rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / (1024 * 1024) # bytes on macOS
with open(a.metrics, "w") as f:
json.dump({"load_ms": load_ms, "runs": runs, "peak_mem_mb": rss,
"gpu_peak_mem_mb": mx.get_peak_memory() / 2**20}, f)
if __name__ == "__main__":
main()