Skip to content

llama.cpp local LLM server

Last updated: 2026-08-17 Status: Active


Overview

This page documents the local LLM inference setup running on the Apple Silicon (M4) Mac mini (castismac1), intended to serve as the model backend for an internal agent that uses MCP tools to query ClickHouse and other internal services, fronted by a FastAPI server.

Important: this same physical Mac mini also runs another VM workload. See Known Constraint before making memory-related changes.


Final Stack

Component Choice Notes
Inference engine llama.cpp (llama-server) Built from source with Metal support
Model Typhoon2.5-Qwen3-30B-A3B (GGUF, Q4_K_M) MoE — 31B total params, ~3B active per token
Chat template External chat_template.jinja, via --chat-template-file Not the GGUF's embedded template (see below) — that one is broken
Tool calling Native, Hermes-style <tool_call> parsing Grammar-constrained JSON tool calls
Concurrency --parallel 6 + --kv-unified + --cont-batching Shared/pooled KV cache across slots, not statically divided — see Resource / Memory Planning
Context window --ctx-size 40000 (shared pool) Raised incrementally from an original 4096 after testing; see the scaling table below
Persistence launchd (LaunchAgent) Auto-restart on crash, starts on login

History — Why We Moved Away from vllm-metal

The original stack used vllm-metal (a community wrapper around MLX, not mainline vLLM — mainline vLLM has no official macOS build and fails to compile on Apple Silicon due to an AppleClang incompatibility).

Fatal flaw discovered: vllm-metal v0.1.0 silently ignores the tools field in chat completion requests. No error, no tool_call in the response — it just answers as if tools was never sent. Since our agent's entire value depends on tool-calling (querying ClickHouse via MCP), this was a blocker.

Alternatives considered:

Option Verdict
Wait for mlx-lm to add tool-calling server support Too immature/uncertain
Patch vllm-metal ourselves Requires maintaining a permanent fork
Ollama Supports concurrency (OLLAMA_NUM_PARALLEL) and tool calling, but less reliable/consistent tool-call formatting than llama.cpp's grammar-constrained approach, especially for a smaller/less mainstream fine-tune like Typhoon
llama.cpp / llama-server Chosen — native Metal accel, genuine grammar-constrained tool calling, real concurrency support

Second issue found after migrating (important — don't skip this): even on llama-server, tool calling was initially unreliable. Root cause: the GGUF conversion (via ggml.ai's automated "GGUF-my-repo" tool) extracts its embedded chat template using an older method that reads tokenizer_config.json — it doesn't recognize newer standalone chat_template.jinja files, so it silently falls back to a generic template with no tool-call logic. --jinja alone applies that broken embedded template with no error or warning. The fix is --chat-template-file, pointing at the real Hermes-style template pulled directly from the original (non-GGUF) HF repo (scb10x/typhoon2.5-qwen3-30b-a3b). Confirmed fixed — verified with a real request returning a populated tool_calls array and finish_reason: "tool_calls".


Installation

# Prerequisites
sw_vers                # macOS Sonoma+
cmake --version         # install via `brew install cmake` if missing

# Build llama.cpp with Metal
mkdir -p ~/local-llm-llamacpp && cd ~/local-llm-llamacpp
git clone https://github.com/ggml-org/llama.cpp
cd llama.cpp
cmake -B build -DGGML_METAL=ON
cmake --build build --config Release -j

# Confirm build
./build/bin/llama-server --help
# Python venv for model + template downloads (huggingface_hub only — NOT needed for
# llama-server itself, which is a compiled binary and runs independent of any venv)
cd ~/local-llm-llamacpp
python3.12 -m venv venv
source venv/bin/activate
pip install --upgrade pip
pip install huggingface_hub

# Download the model
hf download scb10x/typhoon2.5-qwen3-30b-a3b-gguf --local-dir ./models
ls -lh ./models/

# Download the CORRECT chat template — from the original (non-GGUF) repo, not the GGUF one
mkdir -p ./templates
hf download scb10x/typhoon2.5-qwen3-30b-a3b --include "chat_template.jinja" --local-dir ./templates
cat ./templates/chat_template.jinja | head -30   # should reference tool_call logic

