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
6 changes: 3 additions & 3 deletions docs/TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,9 @@ Related regression suites are `test_qwen4_qsa_incremental_cache.py`, `test_qwen4

# Qwen4 verify attention row tests

Run `python -m pytest -q tests/test_qwen4_verify_attention_rows.py` to check that row-exact Lightning MTP verify windows through Qwen4 attention give every row the bits of the serial one-row decode step and leave the same KV and QSA indexer state. The tests build one attention layer at the real Flash-Next shapes with synthetic 6-bit weights. Masked-arm windows (past the 2,048-token QSA budget, rank-three positions) cover 2 to 8 rows at 2,060, 16,382 and 24,000 cached tokens and compare each row's FP32 block scores and token mask; a rollback case accepts one draft and decodes on. Dense windows below the budget include rows on both sides of MLX's one-pass/two-pass vector SDPA switch at 1,024 keys. `OMLX_QWEN4_QSA_MASKED_VERIFY=0` restores the multi-row masked path.
Run `python -m pytest -q tests/test_qwen4_verify_attention_rows.py` to check that row-exact Lightning MTP verify windows through Qwen4 attention give every row the bits of the serial one-row decode step and leave the same KV and QSA indexer state. The tests build one attention layer at the real Flash-Next shapes with synthetic 6-bit weights. Masked-arm windows (past the 2,048-token QSA budget, rank-three positions) cover 2 to 8 rows at 2,060, 16,382 and 24,000 cached tokens and compare each row's FP32 block scores and token mask; a rollback case accepts one draft and decodes on. Dense windows below the budget include rows on both sides of MLX's one-pass/two-pass vector SDPA switch at 1,024 keys.

`test_mlx_vlm_qwen4_exp_compat.py::test_qwen4_mtp_one_row_step_is_the_serial_decode_step` checks that a one-row Lightning MTP window (the activation step and depth-0 cycles) runs the serial decode step: equal logits and cache state, no speculative transaction, and a following verify window that rolls back as usual. `OMLX_QWEN4_MTP_ONE_ROW_DECODE=0` keeps the verify forward for those windows.
`test_mlx_vlm_qwen4_exp_compat.py::test_qwen4_mtp_one_row_step_is_the_serial_decode_step` checks that a one-row Lightning MTP window (the activation step and depth-0 cycles) runs the serial decode step: equal logits and cache state, no speculative transaction, and a following verify window that rolls back as usual.

# Prefill memory accounting tests

Expand Down Expand Up @@ -196,7 +196,7 @@ Run `python -m pytest tests/test_oq.py -k TestStreamedCalibration` for streamed

# Fused routed-expert decode tests

Run `python -m pytest -q tests/test_qwen35_moe_routed_decode.py tests/test_qwen35_moe_router.py tests/test_qwen35_moe_gate_up.py` to check the one-token routed-expert kernels. Real `Qwen3_5MoeSparseMoeBlock` instances laid out like Qwen3.8-Flash-Next oQ (quantized routed experts, 8-bit shared expert and shared-expert gate, bf16 router) must match the served body bit for bit, with the shared expert and its gate folded into the two launches: 5-bit (oQ5e) and 4-bit experts at the Flash-Next shape (hidden 2560, intermediate 640, top-k 10), and 5-bit gs32, 6-bit gs128 and 8-bit experts at smaller shapes. A bf16 shared expert stays composed and must match too. Both launches are also run in FP32 against MLX's FP32 mat-vecs (routed and shared gate+up after SwiGLU, the gate row, every routed and shared down row), because BF16 outputs hide one-ulp FP32 differences (a fast-math `exp` in the SwiGLU sigmoid passes most BF16 cases but fails these). The kernels bind a one-expert view of the stacked weights; routing to experts 500+ of 512 checks that the view still reads the stacked buffer, and replacing the expert or shared-expert arrays must rebuild the cached plan. The other cases check that shapes where MLX would pick a different mat-vec partition, 3-bit experts, top-k 8, prefill and verify rows, float16, blocks without the gate+up fusion and a kernel failure all keep the served body. The one-launch router softmax + top-k must return the indices and scores of the softmax and top-k launches for random logits and engineered near-ties (every logit repeated eight times, logits on adjacent bf16 values, two-valued rows), a block whose router rows repeat eight times must route like the served block, and the softmax runs in FP32 against MLX's FP32 softmax (a fast reciprocal or a precise `exp` still routes identically but fails there). The router gemv must return MLX's `x @ W.T` logits bit for bit at 512x2560, 256x2048 and 128x1024, and its FP32 row sums must equal MLX's FP32 gemv on the same values (a `simd_sum` in place of MLX's shuffle-down tree changes only a few BF16 logits but every FP32 sum); shapes where MLX reduces K differently (K >= 16 N, a guarded K tail) keep `nn.Linear`. Where the router has 128 to 4,096 experts, its softmax + top-k run inside the gate+up launch for one to three rows: 512-expert blocks (with a folded or a bf16 shared expert) must still match the served body, and in FP32, with router logits tied in pairs, the launch must return the routing launch's indices and scores and the gate+up rows of the launch fed with them. `tests/test_qwen35_moe_verify_window.py` runs every window size with the folded and with the separate routing launch (`OMLX_QWEN35_MOE_TOPK_FOLD=0`).
Run `python -m pytest -q tests/test_qwen35_moe_routed_decode.py tests/test_qwen35_moe_router.py tests/test_qwen35_moe_gate_up.py` to check the one-token routed-expert kernels. Real `Qwen3_5MoeSparseMoeBlock` instances laid out like Qwen3.8-Flash-Next oQ (quantized routed experts, 8-bit shared expert and shared-expert gate, bf16 router) must match the served body bit for bit, with the shared expert and its gate folded into the two launches: 5-bit (oQ5e) and 4-bit experts at the Flash-Next shape (hidden 2560, intermediate 640, top-k 10), and 5-bit gs32, 6-bit gs128 and 8-bit experts at smaller shapes. A bf16 shared expert stays composed and must match too. Both launches are also run in FP32 against MLX's FP32 mat-vecs (routed and shared gate+up after SwiGLU, the gate row, every routed and shared down row), because BF16 outputs hide one-ulp FP32 differences (a fast-math `exp` in the SwiGLU sigmoid passes most BF16 cases but fails these). The kernels bind a one-expert view of the stacked weights; routing to experts 500+ of 512 checks that the view still reads the stacked buffer, and replacing the expert or shared-expert arrays must rebuild the cached plan. The other cases check that shapes where MLX would pick a different mat-vec partition, 3-bit experts, top-k 8, prefill and verify rows, float16, blocks without the gate+up fusion and a kernel failure all keep the served body. The one-launch router softmax + top-k must return the indices and scores of the softmax and top-k launches for random logits and engineered near-ties (every logit repeated eight times, logits on adjacent bf16 values, two-valued rows), a block whose router rows repeat eight times must route like the served block, and the softmax runs in FP32 against MLX's FP32 softmax (a fast reciprocal or a precise `exp` still routes identically but fails there). The router gemv must return MLX's `x @ W.T` logits bit for bit at 512x2560, 256x2048 and 128x1024, and its FP32 row sums must equal MLX's FP32 gemv on the same values (a `simd_sum` in place of MLX's shuffle-down tree changes only a few BF16 logits but every FP32 sum); shapes where MLX reduces K differently (K >= 16 N, a guarded K tail) keep `nn.Linear`. Where the router has 128 to 4,096 experts, its softmax + top-k run inside the gate+up launch for one to three rows: 512-expert blocks (with a folded or a bf16 shared expert) must still match the served body, and in FP32, with router logits tied in pairs, the launch must return the routing launch's indices and scores and the gate+up rows of the launch fed with them. `tests/test_qwen35_moe_verify_window.py` runs every window size with the folded and with the separate routing launch.

# Qwen3.5 fused verifier norm

Expand Down
11 changes: 2 additions & 9 deletions docs/experimental/MoE_Expert_Offload.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,9 @@ with a resident-fraction field accepting 5% to 95%, including fractional percent
{"moe_expert_offload_enabled": true, "moe_expert_offload_resident_fraction": 0.25}
```

