Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
8ba5078
feat(scheduler): commit completed prefill blocks to the prefix cache …
e-Evolution Oct 1, 2026
b30e72b
feat(settings): expose prefill_progress_commit_blocks
e-Evolution Oct 1, 2026
bf1611b
fix(settings): reject bool for prefill_progress_commit_blocks
e-Evolution Oct 1, 2026
797f7e4
fix(scheduler): defer prefill commit teardown instead of blocking the…
e-Evolution Oct 1, 2026
1cca37e
fix(scheduler): drain deferred teardowns on reap, skip held ids, canc…
e-Evolution Oct 1, 2026
2be1339
fix(scheduler): bound the final store's wait on an in-flight prefill …
e-Evolution Oct 1, 2026
beea871
refactor(scheduler): move the prefill commit executor into its own mo…
e-Evolution Oct 2, 2026
e37bdfc
feat(enforcer): request a prefill park before aborting at hard pressure
e-Evolution Oct 1, 2026
21dc190
feat(scheduler): park a chunked prefill under memory pressure instead…
e-Evolution Oct 1, 2026
3c459e2
fix(engine): spare parked requests only when the caller keeps the mod…
e-Evolution Oct 1, 2026
4fed9d3
fix(scheduler): bound the park hold gate and let a parked head pass w…
e-Evolution Oct 1, 2026
5ed4e22
fix(scheduler): resume parked requests one per window and keep parked…
e-Evolution Oct 1, 2026
96c8c5c
refactor(scheduler): name the resume-poll saturation sentinel and tes…
e-Evolution Oct 2, 2026
289a9d4
fix(scheduler): commit prefill progress for media prompts and log eve…
e-Evolution Oct 2, 2026
7be0291
fix(scheduler): keep shutdown waits on prefill commits inside the tea…
e-Evolution Oct 2, 2026
4ddc6a4
feat(memory): abort one victim instead of all when nothing is parkable
e-Evolution Oct 5, 2026
4b30e60
feat(cache): domain-isolated exact-prefix chains and exact-chain pins
e-Evolution Oct 5, 2026
efd970e
fix(memory): wait for a single victim to drain before choosing another
e-Evolution Oct 5, 2026
c12cf7e
feat(scheduler): pause a decoding row into an exact SSD prefix
e-Evolution Oct 5, 2026
34839e9
feat(scheduler): resume a paused decoding row from its exact prefix
e-Evolution Oct 5, 2026
0f7b00d
fix(scheduler): continue stop, parser and processor state across a de…
e-Evolution Oct 5, 2026
e4fde40
feat(memory): pause a decoding victim at hard pressure before aborting
e-Evolution Oct 5, 2026
28733ee
feat(scheduler): hand a Lightning MTP row off to standard decode befo…
e-Evolution Oct 5, 2026
cbf7f22
feat(scheduler): resume a parked request when its memory need fits
e-Evolution Oct 5, 2026
cd65a34
feat(scheduler): prefill a cached-media prompt's text suffix in the c…
e-Evolution Oct 5, 2026
78082f4
feat(memory): add the memory_scheduling setting and resolve it in the…
e-Evolution Oct 10, 2026
f5ce370
fix(memory): log only the live enforcer's scheduling state and expose it
e-Evolution Oct 7, 2026
1e7e87f
feat(memory): reject never-fits requests and let fits-later requests …
e-Evolution Oct 5, 2026
fe59823
fix(memory): align the never-fits route and in-stream checks
e-Evolution Oct 5, 2026
61eea31
fix(scheduler): key the deferred release to its table and back off th…
e-Evolution Oct 5, 2026
8550d94
fix(server): return named sampling params and read max_tokens by name
e-Evolution Oct 5, 2026
61cd18a
test(scheduler): drive the deferred-admission backoff test with a con…
e-Evolution Oct 6, 2026
2ea07bd
fix(memory): size VLM weights through the adapter for the never-fits …
e-Evolution Oct 6, 2026
ac6b63c
fix(scheduler): report a resumed park's own committed blocks as resum…
e-Evolution Oct 9, 2026
3c362db
fix(scheduler): resume parked requests under the hard watermark witho…
e-Evolution Oct 6, 2026
68e2502
test(memory): pin the physical cap in the resume-thrash enforcer fixture
e-Evolution Oct 8, 2026
1c20aff
fix(memory): spare external-loop prefills and pause before the emerge…
e-Evolution Oct 6, 2026
31a8f63
fix(memory): keep the emergency brake on no-live-victim and make the …
e-Evolution Oct 6, 2026
60c4fcd
fix(scheduler): keep queued requests waiting while memory is schedule…
e-Evolution Oct 6, 2026
eaba0f1
fix(scheduler): run a lone head that fits under the ceiling alone ins…
e-Evolution Oct 6, 2026
cd1fedc
fix(scheduler): keep a lone head that fits alone from failing on a st…
e-Evolution Oct 9, 2026
cbf624f
fix(scheduler): renew a deferred head's eviction budget on a store dr…
e-Evolution Oct 10, 2026
2b83b55
fix(scheduler): keep the progress clock while a park hold is active
e-Evolution Oct 6, 2026
5de0dcb
fix(memory): count the releasable hot cache in the never-fits gate
e-Evolution Oct 8, 2026
f0dfe4e
fix(memory): raise the never-fits line by the hot cache instead of cr…
e-Evolution Oct 8, 2026
9ff0473
fix(scheduler): restart the fixed stall clock when a park hold ends
e-Evolution Oct 8, 2026
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
27 changes: 26 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,28 @@ Drop-in replacement for OpenAI and Anthropic APIs. Supports streaming usage stat
| `POST /v1/systemone` | Typed decisions with decision models (TypeSafe System One) |
| `GET /v1/models` | List available models |
| `POST /tokenize`, `POST /detokenize` | vLLM-compatible tokenizer API (also under `/v1`) |
| `GET /v1/omlx/capacity?model=<id>` | Memory capacity of a loaded model (see below) |