Note: the old vllm-metal stack (~/local-llm-vllm) and its launchd plist were fully removed as part of this migration.


Model Selection

Chosen: scb10x/typhoon2.5-qwen3-30b-a3b-gguf — Q4_K_M quantization, 18.6GB on disk.

Why MoE over a bigger/smaller dense model:

  • 31B total parameters give it much greater knowledge/reasoning capacity than a dense 4B or 8B model.
  • Only ~3B parameters are active per generated token — inference speed tracks closer to a small dense model (~40 tok/s generation observed on M4), not a full dense 30B.
  • Qwen's own benchmarks state Qwen3-30B-A3B outcompetes QwQ-32B (dense) while using ~10x fewer activated parameters — the architecture is specifically designed to punch above its active-compute weight class.

Observed generation performance (M4 mini, this quant): ~40.7 tokens/sec generation, ~60.8 tokens/sec prompt processing.


Resource / Memory Planning

Item Size
Model file (disk) 18.6GB
Model in RAM when loaded ~18.6GB (Metal shares unified memory — no separate VRAM)
KV cache (with --cache-type-k/v q8_0) Scales mainly with --ctx-size; --parallel alone is comparatively cheap once --kv-unified is on (see table below). Quantized KV cache roughly halves memory vs. fp16 default
Realistic total RAM while serving ~20-23GB at smaller ctx-size; more at the current 40000 setting (see below)

Mac mini total RAM: 32GB.

Observed real-world memory pressure during testing: - Idle (before loading model): 63% free - After loading model + one request, original --ctx-size 4096 / --parallel 2 config (before --kv-unified): 15-16% free, with a large jump in Swapouts (confirmed active disk swapping under load) — this was also the config where a real request got rejected (request (2188 tokens) exceeds the available context size (2048 tokens)), since without --kv-unified the 4096 total gets divided evenly per slot (2048 each) - After VM RAM reduction to 8GB (see Known Constraint): 85% free with the model loaded and one request served

--kv-unified — sharing the context pool instead of dividing it: by default, --ctx-size gets split evenly across --parallel slots (ctx-size ÷ parallel per slot, fixed). Passing --kv-unified instead pools the whole --ctx-size budget dynamically across all slots — a long conversation can draw more from the shared pool while a short one uses less, rather than every slot being hard-capped at an equal fixed share regardless of need. Note: --kv-unified only defaults on when --parallel is left at -1 (auto); since this setup pins --parallel to an explicit number for predictable concurrency, --kv-unified has to be passed explicitly too.

Incremental scaling test results (this exact machine, watching memory_pressure and Swapouts at each step before going further):

--parallel --ctx-size --kv-unified Free % (idle) Free % (under full concurrent load) Notes
2 4096 (2048/slot) off 15-16% — Original config; rejected real requests once system prompt + tools exceeded 2048/slot
2 8192 on 29% — Fixed the rejection
4 8192 on 28% — Confirms --parallel alone is cheap — barely moved at the same --ctx-size
4 12000 on 27% —
4 16000 on 26% —
6 32000 on 22-24% 23% Zero new Swapouts under a 6-way concurrent load test, repeated more than once — the cleanest, most repeatable tested result
10 64000 on 17% 17% At/below caution line. Zero new Swapouts under a full 10-way concurrent test
8 52000 on 18% 17% Real Swapouts increase observed under load — first time seen across this whole testing session
8 40000 on 20% 17% Also showed a Swapouts increase under load
6 40000 on 17-20% 17% Current live config. Chosen after stepping back down from 10/64000; most recent load test showed Swapouts flat across back-to-back checks, but this is a thinner/less consistent margin than 6/32000

Real-world usage context: the largest single conversation observed in production use so far was ~6666 tokens — well under even the 16000 setting. The push to 32000+ was headroom for future growth, not a response to an actual observed limit being hit. --parallel 6 / --ctx-size 32000 remains the cleanest, most repeatable tested config (consistently zero swap increase every time it was tested, both before and after stepping up to 10/64000 and back down) — the current 6/40000 config trades some of that consistency for a larger context ceiling. If Swapouts is ever observed climbing on the live service, roll back to 6/32000. Of the two levers, --ctx-size is the bigger memory cost if a rollback is needed — reduce it before reducing --parallel.