Toggling triggers an engine reload (it is a load-time transform). The env
kill switch `OMLX_MOE_EXPERT_OFFLOAD=0` disables it regardless of settings.
Toggling triggers an engine reload (it is a load-time transform).

Three env vars tune the read path, and none changes what is computed:

| variable | default | effect |
|---|---|---|
| `OMLX_MOE_OFFLOAD_IO_WORKERS` | 12 | threads reading missing experts. `1` or less (or an unparseable value) keeps the serial path and starts no threads |
| `OMLX_MOE_OFFLOAD_IO_BATCH` | `4 x workers` | experts whose reads may be in flight at once — the bound on the host memory the pipeline holds ahead of the slot writes |
| `OMLX_MOE_OFFLOAD_OVERLAP` | 1 | in decode, when a step's reads are slow, keep the GPU busy while they finish: compute the resident routes, keep the GPU clocked for the rest of the read, and dispatch each layer's output as soon as it is built (needs the parallel reader). Steps whose reads arrive within 0.5 ms keep the serial order. `0` keeps the serial order for every step: read, then compute |
Missing experts are read by 12 threads, with at most 48 experts' reads in flight, which bounds the host memory the pipeline holds ahead of the slot writes. In decode, when a step's reads are slow, the GPU stays busy while they finish: it computes the resident routes, stays clocked for the rest of the read, and dispatches each layer's output as soon as it is built. Steps whose reads arrive within 0.5 ms keep the serial order: read, then compute. None of this changes what is computed.