#### Memory capacity

These capacity features plan against a fixed memory budget, so they are part of **memory scheduling**, which is on only when that budget is fixed:

| `memory.memory_scheduling` (env `OMLX_MEMORY_SCHEDULING`) | Effect |
|---|---|
| `auto` (default) | On when the prefill memory guard is on and an explicit ceiling is set (`memory_guard_tier: custom` with `memory_guard_custom_ceiling_gb` > 0, or `--memory-guard-gb`). Off on the `safe` / `balanced` / `aggressive` tiers. |
| `on` | On whatever the tier. It still needs the prefill memory guard; with the guard off it stays off and logs a warning. |
| `off` | Off. Admission is the same as without these features. |

Why an explicit ceiling: waiting for memory and promising what fits alone only make sense when the budget is fixed and memory pressure is expected. On a tier, the ceiling follows the memory other apps use, so a request that fits now may not fit a minute later. At startup, and whenever the mode, the guard, the tier or the ceiling changes, the server logs the resolved state, for example `Memory scheduling: on (explicit ceiling 48.0 GB)` or `Memory scheduling: off (no explicit memory ceiling; ...)`. An explicit mode save from the admin settings logs the state even when it did not change. `GET /admin/api/global-settings` reports the live state as `memory.memory_scheduling_effective` (`{"enabled": true, "reason": "memory_scheduling=on"}`, or `null` when no enforcer runs); the `POST` response carries the same field. `memory.memory_scheduling` is the configured mode.

With memory scheduling on:

