Skip to content
This repository was archived by the owner on Nov 12, 2026. It is now read-only.
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
3 changes: 2 additions & 1 deletion mseries/local-ai/mseries-reply-model.service
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ Environment=OMARCHY_MLX_SYSTEM_PREFIX=%h/.local/share/mlx-omarchy
Environment=PYTHONPATH=%h/.local/share/mlx-omarchy
Environment=VK_DRIVER_FILES=%h/.local/share/mlx-omarchy/vulkan/honeykrisp_icd.aarch64.json
Environment=HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_HUB_DISABLE_TELEMETRY=1
Environment=MLX_OMARCHY_BATCH_WORK=20000
# 120k is the scoreboard value (#664); the system-prompt cache in reply-modeld.py is what cuts the first-token wait.
Environment=MLX_OMARCHY_BATCH_WORK=120000
Environment=MSERIES_REPLY_IDLE=900
Environment=MSERIES_REPLY_RESERVE_GIB=4
ExecStart=%h/.local/share/mlx-omarchy/venv/bin/python %h/.local/libexec/mseries-ai/reply-modeld.py
Expand Down
17 changes: 17 additions & 0 deletions mseries/local-ai/reply-model-compare.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,23 @@ nothing, so `mseries-ai` falls back to the assistant model instead of failing. I
Measured through `mseries-reply draft rust/mseries-reply/fixtures/lunch.json`: 5.8 s for the first draft (3.2 s of it
loading), 1.8 s after.

## Speed-ups (2026-10-28, later)

`reply-modeld.py` now keeps the model state after the fixed system prompt (181 of ~225 prompt tokens) and reuses a copy
for every draft, so only the conversation lines are read each time. Same five threads through the server, Qwen3.5-4B,
warm averages:

| Server setting | First token | Total |
|---|---|---|
| No cache, batch 20k (before) | 1.40 s | 2.75 s |
| No cache, batch 120k | 1.36 s | 2.89 s |
| System-prompt cache, batch 20k | 0.81 s | 2.41 s |
| **System-prompt cache, batch 120k (now)** | **0.81 s** | **2.27 s** |

Totals vary with reply length; the first-token drop is the reliable gain. `mseries-reply draft
rust/mseries-reply/fixtures/lunch.json` went from 1.8 s to 1.4 s warm. Set `MSERIES_REPLY_PREFIX_CACHE=0` to turn the
cache off.

## Re-run

```sh
Expand Down
53 changes: 48 additions & 5 deletions mseries/local-ai/reply-modeld.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
RESERVE_GIB = float(os.environ.get('MSERIES_REPLY_RESERVE_GIB', '4')) # desktop headroom kept free
ADMISSION_GIB = float(os.environ.get('MSERIES_REPLY_ADMISSION_GIB', '3.5')) # weights plus working memory
TIGHT_IDLE_SECONDS = 60
PREFIX_CACHE = os.environ.get('MSERIES_REPLY_PREFIX_CACHE', '1') == '1'
MAX_BODY = 1024 * 1024
MAX_TOKENS = 1400

Expand Down Expand Up @@ -75,6 +76,7 @@ def __init__(self, model, idle_seconds, exit_on_unload=True, revision=None):
self.model = None
self.tokenizer = None
self.load_seconds = None
self.prefix_cache = self.prefix_tokens = None
self.last_used = time.monotonic()
threading.Thread(target=self._idle_watch, daemon=True).start()

Expand All @@ -97,6 +99,7 @@ def _ensure(self):
def _unload(self, why):
import mlx.core as mx
self.model = self.tokenizer = None
self.prefix_cache = self.prefix_tokens = None
gc.collect()
mx.clear_cache()
print(f'reply-modeld: unloaded ({why})', flush=True)
Expand All @@ -117,18 +120,58 @@ def _idle_watch(self):
elif idle > TIGHT_IDLE_SECONDS and available_gib() < RESERVE_GIB:
self._unload('memory is tight')

def _ids(self, messages, **kwargs):
ids = self.tokenizer.apply_chat_template(messages, tokenize=True, **kwargs)
return list(ids['input_ids'] if hasattr(ids, 'keys') else ids)

def _prefix_cache(self, tokens, system, kwargs):
"""The model state after reading the system message, built once and reused while prompts start with it.

Every Smart Reply draft starts with the same fixed instructions (~170 tokens), which were most of the time to
the first token. The shared prefix is where the prompt and a probe (the system message plus a dummy user line)
stop agreeing. Returns (cache copy, prefix length), or (None, 0).
"""
import copy
import mlx.core as mx
from mlx_lm.models.cache import make_prompt_cache
cached = self.prefix_tokens
if not (cached and len(cached) < len(tokens) and tokens[:len(cached)] == cached):
probe = self._ids([system, {'role': 'user', 'content': '.'}], add_generation_prompt=True, **kwargs)
length = 0
# Keep at least one new token for the generation step.
while length < min(len(probe), len(tokens) - 1) and probe[length] == tokens[length]:
length += 1
if length < 16:
return None, 0
cached = tokens[:length]
cache = make_prompt_cache(self.model)
self.model(mx.array(cached)[None], cache=cache)
mx.eval([c.state for c in cache])
self.prefix_cache, self.prefix_tokens = cache, cached
return copy.deepcopy(self.prefix_cache), len(cached)

def chat(self, messages, max_tokens, temperature, template_kwargs):
from mlx_lm import generate
from mlx_lm import stream_generate
from mlx_lm.sample_utils import make_sampler
with self.lock:
self._ensure()
try:
kwargs = {'enable_thinking': False}
kwargs.update({k: v for k, v in template_kwargs.items() if k == 'enable_thinking'})
prompt = self.tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False,
**kwargs)
text = generate(self.model, self.tokenizer, prompt, max_tokens=max_tokens,
sampler=make_sampler(temp=temperature))
tokens = self._ids(messages, add_generation_prompt=True, **kwargs)
started = time.monotonic()
cache, skip = None, 0
if PREFIX_CACHE and messages[0]['role'] == 'system':
cache, skip = self._prefix_cache(tokens, messages[0], kwargs)
first = None
text = ''
for response in stream_generate(self.model, self.tokenizer, tokens[skip:], max_tokens=max_tokens,
sampler=make_sampler(temp=temperature), prompt_cache=cache):
if first is None:
first = time.monotonic() - started
text += response.text
print(f'reply-modeld: first token {first or 0:.2f}s, {len(tokens)} prompt tokens '
f'({skip} from the system-prompt cache)', flush=True)
return text
finally:
self.last_used = time.monotonic()
Expand Down
Loading