## Performance

Expand Down
19 changes: 7 additions & 12 deletions docs/experimental/qwen35_ane_prefill.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,16 +63,12 @@ prefill. The optimal ANE/GPU balance sits well below the classic ~50%
optimum there, so use the Tune ANE Split utility in the model settings to
measure the split for the specific machine before enabling. If the NAX
metallib is missing at runtime, the suffix quietly falls back to the
classic Metal kernels, and `OMLX_QWEN35_QMM_NAX=0` forces that fallback.
`OMLX_QWEN35_ANE_PREFILL=0` keeps the whole feature off everywhere
regardless of the per-model setting.
classic Metal kernels.

The ANE GDN dispatch runs through the mlx-lm prefill linear patch, so
`OMLX_QWEN35_Q4_LM_LINEAR=0` disables ANE GDN acceleration as well as the
standalone GPU qmm routing. GDN b/a suffix projections follow the same q8
token threshold as that patch: below `OMLX_QWEN35_Q8_LINEAR_MIN_TOKENS`
(default 16384, which covers every fixed ANE shape) q8 b/a use stock MLX,
where the native q8 tile is not profitable.
The ANE GDN dispatch runs through the mlx-lm prefill linear patch. GDN b/a
suffix projections follow the same q8 token threshold as that patch: below
16384 tokens, which covers every fixed ANE shape, q8 b/a use stock MLX, where
the native q8 tile is not profitable.

## Per-model settings

Expand Down Expand Up @@ -111,8 +107,7 @@ bank fits one bank per die on M3 Ultra but cannot host both banks on a
single-die chip such as M3 Max, where the load fails with 0x20004. When a
bank fails to load, oMLX first retries with two near-half banks per
instance and then with progressively smaller split banks before falling
back to per-layer programs; `OMLX_QWEN35_ANE_BANK_MAX_BYTES`
forces an initial per-bank cap for testing, counted on the source weights
back to per-layer programs. The per-bank cap counts the source weights
handed to the bank compiler (about four times the compiled INT8 program
size). An interleaved M3 Ultra A/B measured split banks about 1% faster at
prefill with a slightly shorter eager load, but the monolithic bank was
Expand Down Expand Up @@ -355,7 +350,7 @@ the ANE and GPU GDN portions take about 10.1 ms and 9.95 ms respectively. The
at 54% and 4.5370 s at 55%. Larger 60% banks were slower, and a monolithic
60%/60% bank exceeded the compiler's model-verification or weight-blob limit.

