Skip to content

perf: reuse prepared chat prompts across validation and generation - #4336

Merged
jundot merged 2 commits into
jundot:mainfrom
ngutech21:reuse-prepared-chat-prompts
Oct 9, 2026
Merged

jundot merged 2 commits into
jundot:mainfrom
ngutech21:reuse-prepared-chat-prompts

Conversation

@ngutech21

Copy link
Copy Markdown
Contributor

Summary

Prepare each full chat prompt once and reuse its rendered text and token IDs across context validation, preflight, thinking detection, and generation.

This covers local BatchedEngine requests through Chat Completions, Anthropic Messages, and Responses, including streaming and non-streaming. Context limits, prefill memory checks, partial prompts, tokenization options, and SpecPrefill boundaries remain supported.

Template defaults are resolved before preparation. Other engine types retain their existing paths. No shared cache, new dependency, or kernel change is introduced.

Validation

Benchmarks and tests were rerun after rebasing.

Setup

  • Before: 57fda05d5ce04f820261b4e4084de49ed2b5b7e9
  • After: 161679fcb7703746d9c84061b2c229c1af2187f3
  • Hardware: Apple M4 Max, 128 GiB RAM, macOS 26.7.1.
  • Model: mlx-community/Qwen3.5-2B-4bit, affine 4-bit, group size 64.
  • Model snapshot: 674aaa7240b91e8012fcad5d791b7dfe5ba90207.
  • Runtime: Python 3.11.15, MLX 0.32.3, mlx-lm 94cdcae13, mlx-vlm 0.7.7 (4f4634b), Transformers 5.17.0, tokenizers 0.23.2.
  • Sampling: temperature 0, top_p 1, top_k 0, seed 7.
  • Concurrency 1; stream interval 1; prefill step size 1024.
  • Thinking, speculative decoding, and SpecPrefill disabled.
  • Warm cases: 512 MiB hot cache, SSD disabled, effective cache block size 4096. Uncached case: prefix caching disabled.

Complete source snapshots ran in separate processes in before/after/after/before order. Each case used a fresh engine/cache, a disjoint kernel warmup, an excluded initial miss, and an exact-input warmup.

There were 12 measured requests per revision per case: 120 total. Normal cache storage remained enabled.

Performance

Median first-token latency, measured from before prompt preparation through the first generated token:

Workload Prompt tokens Cached tokens Output tokens Before After Reduction
Short, warm 289 282 1 23.17 ms 21.42 ms 7.6%
Tool history, warm 4,757 4,750 1 48.86 ms 34.08 ms 30.3%
Long tool history, warm 23,669 23,662 1 138.83 ms 84.63 ms 39.0%
Tool history, 64-token response 4,776 4,769 64 45.34 ms 32.33 ms 28.7%
Tool history, uncached 4,757 0 1 1,107.58 ms 1,103.89 ms 0.3%

These are engine-request timings. HTTP, SSE serialization, network, route normalization, and model loading are excluded.

For the 64-token response, total request time fell from 274.75 to 260.96 ms. Observed decode throughput was 273.85 → 275.60 tokens/s (+0.64%), effectively unchanged.

Memory tradeoffs:

  • The long warm case’s median MLX peak increased from 1,468.65 to 1,491.76 MiB (+1.6%). Other cases changed by less than 0.02%.
  • Sampled peak RSS medians changed between −0.2% and +4.5% across workloads. RSS was sampled every 10 ms; allocator/process variation limits attribution.

All 120 measured requests matched input-token hashes, decoded-output hashes, prompt/output lengths, and cached-token counts. Scheduler admission checks confirmed that the new path supplies prepared token IDs.

This is one model and synthetic workload on one machine. Short-prompt and uncached timing ranges overlap. No general decode-throughput or memory-improvement claim is made.

Tests

On 161679fc:

  • Focused engine, API, tokenization, thinking, and memory-guard tests: 414 passed.
  • Default suite: 16,642 passed, 1,216 skipped, 84 deselected.
  • git diff --check 57fda05d..161679fc: passed.

Checklist

  • I read CONTRIBUTING.md.
  • I understand every change in this PR and can explain it in review.
  • For UI or UX changes, I attached before and after screenshots. (N/A)

ngutech21 and others added 2 commits October 7, 2026 08:32
Render and tokenize local batched chat prompts once per request.
Reuse the prepared input for memory preflight, generation, thinking
detection, and token accounting while preserving other engine paths.

Add regression coverage for all three chat APIs and prompt options.
# Conflicts:
#	omlx/server.py
#	tests/test_server.py

@jundot jundot left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tested this on a real server with a text-only model and a 15K-token tool history. The prompt is now tokenized once per request instead of 3-4 times, the output matches main, and a warm 1-token reply went from 131 ms to 104 ms. The branch had a small import conflict with main, so I merged main into it. LGTM, merging.

@jundot
jundot merged commit e1293f8 into jundot:main Oct 9, 2026
1 check passed
jundot added a commit that referenced this pull request Oct 9, 2026
jason5545 added a commit to jason5545/omlx that referenced this pull request Oct 10, 2026
衝突:scheduler 的 packed prefill 保留 pre_pool_bytes;server 用上游
_merge_chat_template_kwargs 後再套 sub-key enable_thinking 覆寫;
qwen4_exp 保留 float32 QSA 鍵庫、收上游批次 QSA 旗標並拿掉上游已移除的
三個 env 開關;moe_offload 與 QSA 測試兩邊都留。

上游 jundot#4396 移除 env 開關時一併刪掉 import os 與 moe_expert_offload._env_int,
本地開關仍在用:batch_generator、scheduler、process_memory_enforcer 補回
import os,_env_int 移進 deepseek_v4/moe_offload。test_server 的 jundot#4336 新測試
改為預期本地傳入的 request_policy。
abrisene added a commit to abrisene/omlx that referenced this pull request Nov 14, 2026
Upstream now prepares a chat prompt once and reuses it for generation
(jundot#4336), and moved the web UI to apps/omlx-web. Transactional rewrite
replays continue a corrected assistant prefix, so they render their own
partial prompt instead of reusing the original request's prompt and
partial mode. The rewrite-preset test reads the moved chat template.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
abrisene added a commit to abrisene/omlx that referenced this pull request Nov 18, 2026
Upstream now prepares a chat prompt once and reuses it for generation
(jundot#4336), and moved the web UI to apps/omlx-web. Transactional rewrite
replays continue a corrected assistant prefix, so they render their own
partial prompt instead of reusing the original request's prompt and
partial mode. The rewrite-preset test reads the moved chat template.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants