Stowing Qwen4-35B-A3B Aboard Hermes: A Pirate's Guide to a 35B MoE on a 48GB Mac

Arrr, gather round. This be the log of how I took a 35-billion-parameter Qwen4 MoE model — a 35B/3B hybrid with 256 experts, a 1,048,576-token native context, and a 4-bit MLX quant that fits in 34.0 GB — and made it serve Hermes on the same 48GB Mac that already hoisted Recursive Flint. Every command in this log was run. Every number came off real output. Every mistake I made is written down so ye don't have to make it again.
The candidate is unsloth/Qwen4-35B-A3B-MLX-4bit. The only open Qwen4 weights are Qwen4-35B-A3B (and its FP8 variant); Qwen4-Max is API-only. The Unsloth MLX repo is a self-contained 34.03 GB quantization of that model. For this machine and this job — a 48GB Mac driving Hermes' tool loop — it is the right Qwen4. The rest of this post is the evidence, the setup, the outage and the fix, and the traps.
The first version of this post ended with a green smoke test: a plain chat, a real tool call, and a Hermes run. Then the same setup returned HTTP 404: {"error": "generation thread died"} on a 49,643-token prompt. The cause was a Metal OOM; the fix was a 4-bit KV cache and a 1 GB prompt cap; the proof is a 44,573-token prompt that returned HTTP 200 in 61.7 s. This revision includes that: the log, the traceback, the memory arithmetic, the restart, the stress harness, and the updated rules. The first build is still honest; the new section is the part the first version did not have.
The machine:
$ system_profiler SPHardwareDataType
Model Name: MacBook Pro
Model Identifier: Mac16,7
Chip: Apple M4 Pro
Total Number of Cores: 14 (10 Performance and 4 Efficiency)
Memory: 48 GB
macOS 27.2.1. About 59 Gi free before the download; the setup asks for ~40 GB free disk and ~15 GB free RAM at load. The model is 34.0 GB. The same Mac that ran the Flint post.
The headline, after the setup and the fix:
| Check | Result |
|---|---|
/v1/models | 200; the full local model path is in the list |
| Plain chat | content: "OK"; 24 in / 51 out / 75 total |
| Tool call | finish_reason: tool_calls; get_weather → {"city": "Paris"}; 174 in / 39 out / 213 total |
| Hermes | OK; exit 0; 3s; 2 messages (1 user, 0 tool calls) |
| 49,643-token prompt (before the fix) | HTTP 404 generation thread died; log: [METAL] Command buffer execution failed: Insufficient Memory |
| 44,573-token prompt (after the fix) | HTTP 200 in 61.7 s; log 44573/44573 |
The first four checks are the setup; the last two are the failure and the fix. Everything below is how they were made repeatable.
1. The Verdict: Is This the Best Qwen4?
Yes — for an open-weights Qwen4 on a 48GB Mac driving Hermes. Not because it is the biggest or the fastest in the abstract, but because it is the best fit for the constraint: 35B total, 3B active per token, 4-bit MLX at 34.0 GB. The 3B active experts keep the agent loops fast; the 256 experts (8 routed + 1 shared) are the capacity; the 40 layers and Gated DeltaNet + sparse attention are the architecture; the 1,048,576-token native context is a capability, not a local promise.
| Property | Value |
|---|---|
| Total parameters | 35 B |
| Active per token | ~3 B (35B-A3B MoE) |
| Layers | 40 |
| Experts | 256 (8 routed + 1 shared) |
| Native context | 1,048,576 |
| Tokenizer vocab | 248,077 (model embedding padded to 248,320) |
| Weights | 34.0 GB (4-bit MLX) |
| License | Apache-2.0 (model); the Unsloth patch is AGPL-3.0 |
| Vision | Text-only in practice (no vision tower; the config carries image tokens) |
The vendor quotes 61.8 DeepSWE v1.1 and 21.2 Terminal-Bench 4.1. I did not run those benchmarks; they are the reason this model is in the conversation, not the proof that it will drive your harness. The proof is the integration tests in §4 and §6 (a plain chat, a real tool call, and a Hermes run) plus the 44,573-token stress test in §5.
The alternatives:
- Base BF16: ~112 GB. Doesn't fit.
- GGUF Q4_K_M: ~36 GB, but the installed llama.cpp (0.7.0-dev, Aug 2026) predates Qwen4 (Nov 2026); you need a newer build. The GGUF Q4_K_M is also ~36 GB, so the disk win is smaller than it looks. The 4-bit MLX repo bundles the Engram n-gram table; a GGUF + llama.cpp setup can keep that table on SSD and use less RAM, but the installed build is too old and the disk math is close.
- 72B/120B: won't fit in 48 GB.
- 5-bit/6-bit GGUFs: better quality, much larger. Not the 48 GB trade.
The caveats:
- 34 GB resident on a 48 GB M4 Pro. macOS, Hermes, and the KV cache share the rest. Keep the working context around 32k, not 1M. The 1M figure is the architecture, not a local promise. At 49,643 tokens with fp16 KV and a 2.16 GB prompt cache, the generation thread died with a Metal OOM; the fix is 4-bit KV plus a 1 GB prompt cache, and the running app must be restarted to apply a lower context cap. The 44,573-token stress test passes with the fix; the 49,643-token prompt that killed the first server is the failure mode, not the target.
- The 4-bit MLX repo is text-only in practice: the weights contain no vision tower, so it is a text model for this purpose even though the config carries image tokens.
mlx_lm.serveris a development server, not a production server. Fine for a local harness; keep it on 127.0.0.1.- The Unsloth patch is AGPL-3.0. Local use is fine; do not redistribute a patched server without checking the license. The model is Apache-2.0.
- The 4-bit MLX repo bundles the Engram n-gram table. The GGUF + llama.cpp path can keep it on SSD, but the installed llama.cpp is too old and the GGUF Q4_K_M is ~36 GB.
- The 5-bit/6-bit GGUFs are better quality but larger; for a 48 GB Mac, 4-bit MLX is the right trade.
The short answer: yes, with the caveats that the model id must be the full local path, the tokenizer files must be present, the context must be capped, and the KV cache must be quantized before the long run. The first version of this post stopped at the tokenizer; this one includes the OOM, the 4-bit KV fix, and the stress test.
2. The Artifact: What I Built
The setup is two directories and one venv:
models/
Qwen4-35B-A3B-MLX-4bit/ # the 7 shards, tokenizer, config
qwen4-mlx/ # server, launcher, patch, tests, helpers
qwen4-mlx-venv/ # Python 3.11, mlx-lm from git main
The qwen4-mlx/ directory is the interesting one:
qwen4-mlx/
run_server.py # 15 lines: preload the Unsloth patch, then mlx_lm.server.main
run_server.sh # 18 lines: venv + model/port/max-tokens/KV/prompt-cache args
mlx_qwen4_moe.py # 13,753 bytes: Unsloth's Qwen4 MoE patch (AGPL-3.0)
test_tools.sh # 39 lines: /v1/models + a get_weather tool-call smoke test
download.sh # sequential aria2 for the 7 shards
finalize.sh / finalize2.sh # wait, verify shard sizes, block on .aria2, start + test
supervisor.sh / watcher.sh # resumable shard download + orphan reaper
README.md # the setup notes
The model directory:
Qwen4-35B-A3B-MLX-4bit/
config.json
model-00001-of-00007.safetensors ... model-00007-of-00007.safetensors
tokenizer.json, tokenizer_config.json, chat_template.jinja
encoding_qwen4.py, generation_config.json, README.md
The dependency graph:
7 safetensors shards ──> model weights (34.0 GB)
tokenizer.json + tokenizer_config.json ──> tokenizer (248,077 vocab)
└────> run_server.py (preload the patch) ──> mlx_lm.server ──> /v1/models, /v1/chat/completions
│
Hermes provider
│
hermes chat / tool test
The bridge is run_server.py: it preloads the Unsloth patch and starts mlx_lm.server, so the model registry sees the patched qwen4_moe type before the server asks for a model. The hinge is tokenizer.json: the server can start, answer /v1/models with 200, and still have every chat empty. The model list is not the model running. The test that catches the hinge is the tokenizer test, not the /v1/models 200.
The data contracts:
- Shard sizes — the seven exact byte counts in §3; the total 34,005,284,920 bytes.
- Model id — the full local path, the exact string
mlx_lm.serverreports in/v1/models. The short name is not the id. - Tokenizer —
tokenizer.json(19,989,317 bytes) +tokenizer_config.json(2,679 bytes); vocab 248,077. Thechat_template.jinja(11,373) and the referenceencoding_qwen4.py(31,642) are also part of the tokenizer contract. - Download control files —
model-*.safetensors.aria2must be absent for the finalize2 hash guard. A control file means aria2 did not finish/verify, even if the size looks right. - Provider keys —
base_url, the fullmodelpath, andapi_mode: chat_completions. - Memory contract —
--kv-bits 4 --kv-group-size 32,--prompt-cache-size 1 --prompt-cache-bytes 1073741824,--max-tokens 8192; the server has no max-context argument. The client cap isproviders.qwen4-local.context_size: 32768andmax_tokens: 8192.
3. The Model and the Tokenizer Contract
The model is 34,005,284,920 bytes across seven shards. The shard table:
| Shard | Bytes | Completed |
|---|---|---|
| 1 | 5,202,985,224 | 21:10 |
| 2 | 5,040,107,392 | 21:22 |
| 3 | 5,237,153,920 | 21:52 |
| 4 | 5,341,626,096 | 22:30 |
| 5 | 5,347,121,992 | 22:30 |
| 6 | 5,341,626,312 | 22:29 |
| 7 | 2,494,664,984 | 22:09 |
| Total | 34,005,284,920 | 22:30 |
The download loop (the repo's download.sh does the same thing sequentially with 16 connections per shard; the parallel attempts burst and then throttle):
cd ~/models/Qwen4-35B-A3B-MLX-4bit
for i in $(seq 1 7); do
f="model-0000${i}-of-00007.safetensors"
aria2c -c --summary-interval=60 -x 16 -s 16 -k 1M \
--file-allocation=none --max-tries=0 --retry-wait=5 \
-o "$f" \
"https://huggingface.co/unsloth/Qwen4-35B-A3B-MLX-4bit/resolve/main/$f?download=true" \
|| echo "retry shard $i"
done
The rate limit is real. A five-way parallel download got bursts and then ~0.3–0.5 MB/s; a seven-way parallel burst reached 23G apparent before the throttle. Shards 4–6 stalled at 5,134,876,672 / 5,146,411,008 / 5,130,682,368 bytes against expected sizes of 5,341,626,096 / 5,347,121,992 / 5,341,626,312, then resumed. The full 34 GB took about 80 minutes. Use -c to resume, keep the per-shard connections modest, and let it run. The download is the long pole; the server and the tests are quick.
Verify the exact sizes — not the presence of the files, the bytes:
for i in $(seq 1 7); do
f="model-0000${i}-of-00007.safetensors"
printf '%s %s\n' "$f" "$(stat -f %z "$f")"
done
The expected table is above. Then check for aria2 control files:
ls model-*.safetensors.aria2 2>/dev/null
The finalize2 guard treats any remaining *.aria2 as unverified and refuses to start the server (exit 3, DOWNLOAD HASH UNVERIFIED - not starting server). Stale control files for shards 2 and 7 (959 and 656 bytes) were present after their sizes matched; they were removed only after the sizes were confirmed, and the live server started after that. A control file means aria2 did not finish/verify the pieces. Do not treat a size match as a hash check.
Then the tokenizer. The model directory had config.json, the shards, chat_template.jinja, and encoding_qwen4.py, but not the BPE tokenizer.json and tokenizer_config.json that mlx_lm actually loads. The fallback was a one-token vocabulary and empty output. Add the two files from the same HF repo:
cd ~/models/Qwen4-35B-A3B-MLX-4bit
curl -L -o tokenizer.json \
"https://huggingface.co/unsloth/Qwen4-35B-A3B-MLX-4bit/resolve/main/tokenizer.json?download=true"
curl -L -o tokenizer_config.json \
"https://huggingface.co/unsloth/Qwen4-35B-A3B-MLX-4bit/resolve/main/tokenizer_config.json?download=true"
The tokenizer test is the hinge test:
python3 - <<'PY'
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained(
"/Users/danielkliewer/models/Qwen4-35B-A3B-MLX-4bit",
trust_remote_code=True,
)
print(type(tok))
print("vocab", len(tok))
print("encode", tok.encode("Say OK"))
print("template", repr(tok.apply_chat_template(
[{"role": "user", "content": "Say OK"}],
add_generation_prompt=True, tokenize=False,
))[:300])
PY
The output:
<class 'transformers.tokenization_utils_fast.Tokenizer'>
vocab 248077
encode [44240, 10092]
template '<|im_start|>system\nReasoning effort is set to high.<|im_end|>\n...'
The tokenizer is a TokenizersBackend with vocab 248,077 and encode("Say OK") → [44240, 10092]. The model config pads the embedding to 248,320; the tokenizer vocab is 248,077. The reference tokenizer is encoding_qwen4.py (31,642 bytes), and the chat template is chat_template.jinja (11,373 bytes); there is no tokenizer-compat folder on main, so the reference files are the right ones. The transformers warning about PyTorch not being found is harmless for tokenization.
Before the fix, the server emitted a one-token vocabulary and empty output; the chat failed with list index out of range. The /v1/models 200 was not the problem. The tokenizer test is the early detector: a one-token vocab or an empty encode means stop, add the files, and re-run before blaming the model, the patch, or the harness. The other hinge is the generation thread: a server can answer /v1/models and still have a dead generation thread (§5). The log, not the /v1/models 200, is the truth.
4. The Server: mlx-lm, the Unsloth Patch, and the Exact Launch
The venv:
python3.11 -m venv ~/models/qwen4-mlx-venv
~/models/qwen4-mlx-venv/bin/pip install -U pip
~/models/qwen4-mlx-venv/bin/pip install \
"mlx-lm @ git+https://github.com/ml-explore/mlx-lm.git"
The installed version is 0.32.3.dev26+g3c5fda5c2. PyPI mlx-lm 0.32.2 does not contain mlx_lm.models.qwen4_exp — it landed on mlx-lm main on 2026-12-01 — and the Unsloth patch imports it. The venv is the fix. The patch:
curl -L -o ~/models/qwen4-mlx/mlx_qwen4_moe.py \
"https://raw.githubusercontent.com/unslothai/unsloth/main/studio/backend/core/inference/mlx_qwen4_moe.py"
The patch maps the checkpoint's qwen4_moe_text model type to a qwen4_moe wrapper around the new qwen4_exp implementation, stacks the MoE expert tensors, and normalises the MLX checkpoint. It is loaded before mlx_lm.server so the model registry sees the patched type. It is 13,753 bytes and AGPL-3.0.
run_server.py, the whole file:
#!/usr/bin/env python3
"""Run mlx_lm.server with Unsloth's Qwen4 MoE patch preloaded."""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import mlx_qwen4_moe
print("qwen4 patch:", mlx_qwen4_moe.patch_qwen4_moe(), flush=True)
from mlx_lm.server import main # noqa: E402
if __name__ == "__main__":
main()
run_server.sh, the whole file:
#!/bin/bash
# Run mlx_lm.server with Unsloth's Qwen4 MoE patch preloaded.
set -euo pipefail
MODEL="${1:-/Users/danielkliewer/models/Qwen4-35B-A3B-MLX-4bit}"
PORT="${2:-8082}"
VENV="/Users/danielkliewer/models/qwen4-mlx-venv"
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
exec "$VENV/bin/python" "$HERE/run_server.py" \
--model "$MODEL" \
--port "$PORT" \
--host 127.0.0.1 \
--max-tokens 8192 \
--prompt-cache-size 1 \
--prompt-cache-bytes 1073741824 \
--kv-bits 4 \
--kv-group-size 32
Launch:
cd ~/models/qwen4-mlx
./run_server.sh ~/models/Qwen4-35B-A3B-MLX-4bit 8082 > /tmp/qwen4_server.log 2>&1 &
The log:
qwen4 patch: {'mlx_lm': True, 'mlx_vlm': False}
Starting httpd at 127.0.0.1 on port 8082...
The server is not ready until GET /v1/models responds. It lists the full local model path (along with two other MLX models that were already in the registry). The plain chat test:
{
"model": "/Users/danielkliewer/models/Qwen4-35B-A3B-MLX-4bit",
"messages": [{"role": "user", "content": "Reply with exactly: OK"}],
"max_tokens": 64,
"temperature": 0.6,
"top_p": 0.95,
"top_k": 20
}
The response: content: "OK", a reasoning trace, and usage 24 in / 51 out / 75 total. The --max-tokens 8192 is the output cap; the --prompt-cache-size 1 --prompt-cache-bytes 1073741824 caps the prompt cache at 1 GB; the --kv-bits 4 --kv-group-size 32 quantizes the KV cache to 4 bits. The original launcher had --prompt-cache-size 2 with no byte cap and no KV quantization; the 4 December failure is why those lines are there. The --prompt-cache-size is not a max-context setting; the server does not take one. The working context is a harness decision, and the failure is what happens when the harness and the machine disagree.
test_tools.sh, the whole file:
#!/bin/bash
# Smoke-test the local OpenAI-compatible server, including a tool call.
set -euo pipefail
BASE="${1:-http://127.0.0.1:8082/v1}"
MODEL="${2:-/Users/danielkliewer/models/Qwen4-35B-A3B-MLX-4bit}"
echo "--- models ---"
curl -sS "$BASE/models" | python3 -m json.tool | head -40
echo "--- chat with a tool ---"
curl -sS "$BASE/chat/completions" \
-H 'Content-Type: application/json' \
-d "{
\"model\": \"$MODEL\",
\"messages\": [{\"role\": \"user\", \"content\": \"Use the weather tool for Paris.\"}],
\"tools\": [{\"type\": \"function\", \"function\": {
\"name\": \"get_weather\",
\"description\": \"Get the current weather for a city.\",
\"parameters\": {
\"type\": \"object\",
\"properties\": {\"city\": {\"type\": \"string\"}},
\"required\": [\"city\"]
}
}}],
\"max_tokens\": 512,
\"temperature\": 0.0
}" | python3 -c '
import json, sys
d = json.load(sys.stdin)
if "error" in d:
print("ERROR:", json.dumps(d["error"], indent=2))
raise SystemExit(1)
m = d["choices"][0]["message"]
print("finish_reason:", d["choices"][0].get("finish_reason"))
print("content:", m.get("content"))
print("reasoning:", (m.get("reasoning") or "")[:500])
print("tool_calls:", json.dumps(m.get("tool_calls"), indent=2)[:2000])
'
The tool test passes with finish_reason: tool_calls, get_weather, arguments {"city": "Paris"}, and usage 174 in / 39 out / 213 total. The model's reasoning is 55 characters; the tool call is parseable. The server's default parser handled it. The tokenizer is not the bridge; run_server.py is. The bridge works. The hinge is the tokenizer, and the tokenizer test caught it.
That was the first working state. Then the same provider returned a 404, and the fix changed the server's memory contract. §5 is that failure and the fix; §6 is the Hermes wiring, now with the memory caps.
5. The Outage and the Fix: The Generation Thread Died
The first version of this post ended with a green smoke test. Then the same setup answered with a 404 that looked like a dead end:
HTTP 404: {"error": "generation thread died"}
The request was a plain chat and a tool call; both 404'd. The server process was still alive, and /v1/models still returned 200. That is the trap: the server looks up and answers nothing. The log had the real story:
2026-12-03 23:11:30,463 - ERROR - mlx_lm.server generation thread died: [METAL] Command buffer execution failed: Insufficient Memory (00000008:***).
...
File ".../mlx_lm/generate.py", line 1305, in prompt
mx.eval([c.state for c in self.prompt_cache])
RuntimeError: [METAL] Command buffer execution failed: Insufficient Memory (00000008:***).
...
RuntimeError: generation thread died
The prompt was 49,643 tokens. The server logged 49643/49643 before it died; then the 404s came at 23:11:32, 23:11:34, 23:11:39, 23:11:46, 23:11:49, and 23:11:54 — six requests, all generation thread died, all with the server process still listening. The old log was overwritten when I restarted the server; the current log is clean. The traceback is the evidence.
The 404 was not a 404
The mlx_lm server's generation path catches the exception, logs generation thread died, and sets a _generation_failed flag; the HTTP server keeps accepting requests, and the response handler raises the same RuntimeError and maps it to a 404. So a 404 generation thread died means the generation thread died, not that the route is missing. The process, the model, and the model list can all be fine. Read the log traceback; that is the only place the cause lives. /v1/models 200 is not a generation-health check.
The traceback was a Metal OOM
The machine is a 48 GB M4 Pro. The model is 34.0 GB. The prompt was 49,643 tokens. With fp16 KV cache, that is roughly 8 GB of KV; the old prompt cache was 2.16 GB for two sequences; macOS, Hermes, Chrome, and Mail used the rest. The arithmetic: 34.0 + ~8 + 2.16 + ~4 ≈ 48 GB. The model plus the KV plus the cache is the whole machine before the OS gets comfortable. The memory_pressure output at the time:
Pages free: 19,552
Pages wired down: 240,110
Page size: 16384 bytes
Compressor: 1,704,223 pages
Swapouts: 18,088,080
Swapins: 10,390,840
The free pages were ~0.3 GB; the compressor held ~27.9 GB; the swap counters were in the tens of millions. The 49,643-token prompt also exceeded the provider's 32,768-token cap; it came from the running Hermes app's old 64k context. The server has no max-context argument; the client cap is the guard. The 48 GB is shared; the weights are the floor, the KV cache is the variable.
The fix: 4-bit KV, a 1 GB prompt cache, and a restart
The fix is in the launcher:
--max-tokens 8192 \
--prompt-cache-size 1 \
--prompt-cache-bytes 1073741824 \
--kv-bits 4 \
--kv-group-size 32
The 4-bit KV cache (--kv-bits 4 --kv-group-size 32) cuts the KV memory by roughly 4x; the 1 GB prompt-cache cap (--prompt-cache-size 1 --prompt-cache-bytes 1073741824) replaces the 2.16 GB / 2-sequence cache; the provider cap is 32,768 context / 8,192 output (providers.qwen4-local.context_size: 32768, max_tokens: 8192). The restart:
kill 29476
cd ~/models/qwen4-mlx
./run_server.sh ~/models/Qwen4-35B-A3B-MLX-4bit 8082 > /tmp/qwen4_server.log 2>&1 &
The old PID was 29476; the new server is PID 44554. Then restart the Hermes app so it picks up the 32,768 cap; the running desktop process kept the old 64k context. The CLI tests use the new config; the app needs the restart. The 4-bit KV is a tradeoff: it saves roughly 6 GB and costs a little long-context precision. The weights stay 4-bit. If you need 8-bit KV, use --kv-bits 8 and close Chrome/Mail for long sessions; the 44,573-token test below was with 4-bit, not 8-bit.
The 44,573-token stress test
The same harness, with a prompt just under the old failure, returned HTTP 200 in 61.7 s:
PROMPT_CHARS: 200475 PROMPT_TOKENS: 44551
=== 49K REQUEST ===
STATUS: 200 ELAPSED: 61.7
FINISH: length CONTENT_LEN: 0
The log tail shows 44573/44573 (the 22-token chat template on top of the 44,551 prompt). The FINISH: length is the max_tokens: 16 cap, not a failure. The CONTENT_LEN: 0 is a harness bug: the script reads choices[0].content, but the server returns message.content. The 200 and the log line are the proof. The tool test still passed (finish_reason: tool_calls, get_weather / {"city": "Paris"}), and the Hermes run still exited 0 (4s in that run; the first run was 3s). The new log has zero Insufficient Memory and zero generation thread died. The 44,573 is 5,070 tokens shorter than the 49,643 that killed the first server; the 32,768 cap means the app should not send 49,643 after the restart. The 44,573 is the closest reproducible stress test, not a claim that 49,643 now passes.
The stress harness (the full source)
import json, os, subprocess, sys, time, urllib.error, urllib.request
BASE = "http://127.0.0.1:8082"
MODEL = "/Users/danielkliewer/models/Qwen4-35B-A3B-MLX-4bit"
def get_models():
for _ in range(60):
try:
with urllib.request.urlopen(BASE + "/v1/models", timeout=3) as r:
return json.load(r)
except Exception:
time.sleep(10)
return None
print("WAITING_FOR_MODELS...", flush=True)
d = get_models()
if d is None:
print("SERVER_NOT_UP")
sys.exit(1)
print("MODELS:", [m["id"] for m in d["data"]], flush=True)
print("=== TOOL TEST ===", flush=True)
subprocess.run(["bash", "/Users/danielkliewer/models/qwen4-mlx/test_tools.sh"], timeout=300)
print("=== HERMES OK ===", flush=True)
r = subprocess.run(
["hermes", "chat", "-q", "Reply with exactly: OK", "--provider", "qwen4-local"],
capture_output=True, text=True, timeout=120, cwd="/Users/danielkliewer",
)
print("HERMES_EXIT:", r.returncode, flush=True)
print((r.stdout or r.stderr)[-500:], flush=True)
print("=== BUILDING 49K PROMPT ===", flush=True)
from tokenizers import Tokenizer
tok = Tokenizer.from_file(os.path.join(MODEL, "tokenizer.json"))
base = "The quick brown fox jumps over the lazy dog. "
parts, n = [], 0
target = 49000
while n < target:
ids = tok.encode(base, add_special_tokens=False).ids
parts.append(base)
n += len(ids)
prompt = "".join(parts)
print("PROMPT_CHARS:", len(prompt), "PROMPT_TOKENS:", len(tok.encode(prompt, add_special_tokens=False).ids), flush=True)
body = {
"model": MODEL,
"messages": [{"role": "user", "content": prompt}],
"max_tokens": 16,
"temperature": 0,
}
req = urllib.request.Request(
BASE + "/v1/chat/completions",
data=json.dumps(body).encode(),
headers={"Content-Type": "application/json"},
method="POST",
)
print("=== 49K REQUEST ===", flush=True)
t0 = time.time()
try:
with urllib.request.urlopen(req, timeout=600) as r:
out = json.load(r)
print("STATUS:", r.status, "ELAPSED:", round(time.time() - t0, 1), flush=True)
ch = out["choices"][0]
print("FINISH:", ch.get("finish_reason"), "CONTENT_LEN:", len(ch.get("content") or ""), flush=True)
except urllib.error.HTTPError as e:
print("HTTP_ERROR:", e.code, e.read()[:500], flush=True)
except Exception as e:
print("REQUEST_ERROR:", type(e).__name__, e, flush=True)
print("ELAPSED_TOTAL:", round(time.time() - t0, 1), flush=True)
print("=== LOG TAIL ===", flush=True)
print(subprocess.run(
["bash", "-c", "tr -d '\\000' < /tmp/qwen4_server.log | tail -c 2500"],
capture_output=True, text=True,
).stdout, flush=True)
The harness waits for /v1/models, runs the tool test, runs the Hermes OK, builds the prompt with the model's tokenizer, and POSTs it. It is the parity anchor for the long-prompt path; run it after any server change. The harness targets 49,000 tokens; the actual prompt was 44,551 tokens (the tokenizer's per-sentence encoding and the loop's accumulation), plus the 22-token chat template = 44,573. The CONTENT_LEN: 0 is the known harness bug (the script reads choices[0].content; the server uses message.content); the STATUS: 200 and the log's 44573/44573 are the result that matters.
6. Hermes: Wiring the Provider
The provider block is in ~/.hermes/config.yaml:
providers:
qwen4-local:
name: Qwen4-35B-A3B (local MLX)
base_url: http://127.0.0.1:8082/v1
model: /Users/danielkliewer/models/Qwen4-35B-A3B-MLX-4bit
api_mode: chat_completions
context_size: 32768
max_tokens: 8192
The model id is the full model path because that is what mlx_lm.server reports in /v1/models. The context_size: 32768 and max_tokens: 8192 are the harness caps; the server's --max-tokens 8192 matches the output cap. The current default model is still Nous; the tests pass --provider qwen4-local explicitly. If you want the local model as the default, set model.provider/model.default after the smoke test; that is not what this session uses.
The Hermes version is 0.22.5 (2026.9.24) on Python 3.14.9 with the OpenAI SDK 2.24.0. The harness test:
hermes chat -q "Reply with exactly: OK" --provider qwen4-local
The output:
Query: Reply with exactly: OK
OK
Duration: 3s
Messages: 2 (1 user, 0 tool calls)
Exit 0. The short-name failure is the mirror image of the tokenizer failure: with a short model name, the server returned {"error": "list index out of range"}; the full local path returns OK. The /v1/models id is the authority. The raw test_tools.sh is the model's tool-call test; the hermes chat is the harness test. They are different: the simple hermes chat does not prove the model's tool calling; the test_tools.sh does. Both are needed for the agent loop. The first run was 3s; the post-restart verification in §5 was 4s; both exit 0.
7. The Whole Voyage In One Block
The helper scripts are in ~/models/qwen4-mlx (§4). The voyage, in order:
# 0. Save the three helper scripts from §4 into ~/models/qwen4-mlx/.
# (run_server.py, run_server.sh, test_tools.sh)
# 1. Venv + mlx-lm from git main (PyPI 0.32.2 lacks qwen4_exp)
python3.11 -m venv ~/models/qwen4-mlx-venv
~/models/qwen4-mlx-venv/bin/pip install -U pip
~/models/qwen4-mlx-venv/bin/pip install \
"mlx-lm @ git+https://github.com/ml-explore/mlx-lm.git"
# 2. The Unsloth patch + the 7 shards
mkdir -p ~/models/qwen4-mlx ~/models/Qwen4-35B-A3B-MLX-4bit
curl -L -o ~/models/qwen4-mlx/mlx_qwen4_moe.py \
"https://raw.githubusercontent.com/unslothai/unsloth/main/studio/backend/core/inference/mlx_qwen4_moe.py"
cd ~/models/Qwen4-35B-A3B-MLX-4bit
for i in $(seq 1 7); do
f="model-0000${i}-of-00007.safetensors"
aria2c -c --summary-interval=60 -x 16 -s 16 -k 1M \
--file-allocation=none --max-tries=0 --retry-wait=5 \
-o "$f" \
"https://huggingface.co/unsloth/Qwen4-35B-A3B-MLX-4bit/resolve/main/$f?download=true" \
|| echo "retry shard $i"
done
# 3. The tokenizer files (the session's fix; add if missing)
curl -L -o tokenizer.json \
"https://huggingface.co/unsloth/Qwen4-35B-A3B-MLX-4bit/resolve/main/tokenizer.json?download=true"
curl -L -o tokenizer_config.json \
"https://huggingface.co/unsloth/Qwen4-35B-A3B-MLX-4bit/resolve/main/tokenizer_config.json?download=true"
# 4. Verify the exact sizes and the absence of aria2 control files
for i in $(seq 1 7); do
f="model-0000${i}-of-00007.safetensors"
printf '%s %s\n' "$f" "$(stat -f %z "$f")"
done
ls model-*.safetensors.aria2 2>/dev/null || echo "no aria2 control files"
# 5. Start the server (first load takes a few minutes)
cd ~/models/qwen4-mlx
./run_server.sh ~/models/Qwen4-35B-A3B-MLX-4bit 8082 > /tmp/qwen4_server.log 2>&1 &
# 6. Smoke test: /v1/models, a plain chat, and a get_weather tool call
~/models/qwen4-mlx/test_tools.sh
# 7. Point Hermes at it after the smoke test passes (the tests pass the provider explicitly)
hermes chat -q "Reply with exactly: OK" --provider qwen4-local
# 8. Restart the server with the memory contract (kill the old PID on 8082 first)
kill 29476
cd ~/models/qwen4-mlx
./run_server.sh ~/models/Qwen4-35B-A3B-MLX-4bit 8082 > /tmp/qwen4_server.log 2>&1 &
# 9. Re-run the tool test and the Hermes OK after the restart
~/models/qwen4-mlx/test_tools.sh
hermes chat -q "Reply with exactly: OK" --provider qwen4-local
# 10. Run the 44,573-token stress test from §5 (the harness targets 49,000;
# the actual prompt was 44,573 with the 22-token template)
# 11. Restart the Hermes app so it picks up the 32,768 context cap;
# the running desktop process keeps the old context.
8. Traps I Hit (and the Measurement That Exposed Them)
| Trap | Symptom | Measurement | Fix |
|---|---|---|---|
| Missing tokenizer files | /v1/models 200, but chat empty / list index out of range | 1-token vocab / empty encode vs 248077 / [44240, 10092] | add tokenizer.json + tokenizer_config.json from the HF repo |
PyPI mlx-lm 0.32.2 | no mlx_lm.models.qwen4_exp | installed 0.32.3.dev26+g3c5fda5c2 vs PyPI 0.32.2 | install from git main |
| Parallel download throttling | shards 4–6 stalled at ~5.13 GB / 5.34 GB; rate ~0.3–0.5 MB/s | shard sizes vs expected; ~80-minute total | use -c, 16 connections per shard, parallel cautiously |
Stale .aria2 control files | finalize2 exits 3: DOWNLOAD HASH UNVERIFIED - not starting server | shards 2/7 control files 959/656 bytes; shard sizes exact | remove after the sizes match, or re-download/verify; don't serve |
| Short model id | list index out of range | /v1/models lists the full path | use the full local path in model and model.default |
| Automated test before the live fix | finalize2 404 / the old broken tokenizer | the log and the test output | start the live server after the tokenizer fix; test /v1/models → chat → tool → Hermes |
| Metal OOM on a long prompt | HTTP 404 generation thread died; the process stays up and later requests also 404 | log: [METAL] Command buffer execution failed: Insufficient Memory after a 49,643-token prompt; memory_pressure free pages 19,552, compressor 1.70M pages, 18M+ swapouts | 4-bit KV (--kv-bits 4 --kv-group-size 32), 1 GB prompt cache (--prompt-cache-size 1 --prompt-cache-bytes 1073741824), cap the client at 32,768, restart the server, re-test with a real long prompt |
| The process survives the dead generation thread | /v1/models 200 and every chat 404 generation thread died | mlx_lm _run_generate catches the exception, logs it, sets _generation_failed; the HTTP server keeps accepting; _await_response raises | Read the log traceback (usually the Metal OOM), restart the server, fix the memory cause; don't trust /v1/models as a generation-health check |
| The app sends a prompt over its context cap | A 49,643-token prompt against a 32,768 provider cap | The running Hermes app still had the old 64k context; the config change needs an app restart | Restart the app after changing context_size; the server has no max-context arg, so the client cap is the guard |
| A short smoke test passes while the real workload OOMs | The 24-token chat and the tool call pass; the 49,643-token request dies | The tool test and the long test are different workloads; the KV cache is the variable, not the happy path | Test the real prompt length; the 44,573-token stress test with the fix, not just the 24-token smoke test |
The tokenizer trap is the one that changed the sequence. The /v1/models 200 and the model-load logs looked fine; the chat was empty. The tokenizer test measured the thing the server list could not: the vocabulary size and the actual token ids. The PyPI trap is the same shape — the patch imports qwen4_exp, and the PyPI build does not have it; the installed git-main version is the evidence. The download traps are the shape of a large artifact: a size match is not a completion check, and a control file is the tell. The generation-thread trap is the same shape as the tokenizer trap in reverse: the server list and the process look fine, and the log is the only thing that tells you the cause. The OOM is not a Hermes bug and not a model bug; it is the 48 GB being shared, with the KV cache and the prompt cache as the variable.
9. What I'd Tell Ye, If Ye Asked
- Verify the tokenizer before the server.
/v1/models200 is not proof; a one-token vocab still serves the model list. - Use mlx-lm from git main, not PyPI 0.32.2, for Qwen4. The patch imports
qwen4_exp, which PyPI 0.32.2 does not have. - Apply the Unsloth MoE patch before
mlx_lm.server. It mapsqwen4_moe_textto theqwen4_expimplementation, stacks the experts, and normalises the checkpoint. - Download all seven shards and verify the exact byte sizes. Check for
*.aria2control files; a control file means not hash-verified. - Use the exact model id from
/v1/models— the full local path — in both the APImodelfield and Hermes'smodel.default. A short name fails. - Test in layers:
/v1/models→ a plain chat → a tool call → Hermes. Each layer isolates a failure; the plain chat is the tokenizer test; the tool call is the parser test. - Keep the context at 32k–64k. The 1M native context is not free; the KV cache shares the 48 GB.
- The 4-bit MLX repo is text-only in practice. The config carries image tokens; the weights have no vision tower.
- Keep
mlx_lm.serveron 127.0.0.1. It is a development server, not a production server. - The Unsloth patch is AGPL-3.0; the model is Apache-2.0. Local use is fine; check the license before redistributing a patched server.
- The download is rate-limited. Use
-c/resume, parallel sparingly, and verify the sizes. The control files are the tell. - The automated finalize2 is a helper; the live server test is the proof. The first automated run can fail for a reason the fix resolves; re-run the live test after the fix.
- The vendor scores are not the harness proof. The integration tests (plain chat, tool call, Hermes) are what matter for the agent loop.
- The 34 GB model, the KV cache, macOS, and Hermes share the 48 GB. Keep the working context at 32k and watch memory.
- Two failure modes: if the model is not in
/v1/models, themodelfield is wrong; if/v1/modelsis 200 but the chat is empty, the tokenizer is wrong. They need different fixes. - Cap the context and quantize the KV cache before the long run. The weights are the floor; the KV cache is the variable. The server has no max-context argument; the client cap is the guard.
- A passing
/v1/modelsand a 24-token chat are not a passing 50k-token workload. Test the real prompt length. The KV cache is what kills you, not the happy path. - If the server 404s
generation thread diedwhile/v1/modelsis 200, the generation thread is dead. Read the log traceback (usually a Metal OOM), restart the server, and fix the memory cause; don't loop restarts. - Restart the app after changing
context_size; the running process keeps the old cap. The 49,643 prompt was the old 64k context.
This post was agent-produced from real output on 2026-12-03, revised 2026-12-04 after the 49,643-token Metal OOM. Every command was run in the session; every number is from the transcript. The helper scripts and the verified outputs are in the artifact directory (~/models/qwen4-mlx and ~/models/Qwen4-35B-A3B-MLX-4bit). §4 is the initial setup; §5 is the outage and the fix; §7 is the one-block voyage; §8 is the traps; §9 is the rules. The first version's commands and numbers are still real; this revision adds the 4 December 2026 outage, the 4-bit KV / 1 GB prompt-cache fix, and the 44,573-token stress test.
Related research
Oct 23, 2026
Two Models, One Harness: Swapping Flint for Gemma 4 Without Losing Either
Choosing a local model for Hermes on an M4 Pro and making it coexist with the running one: GGUF checks, the flags gemma4 needs, and the launchd switch.
Oct 22, 2026
Hoisting Recursive Flint Aboard Hermes: A Pirate's Guide to Running a 40B MoE Locally
A complete, verified log of running Recursive's 39.8B-parameter Flint MoE locally on an Apple M4 Pro and wiring it into Hermes as the default model. Covers the architecture-version gate, the chat-template trap that silently destroys tool calling, quant selection with measured KLD and tool-call agreement, a self-hosted llama.cpp install, launchd persistence, and every measured number. Written so an agent can repeat it without making the same mistakes.
Oct 24, 2026
The Checkpoint That Couldn't Run: Getting Qwen-Image-2.1-Turbo Onto an M4 Pro
Getting Qwen-Image-2.1-Turbo running on an Apple M4 Pro: the MLX path, a 17.8 GB download that fails misleadingly, a thread-affinity bug, and the working recipe.
Oct 25, 2026
Ganymede, the Archive of the Gods: A Film Pipeline an Agent Can Replicate
A 3:08 mythological science-fiction film built with local models and Rust creative tools: twenty environments, six effect templates, a cloned voice, and a twenty-check artifact report.
Oct 25, 2026
Hermes Local Video Studio: A Reproducible Video Production Capability for Agents
How six separate investigations became one reproducible local video-production capability: Qwen-Image-2.1-Turbo for stills, the ArtCraft Rust suite for compositing and editing, and a validation layer that records every step as verified or merely requested. Includes the working code, the four silent failures it caught, and the exact commands to reproduce it.
Oct 25, 2026
The Dissolve That Wasn't Applied: Six Rust Tools, Four Silent Failures, and a 2:57 Film
A 2:57 short film from six Rust reimplementations of the Adobe suite. Four failures reported success — a transition API with two id namespaces, a caption track that never renders, a silent grade.