Set `OMLX_ANE_PROFILE=1` when running the benchmark to collect opt-in phase
The `[benchmark-ane-profile]` trace above reports these opt-in phase
timings. In the final paired run, ANE0 and ANE1 were executing requests for
38.81% each of total body time. Request launch delay was only 29-37 us. The
dominant downtime was dependency/input readiness: 25.1 ms before each MLP
Expand Down
1 change: 0 additions & 1 deletion docs/experimental/rdma-links.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ would take the worker's end of the mailbox away from the running rank.

| Variable | Effect |
| --- | --- |
| `OMLX_RDMA_STAGE_LINKS=0` | Never route stage activations over RDMA |
| `OMLX_MCDMA_RPCD_SOCKET` | Control socket of the Mac's daemon (default `/tmp/mcdma-rpcd.sock`) |
| `OMLX_MCDMA_RPC_LIBRARY` | Path to `libmcdma-rpc` |

Expand Down
6 changes: 0 additions & 6 deletions omlx/cluster/control_plane.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import hashlib
import hmac
import logging
import os
import pickle
import secrets
import socket
Expand Down Expand Up @@ -312,13 +311,8 @@ def _connect_direct(self, *, deadline: float, allow_proxy: bool) -> None:
raise TimeoutError(f"rank-control coordinator was unreachable: {last_error}")

def _connect_to_coordinator(self) -> None:
mode = os.environ.get("OMLX_CLUSTER_CONTROL_TRANSPORT", "auto").strip().lower()
proxy_available = should_proxy_control_socket(self.host)
deadline = time.monotonic() + self._connect_timeout
if mode == "system-proxy":
self._connect_via_proxy(deadline=deadline)
return