Root cause of the tight headroom (independent of the above config choices): a separate VM running on the same physical machine adds significant host-side footprint (VM overhead + disk image caching on top of guest RAM), on top of whatever the LLM's current config reserves — see Known Constraint. Both the LLM's memory and the VM's configured RAM are largely fixed reservations once running — held by the host whether actively busy or idle — rather than something that grows with traffic. The risk of low free% isn't the LLM using more over time (it won't, on its own); it's the other VM's memory needs being independent and not fully controllable from here.


Launch Parameters Reference

Core / required

Flag Value Purpose
-m path to .gguf Model file
--host 0.0.0.0 Listen on all interfaces (needed for other clients on the LAN to reach it)
--port 8001
--chat-template-file path to chat_template.jinja Required for tool calling. Overrides the GGUF's broken embedded template (see History) with the real one, downloaded from the original HF repo. Supersedes plain --jinja — don't use both.
-ngl 99 Offload all layers to Metal GPU

Memory-critical

Flag Value Purpose
--ctx-size 40000 (current) Total context window/KV-cache budget. Raised incrementally from an original 4096, tested up to 64000 and back down — see the scaling table in Resource / Memory Planning before picking a value for a different machine.
--parallel 6 (current) Concurrent request slots; scale up incrementally while watching memory_pressure and Swapouts
--kv-unified (flag) Shares the --ctx-size pool dynamically across slots instead of dividing it evenly and statically. Requires a build that supports it (llama-server --help \| grep kv-unified); only defaults on when --parallel is -1/auto, so must be passed explicitly here since --parallel is pinned
--cache-type-k / --cache-type-v q8_0 Quantized KV cache — roughly halves KV cache memory vs. default fp16, minimal quality loss
--cont-batching (flag) Lets finished requests free their slot immediately

Avoid on this hardware: - --mlock — can cause a hard OOM at launch on a tight-memory system instead of letting macOS manage pressure gracefully. - Forcing --no-mmap off default — mmap's default behavior is a safety net here, not a problem.

Generation / sampling

Flag Value Purpose
--temp 0.4 Lower = more deterministic, more reliable tool-call formatting
./llama.cpp/build/bin/llama-server \
  -m ./models/typhoon2.5-qwen3-30b-a3b-q4_k_m.gguf \
  --chat-template-file ./templates/chat_template.jinja \
  --host 0.0.0.0 \
  --port 8001 \
  -ngl 99 \
  --parallel 6 \
  --ctx-size 40000 \
  --kv-unified \
  --cont-batching \
  --cache-type-k q8_0 \
  --cache-type-v q8_0 \
  --temp 0.4

Incremental scale-up procedure

When increasing --parallel or --ctx-size, step up one increment at a time and check memory_pressure after each — this is exactly how the current config was reached, including stepping up to 10/64000 and back down to the current 6/40000 (see the full table in Resource / Memory Planning): - Watch "System-wide memory free percentage" — treat <15-20% while idle as a warning sign. - Watch Swapouts — a climbing count after load or during requests means active swapping; back off to the previous increment. A flat/unchanged Swapouts count under load (even at low free%) is a better "still okay" signal than free% alone. - Of the two levers, --ctx-size costs more memory than --parallel — if scaling back down, reduce --ctx-size first.


Running as a Persistent Service (launchd)

A ready-to-use plist (com.local.llama-server.plist) is checked into the hotel-iac repo alongside local-ai-setup.sh/.md — copy it directly rather than hand-writing this:

cp com.local.llama-server.plist ~/Library/LaunchAgents/com.local.llama-server.plist
launchctl load ~/Library/LaunchAgents/com.local.llama-server.plist
launchctl start com.local.llama-server

Contents, for reference / manual editing:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.local.llama-server</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Users/<USER>/local-llm-llamacpp/llama.cpp/build/bin/llama-server</string>
        <string>-m</string>
        <string>/Users/<USER>/local-llm-llamacpp/models/typhoon2.5-qwen3-30b-a3b-q4_k_m.gguf</string>
        <string>--chat-template-file</string>
        <string>/Users/<USER>/local-llm-llamacpp/templates/chat_template.jinja</string>
        <string>--host</string>
        <string>0.0.0.0</string>
        <string>--port</string>
        <string>8001</string>
        <string>-ngl</string>
        <string>99</string>
        <string>--parallel</string>
        <string>6</string>
        <string>--ctx-size</string>
        <string>40000</string>
        <string>--kv-unified</string>
        <string>--cont-batching</string>
        <string>--cache-type-k</string>
        <string>q8_0</string>
        <string>--cache-type-v</string>
        <string>q8_0</string>
        <string>--temp</string>
        <string>0.4</string>
    </array>
    <key>WorkingDirectory</key>
    <string>/Users/<USER>/local-llm-llamacpp</string>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/Users/<USER>/local-llm-llamacpp/llama-server.log</string>
    <key>StandardErrorPath</key>
    <string>/Users/<USER>/local-llm-llamacpp/llama-server-error.log</string>
</dict>
</plist>

Verify:

launchctl list | grep llama-server   # "0" in middle column = healthy
tail -f ~/local-llm-llamacpp/llama-server.log

Common commands:

launchctl stop com.local.llama-server
launchctl start com.local.llama-server
launchctl unload ~/Library/LaunchAgents/com.local.llama-server.plist   # full removal
lsof -ti:8001 | xargs kill                                             # force-kill if port stuck

** Before loading this plist:** kill any manually-launched llama-server process holding port 8001 first (lsof -ti:8001 | xargs kill) to avoid a port conflict.

** zsh gotcha:** if pasting multi-step command blocks with # comments directly into an interactive zsh terminal, strip the comments first — unlike bash, zsh doesn't treat # as a comment by default in interactive mode, and will error on it (zsh: command not found: #), breaking the rest of the paste.

** Logs go to stderr, not stdout:** llama-server's actual per-request activity (token counts, timing, errors like context-size rejections) is written to StandardErrorPath (llama-server-error.log), not StandardOutPath (llama-server.log) — the latter stays empty by design under normal operation, that's not a sign anything is broken. Always check the -error.log file for real request activity:

tail -f ~/local-llm-llamacpp/llama-server-error.log
Each request logs a line like n_tokens = 2126 (context length reached in that slot) or, on the confirmed original bug, error: request (2188 tokens) exceeds the available context size (2048 tokens). Useful for debugging config/memory issues, but note every entry only has an internal task id/slot id — no session or caller identity, see below.


Per-Session Token Usage Tracking

llama-server has no concept of "who" is calling it — every /v1/chat/completions response includes a usage object (prompt_tokens/completion_tokens/total_tokens), but with no caller identity attached, and its own log (see above) only ties usage to an internal task/slot ID, not a person or session.

Since FastAPI is the single entry point that actually knows the caller (session ID, user ID, etc.), per-session/per-user token accounting has to be implemented there, not at the llama-server layer. Approach used: a small tracker module (token_usage_tracker.py) that FastAPI calls once per response —

usage = response_json.get("usage", {})
tracker.record(session_id=session_id, usage=usage)

— keeping an in-memory running total per session for fast lookups, plus an append-only token_usage.jsonl log on disk so totals survive a FastAPI restart. Two small endpoints (GET /usage/{session_id}, GET /usage) expose the totals. Not yet integrated into the live FastAPI backend — see Open Items.

For a lighter-weight option (gating access rather than full accounting), llama-server also supports --api-key <key>, requiring an Authorization: Bearer <key> header on every request — not currently enabled (CORS is open to all origins with no API key set, per the startup warning in the log).


Integration with FastAPI + MCP

Architecture:

Frontend/App → FastAPI → llama-server (Typhoon2.5-30B-A3B)
                   │
                   └──→ MCP Server (tool calls) → Core logic / ClickHouse / DB

FastAPI is the single entry point for all clients (web/app). It drives the "agent loop": send user message + MCP tool list to the LLM → if tool_calls is populated in the response, forward the call to the MCP server → feed the result back to the LLM → repeat until a plain-text final answer.

Key implementation detail: since llama-server (unlike vllm-metal) genuinely populates response.choices[0].message.tool_calls — as long as --chat-template-file points at the correct template, not the GGUF's broken embedded one — FastAPI can use the native OpenAI-style tool-calling loop. No manual regex/JSON-parsing workaround needed.

If deploying FastAPI+MCP elsewhere on the network while llama-server stays bare-metal on the Mac mini (recommended — Metal/GPU access is more reliable outside a VM): clients need to reach the Mac's LAN-routable address, not localhost. Verify reachability with a simple curl -v http://<host-ip>:8001/v1/models from wherever FastAPI runs.


Known Constraint: Shared Hardware on This Mac Mini

This is the most important operational note on this page.

The same physical Mac mini running llama-server also runs another VM workload on the same 32GB of unified memory. LLM experimentation here directly competes for memory with whatever else is running on the box. The 15-16% free / active-swapping situation observed during testing was caused by that other VM's large host-side footprint plus the LLM's ~20-23GB, both on the same 32GB machine.

Mitigation applied: the other VM's guest RAM was reduced to free headroom for the LLM. After this change, memory pressure with the model loaded and a request served improved to 85% free.

Recommendation for future work: avoid running heavy LLM experiments on this Mac mini at the same time as other heavy workloads until this resource contention is resolved more permanently — either by moving llama-server to dedicated hardware, or further tuning shared allocation once usage patterns are better understood.


Testing Checklist

  • Basic chat completion (confirmed working, Thai + English)
  • Tool-calling test — confirmed tool_calls populated correctly, but only after fixing the chat template (see History) — --jinja alone was insufficient
  • Memory headroom re-verified after VM RAM reduction to 8GB — 85% free observed with model loaded and a request served
  • Live launchd service confirmed running with --chat-template-file (not --jinja), current config (--parallel 6, --ctx-size 40000, --kv-unified) — verified via llama-server-error.log's load_model line on each restart
  • Concurrency test — confirmed working incrementally at 2, 4, 6, 8, and 10 concurrent requests, including mixed plain-chat + tool-calling requests together, all returning correctly
  • Sustained/incremental load test — memory_pressure + Swapouts checked at every scaling step, both up (2/4096 → 10/64000) and back down (10/64000 → 8/52000 → 8/40000 → 6/40000); see table in Resource / Memory Planning
  • Per-session token usage tracking (token_usage_tracker.py) — written but not yet integrated into the live FastAPI backend
  • Monitor Swapouts over a real multi-day/production period at the current 6/40000 config — this config showed flat Swapouts under its most recent test, but hasn't been observed over sustained real traffic combined with the other VM's independent load; 6/32000 remains the more consistently clean fallback if this drifts

Open Items

  1. Per-session token usage tracking not yet wired into FastAPI — the tracker module exists (records usage from each llama-server response, keyed by session ID, with a durable JSONL log and /usage endpoints) but hasn't been added to the live backend yet.
  2. Watch for Swapouts climbing at the current --parallel 6 / --ctx-size 40000 config, especially if the other VM's own memory usage increases independently. Note: 8/52000 and 8/40000 both showed real Swapouts increases under load during testing (unlike every config at --parallel 6, which stayed clean), so if the current config ever starts showing the same, roll back to --parallel 6 / --ctx-size 32000 — the most consistently clean tested result (see Resource / Memory Planning for the rollback command).
  3. Model upgrade evaluation in progress — comparing the current Typhoon2.5-Qwen3-30B-A3B against newer same-class MoE alternatives (Qwen3.6-35B-A3B as the top candidate, Gemma 4 26B-A4B as backup) for meaningfully better reasoning/coding benchmarks at similar speed. Full comparison and rationale in the separate local-llm-model-comparison-wiki.md doc (same project). Live test of Qwen3.6-35B-A3B on a separate port (8002) queued but not yet run.