- **Never fits.** A request that cannot fit even with nothing else running (model weights + KV for the prompt plus `max_tokens` + the prefill transient, over the memory guard's capacity line) is rejected up front with HTTP 400 and `omlx_code: "context_exceeds_capacity"`. The usual error envelope stays (`message`, `type`, `code`, `estimated_bytes`, `limit_bytes`) and adds `required_bytes`, `capacity_bytes`, `weights_bytes`, `kv_bytes_per_token`, `requested_context_tokens`, `requested_max_tokens`, `max_viable_context_tokens` and `retryable: false`. Compact or shorten the context, or lower `max_tokens`, before retrying.
- **Fits later.** A request that fits alone but not right now is not rejected. It waits at the head of the queue until running requests free memory. With the park feature on and nothing running, it can run alone (solo) instead of being rejected.
- **Stall clock.** A queued request fails after 60 s without progress by any request (a token, a prefill chunk, a drained cache write), not 60 s after it started waiting. While memory is held on purpose, the bound is `scheduler.admission_no_progress_timeout_s` (default 600 s). With the park feature on (`scheduler.memory_pressure_park`), this clock also applies while a parked or paused request runs alone or waits, whatever `memory_scheduling` says.
- **Capacity numbers.** `GET /v1/omlx/capacity?model=<id>&context_tokens=<n>&max_tokens=<m>` (API key like the other `/v1` routes) returns the same numbers for a request of that size plus `free_bytes_now`, without loading the model. An unknown model is a 404 and an unloaded one a 409; `available: false` when no estimate exists. Chat completions also carry an `X-oMLX-Max-Context-Tokens` header: the largest prompt plus `max_tokens` that fits alone.

With memory scheduling off, a request is checked against the current usage and rejected if it does not fit now, a queued request fails 60 s after it started waiting for memory (unless a park hold is active, see above), and there is no header. The capacity endpoint still answers for a loaded model, with `available: false`, `memory_scheduling: "off"` and the reason.

The admin API for settings, models, downloads, quantization, and benchmarks takes the main API key as a Bearer token and also works in headless mode. See [Admin API](docs/admin-api.md).

Expand Down Expand Up @@ -334,9 +356,12 @@ omlx serve --model-dir ~/models
# Choose a memory guard tier at startup
omlx serve --model-dir ~/models --memory-guard safe

# Set a custom memory guard ceiling in GB
# Set a custom memory guard ceiling in GB (also turns memory scheduling on)
omlx serve --model-dir ~/models --memory-guard-gb 48

# Force memory scheduling on or off (default auto)
OMLX_MEMORY_SCHEDULING=on omlx serve --model-dir ~/models

# Enable SSD cache for KV blocks
omlx serve --model-dir ~/models --paged-ssd-cache-dir ~/.omlx/cache

Expand Down
38 changes: 38 additions & 0 deletions docs/TESTING.md

Large diffs are not rendered by default.

49 changes: 48 additions & 1 deletion omlx/admin/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -689,6 +689,7 @@ class GlobalSettingsRequest(BaseModel):
memory_guard_custom_ceiling_gb: float | None = (
None # only used when tier == "custom"
)
memory_scheduling: str | None = None # "auto" / "on" / "off"

# Scheduler settings
max_concurrent_requests: int | None = None
Expand Down Expand Up @@ -4565,7 +4566,27 @@ async def get_global_settings(is_admin: bool = Depends(require_admin)):
await asyncio.to_thread(
find_splash_binary, global_settings.integrations.splash_path
)
return _global_settings_response(global_settings)
response = _global_settings_response(global_settings)
response["memory"]["memory_scheduling_effective"] = _memory_scheduling_effective()
return response


def _memory_scheduling_effective() -> dict[str, Any] | None:
"""The live enforcer's resolved memory scheduling: enabled and why.

``memory.memory_scheduling`` is the configured mode; this is what the
enforcer resolved it to against the guard, tier and ceiling (and pushes
to every scheduler). None when no enforcer runs.
"""
from ..server import _server_state

enforcer = getattr(_server_state, "process_memory_enforcer", None)
if enforcer is None:
return None
return {
"enabled": bool(enforcer.memory_scheduling_enabled),
"reason": str(enforcer.memory_scheduling_reason),
}


@router.get("/api/global-settings/defaults")
Expand Down Expand Up @@ -4683,6 +4704,7 @@ def _global_settings_response(global_settings):
"prefill_memory_guard": global_settings.memory.prefill_memory_guard,
"memory_guard_tier": global_settings.memory.memory_guard_tier,
"memory_guard_custom_ceiling_gb": global_settings.memory.memory_guard_custom_ceiling_gb,
"memory_scheduling": global_settings.memory.memory_scheduling,
},
"scheduler": {
"max_concurrent_requests": global_settings.scheduler.max_concurrent_requests,
Expand Down Expand Up @@ -5120,6 +5142,30 @@ async def update_global_settings(
f"{'enabled' if request.memory_prefill_memory_guard else 'disabled'}"
)

# Apply memory scheduling mode (Live): the enforcer re-resolves it
# against the guard and ceiling and propagates it to every scheduler.
if request.memory_scheduling is not None:
from ..settings import (
VALID_MEMORY_SCHEDULING_MODES,
normalize_memory_scheduling,
)

mode = normalize_memory_scheduling(request.memory_scheduling)
if mode is None:
raise HTTPException(
status_code=400,
detail=[
f"Invalid memory_scheduling: {request.memory_scheduling!r} "
f"(must be one of {', '.join(VALID_MEMORY_SCHEDULING_MODES)})"
],
)
global_settings.memory.memory_scheduling = mode
from ..server import _server_state

if _server_state.process_memory_enforcer is not None:
_server_state.process_memory_enforcer.memory_scheduling = mode
runtime_applied.append("memory_scheduling")

# Apply scheduler settings
if request.max_concurrent_requests is not None:
if (
Expand Down Expand Up @@ -5945,6 +5991,7 @@ async def update_global_settings(
"success": True,
"message": message,
"runtime_applied": runtime_applied,
"memory_scheduling_effective": _memory_scheduling_effective(),
}


Expand Down
22 changes: 22 additions & 0 deletions omlx/cache/paged_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -1298,6 +1298,28 @@ def delete_block_table(self, request_id: str) -> None:
for block_id in table.block_ids:
self.free_block(block_id)

def release_block_table(
self, request_id: str, table: BlockTable | None = None
) -> None:
"""Drop a request's block table without freeing its blocks.

Its references are released for eviction (``release_for_eviction``),
so the blocks stay cached and findable by later prefix lookups, as
after a completed request's store.

With ``table``, only that table instance is released: its refs are
given back, and the request's entry is dropped only while it still
is that table. A newer table the request got since (a re-admission
replaces the entry) keeps its entry and its refs.
"""
with self._lock:
if table is None:
table = self.request_tables.pop(request_id, None)
elif self.request_tables.get(request_id) is table:
del self.request_tables[request_id]
if table:
self.release_for_eviction(table.block_ids)

def add_block_to_table(
self,
table: BlockTable,
Expand Down
59 changes: 56 additions & 3 deletions omlx/cache/paged_ssd_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import time
import uuid
from collections import OrderedDict
from collections.abc import Iterable
from dataclasses import dataclass
from pathlib import Path
from typing import Any
Expand Down Expand Up @@ -1774,6 +1775,11 @@ def __init__(
# promoted into the raw-byte hot cache. They still consume the same
# shared SSD budget as the two main block indexes.
self._gdn_sidecar_index = GDNCheckpointIndex(max_size_bytes)
# Block hashes held by parked requests: size enforcement skips them
# (and their GDN sidecars) so a parked prefix survives until resume.
# Refcounted so overlapping prompts can pin the same block.
self._pinned_hashes: dict[bytes, int] = {}
self._pin_lock = threading.Lock()
self._hot_cache_only = hot_cache_only
self._expected_model_name = expected_model_name
self._expected_num_layers = expected_num_layers
Expand Down Expand Up @@ -4795,6 +4801,38 @@ def _get_effective_max_size(self) -> int:
disk_limit = int(disk_available * self._DISK_SAFE_RATIO)
return min(self._max_size, disk_limit)

def pin_blocks(self, block_hashes: Iterable[bytes]) -> None:
"""Protect blocks (and their GDN sidecars) from size-based eviction."""
with self._pin_lock:
for block_hash in block_hashes:
key = bytes(block_hash)
self._pinned_hashes[key] = self._pinned_hashes.get(key, 0) + 1

def unpin_blocks(self, block_hashes: Iterable[bytes]) -> None:
"""Release one pin per hash taken by :meth:`pin_blocks`."""
with self._pin_lock:
for block_hash in block_hashes:
key = bytes(block_hash)
remaining = self._pinned_hashes.get(key, 0) - 1
if remaining > 0:
self._pinned_hashes[key] = remaining
else:
self._pinned_hashes.pop(key, None)

@property
def pinned_block_count(self) -> int:
with self._pin_lock:
return len(self._pinned_hashes)

def has_pending_writes(self, block_hashes: Iterable[bytes]) -> bool:
"""Whether any block still waits in memory for the background writer."""
with self._pending_write_hashes_lock:
return any(bytes(h) in self._pending_write_hashes for h in block_hashes)

def _pinned_snapshot(self) -> frozenset[bytes]:
with self._pin_lock:
return frozenset(self._pinned_hashes)

def _evict_tracked_until_size(
self,
target_size: int,
Expand All @@ -4809,14 +4847,29 @@ def _evict_tracked_until_size(
avoiding a second, competing budget for GDN history.
"""
evicted: list[tuple[Any, Any]] = []
pinned = self._pinned_snapshot()
# Look past pinned entries so one parked prefix never blocks the walk.
depth = 1 + len(pinned)

def oldest_unpinned(entries: list[Any], hash_attr: str) -> list[Any]:
for entry in entries:
if getattr(entry, hash_attr) not in pinned:
return [entry]
return []

while self._tracked_ssd_size() > target_size:
if max_count is not None and len(evicted) >= max_count:
break

compatible = self._index.get_lru_entries(1)
incompatible = self._incompatible_index.get_lru_entries(1)
sidecars = self._gdn_sidecar_index.get_lru_entries(1)
compatible = oldest_unpinned(
self._index.get_lru_entries(depth), "block_hash"
)
incompatible = oldest_unpinned(
self._incompatible_index.get_lru_entries(depth), "block_hash"
)
sidecars = oldest_unpinned(
self._gdn_sidecar_index.get_lru_entries(depth), "source_block_hash"
)
candidates: list[tuple[float, int, Any, Any]] = []
if compatible:
candidates.append((compatible[0].last_access, 0, self._index, compatible[0]))
Expand Down
Loading
Loading