try:
self._connect_direct(deadline=deadline, allow_proxy=proxy_available)
except OSError as exc:
Expand Down
4 changes: 1 addition & 3 deletions omlx/cluster/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -1045,9 +1045,7 @@ def _tailscale_executable() -> str | None:
discovered = shutil.which("tailscale")
if discovered:
return discovered
candidate = Path(
os.environ.get("OMLX_TAILSCALE_CLI", _MACOS_TAILSCALE_CLI)
).expanduser()
candidate = Path(_MACOS_TAILSCALE_CLI)
if (
sys.platform == "darwin"
and candidate.is_file()
Expand Down
62 changes: 15 additions & 47 deletions omlx/cluster/inference_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@
from .telemetry import install_server_telemetry

_EVENT_PREFIX = "OMLX_CLUSTER_EVENT:"
# Bound for the Metal release in the SIGTERM/SIGINT handler before hard exit.
_SIGNAL_CLEAR_TIMEOUT_SECONDS = 10

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -593,9 +595,7 @@ def interrupt(signum: int, _frame: Any) -> None:
# KeyboardInterrupt path is unchanged for a rank that answers promptly.
try:
signal.signal(signal.SIGALRM, hard_exit)
signal.alarm(
int(os.environ.get("OMLX_CLUSTER_SIGNAL_CLEAR_TIMEOUT", "10") or "10")
)
signal.alarm(_SIGNAL_CLEAR_TIMEOUT_SECONDS)
except Exception:
pass
_release_metal_memory(f"rank received {name}")
Expand Down Expand Up @@ -661,8 +661,6 @@ def _watch_launcher_parent(
marker: RuntimeMarker,
*,
poll_interval: float = 0.2,
watched_marker_path: Any = None,
marker_stale_after: float = 45.0,
get_parent_pid: Any = os.getppid,
wait: Any = time.sleep,
exit_process: Any = os._exit,
Expand All @@ -677,42 +675,22 @@ def _watch_launcher_parent(
of every rank, so a reparented worker cannot make useful collective
progress and must not remain resident on a node.

Two conditions are watched: the parent pid changing (the original check),
and — when ``watched_marker_path`` is configured — a launcher- or
coordinator-maintained lease file going stale for ``marker_stale_after``
seconds, which catches a launcher that is alive but wedged (its ranks
would otherwise wait in a collective forever). ``os._exit`` stays the
last resort: ``on_abort`` fires first so in-flight requests can be
cancelled at a step boundary, and ``release_memory`` unwires the rank's
Metal allocations before the process disappears — ``os._exit`` skips
every finally/atexit handler, and a skipped release strands wired memory
until the Mac is rebooted.
``os._exit`` stays the last resort: ``on_abort`` fires first so in-flight
requests can be cancelled at a step boundary, and ``release_memory``
unwires the rank's Metal allocations before the process disappears -
``os._exit`` skips every finally/atexit handler, and a skipped release
strands wired memory until the Mac is rebooted.
"""

watched = Path(watched_marker_path) if watched_marker_path else None
while True:
wait(poll_interval)
reason = None
if get_parent_pid() != parent_pid:
current_parent = get_parent_pid()
reason = (
f"rank launcher parent changed from {parent_pid} to "
f"{current_parent}; the rank cannot safely continue"
)
elif watched is not None and marker_stale_after > 0:
try:
age = time.time() - watched.stat().st_mtime
except OSError:
age = None
# A lease that never appeared yet is not stale; the launcher may
# still be starting. Once it exists, it must stay fresh.
if age is not None and age > marker_stale_after:
reason = (
f"launcher lease {watched} is stale ({age:.1f}s > "
f"{marker_stale_after:.1f}s); the launcher is wedged"
)
if reason is None:
if get_parent_pid() == parent_pid:
continue
current_parent = get_parent_pid()
reason = (
f"rank launcher parent changed from {parent_pid} to "
f"{current_parent}; the rank cannot safely continue"
)
# Keep the marker as bounded crash evidence. The next activation
# overwrites the deterministic path, and liveness already ignores a
# marker whose owner is dead. Removing it here reduced this exact
Expand Down Expand Up @@ -842,14 +820,12 @@ def on_abort(reason: str) -> None:
plan_hash=marker.payload.get("plan_hash"),
)

abort_grace = float(os.environ.get("OMLX_CLUSTER_PEER_ABORT_GRACE", "5.0") or 0.0)
watchdog = PeerWatchdog(
hosts_by_rank,
deployment_id=deployment_id,
state_dir=state_dir,
on_lost=on_lost,
on_abort=on_abort,
abort_grace=abort_grace,
)
thread = threading.Thread(
target=watchdog.run, name="omlx-cluster-peer-watchdog", daemon=True
Expand All @@ -864,11 +840,6 @@ def _start_launcher_watchdog(
*,
state_dir: str | None = None,
) -> None:
# Optional coordinator/launcher lease file: when configured (and once
# it exists), the watchdog also fires if it goes stale — covering a
# launcher that is alive but wedged, which the parent-pid check alone
# cannot see. Off by default, preserving the original PPID-only watch.
lease = os.environ.get("OMLX_CLUSTER_LAUNCHER_LEASE", "").strip()
deployment_id = str(marker.payload.get("deployment_id") or "")

def on_abort(reason: str) -> None:
Expand All @@ -883,10 +854,7 @@ def on_abort(reason: str) -> None:
thread = threading.Thread(
target=_watch_launcher_parent,
args=(parent_pid, marker),
kwargs={
"watched_marker_path": lease or None,
"on_abort": on_abort,
},
kwargs={"on_abort": on_abort},
name="omlx-cluster-launcher-watchdog",
daemon=True,
)
Expand Down
Loading
Loading