zouyee/dmlx
Sobre
Big models. Small Macs. Zero excuses.
IA e aprendizado de máquinaCrescimento medido de estrelas
- em 24 h
- 0
- em 7 dias
- -1
- em 15 dias
- 0
- em 1 mês
- Coletando histórico
Variações líquidas em períodos sobrepostos, não totais diários. Medições ausentes ficam em branco. Estrelas indicam interesse, não qualidade.
README.md
Originaldmlx
Agent-grade local inference on Apple Silicon.
A Zig inference runtime for Apple Silicon, built for model-specific speculative decoding and memory-bounded local execution.
dmlx runs local language models through a Zig-controlled serving and inference stack backed by Apple MLX, custom Metal kernels, and a separate native path for SSD-streamed MoE models.
Its two flagship paths are:
- Qwen3.8-27B-4bit + MTP — model-specific speculative decoding with GPU-chained drafts, multi-token verification, rollback, and an adaptive draft-depth controller. Image input is supported end to end (CLI
--image, serverimage_urlcontent parts, bf16 vision tower with MRoPE, MTP-compatible). - DeepSeek V4 Flash + native expert streaming — a 284B-parameter MoE checkpoint running within a 48GB unified-memory budget by keeping a bounded expert hot set in RAM and reading cold experts from SSD.
Project status: experimental. The flagship configurations below are benchmarked and exercised regularly. Other registered model architectures are compatibility paths, not equivalent claims of production readiness.
Why dmlx
Model-aware speculative decoding
The Qwen3.8 path does more than call a generic draft model:
- a dedicated MTP head with its own cache
- GPU-chained greedy drafting with one synchronization per round
- one target forward over the proposed block
- transactional commit and rollback of target and drafter state
- online depth selection from observed round cost and conditional acceptance
- shape-routed quantized matmul kernels for verify workloads
Models larger than unified memory
The DeepSeek V4 native path does not try to preload every routed expert. It combines:
- packed expert files with direct
pread - a bounded SMELT hot-expert cache
- asynchronous cold-expert loading
- native Metal kernels for attention and routed MoE execution
On a 48GB Mac, the safe default is NATIVE_SMELT_N=20. Full expert preload would require roughly 147GB and is intentionally unsupported on this hardware class.
Agent-ready serving
The server is built to sit behind an agent harness, not just a chat UI:
- OpenAI Chat Completions and Anthropic Messages APIs (tools + streaming)
dmlx connectprints or writes the harness config (Claude Code, Codex, aider, Cline)- longest-prefix KV snapshots: multi-turn agent sessions re-use the shared prompt prefix instead of re-prefilling from scratch (~44x faster turn-2 measured)
- streaming speculative decoding: SSE clients get the same MTP speedup as batch requests
- long context validated end-to-end at 42k tokens (256k positions declared by the model config)
An inspectable local runtime
The service, scheduler, model adapters, cache management, and performance-critical dispatch logic live in Zig. Python is used for conversion, oracle checks, and benchmark tooling, but the serving process does not require a Python runtime.
The MLX-backed path still depends on mlx-c; “Zig-controlled” does not mean “MLX-free.” The DeepSeek V4 --native path is the separate native execution path.
Choose a path
| Path | Execution | Best for | Status |
|---|---|---|---|
| Qwen3.8-27B-4bit + MTP | Zig runtime + mlx-c + custom Metal kernels |
Agent-harness serving, fast local decode, speculative-decoding research | Flagship / benchmarked |
| DeepSeek V4 Flash | Native engine + packed SSD-streamed experts | Running a 284B MoE model under a 48GB memory budget | Flagship / benchmarked |
| Llama-like, Mistral, Qwen2/3, Gemma, GLM-4, Phi/Phi-3, LLaVA, GLM-5 Next | MLX-backed registry adapters | Compatibility and development | Implemented / model-dependent |
| n-gram speculation, PLD, EAGLE, DSpark and alternate Metal paths | Mixed | Kernel and decoding experiments | Experimental |
Quick start
One-command install (macOS, Apple Silicon)
curl -fsSL https://raw.githubusercontent.com/zouyee/dmlx/main/scripts/install.sh | bash
This downloads the latest release,
verifies the sha256, installs into ~/.local/share/dmlx, and links the CLI to
~/.local/bin/dmlx. The tarball bundles libmlxc, libmlx, and
mlx.metallib — nothing else to install, no Zig required.
What runs on your Mac
Measured on an Apple M4 Pro with 48GB unified memory; see Benchmarks for protocols and raw artifacts.
| Model | Memory needed | Measured speed | Notes |
|---|---|---|---|
| Qwen3.8-27B-4bit + MTP drafter | fits in 48GB | 43.2 tok/s decode (non-thinking), 0.28s TTFT | speculative decoding, flagship path |
| DeepSeek V4 Flash 4bit (284B MoE) | ~20.3GiB RSS + SSD for cold experts | 1.24 tok/s effective completion | 284B model under a 48GB budget via expert streaming |
| Llama / Mistral / Qwen2/3 / Gemma / GLM / Phi registry models | model-dependent | compatibility paths | see Choose a path |
Models the easy way
dmlx pull downloads a registered model from Hugging Face with resumable
transfers and SHA256 verification; dmlx doctor checks hardware, Metal, and
installed models. Model aliases work anywhere --model takes a path.
./dmlx/bin/dmlx doctor
./dmlx/bin/dmlx pull qwen3.8-27b-4bit # target model
./dmlx/bin/dmlx pull qwen3.8-27b-mtp-4bit # MTP drafter for speculative decode
./dmlx/bin/dmlx serve --model qwen3.8-27b-4bit --speculative-mtp 7 --port 8080
Pulled models land in ~/.cache/dmlx/models/ (override with
DMLX_MODEL_HOME). Registered aliases: qwen3.8-27b-4bit,
qwen3.8-27b-mtp-4bit, deepseek-v4-flash-4bit.
Install from a release (no Zig required)
Download the latest dmlx-*-macos-arm64.tar.gz from
GitHub Releases and unpack it:
tar -xzf dmlx-*-macos-arm64.tar.gz
./dmlx/bin/dmlx version
The tarball bundles libmlxc, libmlx, and mlx.metallib; nothing else
needs to be installed. The binary is ad-hoc signed, so on first run macOS may
require xattr -dr com.apple.quarantine dmlx/ or right-click → Open.
A Homebrew tap formula lives in
packaging/homebrew/dmlx.rb and can be copied
into a homebrew-tap repository for brew install distribution.
Build from source
Requirements:
- macOS on Apple Silicon
- Zig 0.16 or newer
mlx-c, discoverable throughpkg-configor an explicit prefix
brew install zig mlx-c
zig version
pkg-config --modversion mlxc
If pkg-config cannot locate mlx-c, set MLX_C_PREFIX or pass -Dmlx_prefix=/path/to/mlx-c to zig build.
Build
git clone https://github.com/zouyee/dmlx.git
cd dmlx
zig build -Doptimize=ReleaseFast
The binary is written to zig-out/bin/dmlx.
Serve Qwen3.8-27B with MTP
The target model and MTP drafter are separate checkpoints.
export DMLX_QWEN38_MTP_DIR=~/models/Qwen3.8-27B-MTP-4bit
./zig-out/bin/dmlx serve \
--model ~/models/Qwen3.8-27B-4bit \
--mlx \
--speculative-mtp 7 \
--port 8080
--speculative-mtp 7 sets the adaptive controller’s ceiling; it does not force every round to draft seven tokens.
DFlash2 block drafter (experimental). Instead of the sequential MTP head you can use the block-parallel z-lab/Qwen3.8-27B-DFlash2 drafter (7 tokens per draft round, conditioned on backbone layers 5/19/33/47/61). Point DMLX_QWEN38_DFLASH2_DIR at the checkpoint before serving with --speculative-mtp:
huggingface-cli download z-lab/Qwen3.8-27B-DFlash2
DMLX_QWEN38_DFLASH2_DIR=~/.cache/huggingface/hub/models--z-lab--Qwen3.8-27B-DFlash2/snapshots/<rev> \
./dmlx/bin/dmlx serve --model qwen3.8-27b-4bit --speculative-mtp 7 --port 8080
Greedy (temperature 0) only for now; sampled drafting and vision prompts fall back or error. The drafter weights are quantized to 4-bit at load by default (DMLX_DF2_DRAFTER_BITS=0 keeps bf16).
Measured on an M4 Pro 48 GB (temp 0, 256-token generations, scripts/realistic_h2h.py):
| scenario | decode tok/s | repeat-prompt TTFT |
|---|---|---|
| code generation | 33.6 | 0.15 s |
| multi-turn | 26.3 | 0.15 s |
| prose summary | 35.8 | 0.28 s |
How it works: the backbone exposes hidden-state taps at layers 5/19/33/47/61; the drafter conditions on those (projected once per committed token into a per-layer K/V ring), drafts 7 tokens in ONE parallel pass through 5 non-causal layers with two-tap dynamic convolutions, and a rank-256/top-16 candidate selector picks the block greedily. The standard draft→verify→commit path keeps outputs lossless (greedy output is bit-identical to the MTP path). Repeat prompts restore both the backbone KV snapshot and the drafter context, so the second turn skips prefill entirely. DMLX_DF2_PREDRAFT=1 additionally builds the next block during verify (off by default — see HANDOFF.md for the measurements).
LoRA adapters (experimental). PEFT adapters can be merged into the quantized backbone at load time — verified with harness-hub/Qwen3.8-27B-pi-adapted (r=32, 256 modules):
huggingface-cli download harness-hub/Qwen3.8-27B-pi-adapted
DMLX_LORA_ADAPTER=~/.cache/huggingface/hub/models--harness-hub--Qwen3.8-27B-pi-adapted/snapshots/<rev> \
./dmlx/bin/dmlx serve --model qwen3.8-27b-4bit --speculative-mtp 7 --port 8080
Each targeted linear is dequantized, merged as W + (alpha/r)·B·A in f32, and requantized — no runtime cost, but not bit-identical to a bf16 merge. Compatible with both MTP and DFlash2 speculative decoding.
Model-card parity for pi-adapted: serve with DMLX_CHAT_EMPTY_THINK=1 (thinking off, as trained) and drive it over /v1/chat/completions (pi: "api": "openai-completions" in ~/.pi/agent/models.json). Tool calls parse into structured tool_calls (qwen3_xml format). Verified end-to-end: the pi coding agent ran a fix-the-failing-test loop (pytest → diagnose → edit → green) against this server. Note the adapter was trained on bf16 weights; merging into a 4-bit backbone preserves behavior in our checks but Terminal-Bench scores were not reproduced. temp>0 requests bypass DFlash2 (greedy-only drafter) automatically.
MTP applies to streaming and non-streaming alike; benchmark measurements should still use non-streaming requests (SSE delivery adds overhead).
Serve DeepSeek V4 Flash in native mode
Pack the routed experts once:
python3 scripts/repack_experts.py ~/models/DeepSeek-V4-Flash-4bit
Then start one server instance:
pkill -f "dmlx serve" 2>/dev/null; sleep 1
NATIVE_SMELT_N=20 ./zig-out/bin/dmlx serve \
--model ~/models/DeepSeek-V4-Flash-4bit \
--expert-packed-dir ~/models/DeepSeek-V4-Flash-4bit/packed_experts \
--native \
--port 8080
Do not use full expert preload on a 48GB machine. One DeepSeek V4 server already holds model weights and an expert cache; running two instances can exhaust unified memory.
Query the server
curl http://127.0.0.1:8080/health
curl http://127.0.0.1:8080/v1/chat/completions \
-H 'Content-Type: application/json' \
-d '{
"model": "default",
"messages": [{"role": "user", "content": "Explain unified memory briefly."}],
"max_tokens": 64,
"temperature": 0,
"stream": false
}'
The server exposes OpenAI-style Chat Completions and an Anthropic-style Messages endpoint. It does not claim full compatibility with every endpoint or response field from either hosted API.
Connect an agent harness
dmlx connect prints the exact config per harness, and --apply writes it where supported:
dmlx connect # list harnesses, detect installed CLIs
dmlx connect claude-code --apply # merge ANTHROPIC_* env into ~/.claude/settings.json
dmlx connect codex --apply # append [model_providers.dmlx] to ~/.codex/config.toml
dmlx connect dsh --apply # write dsh profile patches (web/headless/dsh-tui)
dmlx connect aider # print OPENAI_API_BASE exports
dmlx connect cline # print Cline provider fields
For DeepSeek Harness (dsh), dmlx connect dsh --apply writes
~/.dsh/profiles/<profile>/cordis.patch.yml for the web, headless and
dsh-tui profiles: dmlx as a pi-ai provider, the local model as default
(with image input enabled and a 40960-token context window), and the
mutating tools enabled for the web profile. Then:
DMLX_LOCAL_KEY=local dsh web # or: dsh headless "task"
DMLX_LOCAL_KEY is only a credential placeholder — dmlx ignores the value.
The served model's vision tower handles image input directly (PNG/JPEG via
stb_image, WebP/HEIC via a macOS ImageIO fallback). Codex uses
wire_api = "responses" (newer Codex releases removed the "chat"
wire API); /v1/responses supports function tools and ignores
reasoning/encrypted-content fields.
Zero-wait restarts (agent workloads)
dmlx serve is restart-friendly by default:
- Disk-persisted prefix snapshots — the largest prefix snapshot is
written to
~/.cache/dmlx/snaps/(override withDMLX_QWEN38_SNAP_DIR, empty disables) and reloaded after a restart, so a harness's big static system prompt is prefilled once ever, not once per process. - Startup warmup replay — the highest-token chat request body seen so
far is kept at
~/.cache/dmlx/last_chat.json(override withDMLX_PROMPT_DUMP, empty disables) and replayed withmax_tokens=1three seconds after launch, pre-building snapshots before the first real turn arrives. - Token-prefix-stable prompts — the server reuses cached token ids for the shared string prefix of consecutive requests, which is what makes the KV snapshot's exact-prefix match hit every turn (BPE re-tokenization of the full prompt is not prefix-stable).
Benchmarks
Benchmark claims in this README are deliberately narrow. Each result names its model, hardware, content mode, and raw artifact. Do not compare results across different prompt templates, thinking modes, sampling settings, cache states, or metric definitions.
Qwen3.8-27B-4bit speculative decode
- Hardware: Apple M4 Pro, 48GB unified memory
- Model: local Qwen3.8-27B-4bit target with the same MTP drafter for both engines
- Protocol: greedy, non-streaming, one server at a time, prefix cache disabled or defeated, interleaved A/B
- Metric: streamed token-equivalent content deltas per second during decode; the protocol observed one delta per token for these engines, but SSE does not guarantee this generally
| Workload | dmlx | omlx-mtp | Difference | Source |
|---|---|---|---|---|
| Non-thinking decode headline | 43.2/s | 36.1/s | +19.7% | final_nothink_20261106.json |
| Aligned thinking decode headline | 40.5/s | 35.6/s | +13.8% | think_latch_20261106.json |
| Thinking, code | 47.1/s | 37.7/s | +24.9% | think_latch_20261106.json |
| Thinking, math | 46.6/s | 42.3/s | +10.2% | think_latch_20261106.json |
| Short-prompt TTFT, non-thinking | 0.28s | 0.91s | 3.2× lower | final_nothink_20261106.json |
The headline is the arithmetic mean of the code, prose, and math prompt results. The intentionally predictable count prompt is excluded. “Aligned thinking” means both arms receive the same explicit reasoning directive; unaligned thinking outputs are not comparable because speculative acceptance depends on the text each engine generates.
The harness, prompt set, aggregation, cache controls, and metric definitions are in scripts/compare_engines.py. The raw artifacts currently report engine versions as ?; treat the figures as a recorded local result, not a portable guarantee.
Historical comparisons against mlx-vlm and mlx-lm are not used as headline claims because several earlier runs mixed decode-only rates with end-to-end rates or compared speculative and non-speculative execution. The common-basis result against mlx-vlm was parity, not a demonstrated win. See HANDOFF.md for the measurement history and withdrawn conclusions.
DeepSeek V4 Flash native path
- Hardware: Apple M4 Pro, 48GB
- Configuration: native mode, packed experts,
NATIVE_SMELT_N=20 - Source of truth:
performance-benchmark.json
| Metric | Result |
|---|---|
| Standard effective completion throughput | 1.236 tok/s — median of three 5-token HTTP requests |
| Long-decode diagnostic | 1.950 tok/s — 100 tokens, excluded from the standard median |
| Startup to health-ready | 7.218s |
| Peak RSS | 21,829,861,376 bytes, about 20.3GiB |
| Correctness | Paris PASS; 7/7 end-to-end prompts PASS |
See the human-readable report for request-level timings, telemetry coverage, configuration, and unavailable metrics. In particular, the report does not claim a true HTTP TTFT measurement for this run.
Reproduce locally
# Qwen3.8 benchmark
EXTRA_SERVE_FLAGS="--speculative-mtp 7" \
bash scripts/run_benchmark_qwen38.sh ~/models/Qwen3.8-27B-4bit
# DeepSeek V4 correctness
bash scripts/dsv4_smoke.sh
bash scripts/run_kernel_tests.sh
bash scripts/run_mla_attention_test.sh
# DeepSeek V4 standard benchmark
NATIVE_SMELT_N=20 bash scripts/run_benchmark.sh --native \
~/models/DeepSeek-V4-Flash-4bit
Benchmark numbers are hardware-, model-, prompt-, and version-specific. Please attach the raw artifact when reporting a result.
How the Qwen3.8 MTP path works
prompt
│
├─ target prefill ───────────────► first target token
│ │
│ MTP head cache
│ │
└─► adaptive draft chain: d1 → d2 → … → dN
│
one target verify over [token, d1…dN]
│
accept longest matching prefix
│
commit accepted state / rollback rejected state
└─► next round
Important implementation points:
src/models/qwen38_mtp.zig— MTP head, cache, chained draft body, coarse candidate headsrc/models/qwen38_gdn.zig— Gated DeltaNet prefill, verify, decode, and custom kernelssrc/models/verify_qmm.zig— shape-based split-K and simdgroup-matrix routingsrc/model_registry.zig— target/drafter adapter, prompt priming, commit, and rollbacksrc/engine/engine_loop.zig— speculative request loop and adaptive depth controller
How DeepSeek V4 fits in 48GB
The routed MoE has 256 experts per layer and activates six per token. Loading every expert for every layer would require about 147GB even in the packed format, so the native path uses a bounded working set:
request
│
├─ resident non-expert weights
├─ SMELT hot experts in unified memory
└─ cold expert miss
└─ async pread from packed_experts/
└─ routed Metal kernel
Approximate memory budget for the tested 48GB machine:
| Component | Approximate memory |
|---|---|
| Non-expert model weights | ~5GB |
| Attention and mHC weights | ~2GB |
SMELT expert cache, N=20 |
~11GB |
| Metal buffers | ~2–3GB |
| OS and other processes | ~3–5GB |
N=20 leaves room for the OS page cache and is the recommended default. Larger hot sets can improve hit rate but approach the machine’s memory limit quickly.
API and runtime boundaries
Currently exposed routes:
POST /v1/chat/completionsPOST /v1/completions(legacy raw-text completion)POST /v1/responses(+GET/DELETE /v1/responses/{id})POST /v1/messages(+POST /v1/messages/count_tokens)POST /v1/tokenize/POST /v1/detokenize(aliases/tokenize,/detokenize)POST /v1/embeddings(last-hidden pooling, Qwen3.8 path)GET /v1/modelsGET /metrics(Prometheus text format, also/v1/metrics)GET /api/statusGET /healthPOST /shutdown
Current boundaries:
- the HTTP service starts with one configured model
- request handling is currently serialized through the active engine path
- MTP performance measurements use non-streaming requests
- registered architecture support is broader than the set of continuously benchmarked checkpoints
- experimental speculative methods and alternate Metal paths may have no stable server entry point
These boundaries are intentional documentation, not a roadmap promise.
Build, test, and benchmark
make # ReleaseFast build
make test # build + unit tests
make verify # model-backed DeepSeek V4 verification
make benchmark # DeepSeek V4 benchmark; requires local model and packed experts
make check # test + verify + benchmark
Metal changes should also run:
bash scripts/run_kernel_tests.sh
bash scripts/run_mla_attention_test.sh
Model-backed commands require the corresponding local checkpoints and enough unified memory. They are not part of a lightweight dependency-only test run.
Repository map
src/
├── main.zig CLI and command dispatch
├── model_registry.zig model adapters and MTP integration
├── engine/ request loop, scheduling, prefix cache
├── server/ HTTP endpoints and request handling
├── models/
│ ├── qwen38.zig Qwen3.8 target model
│ ├── qwen38_mtp.zig Qwen3.8 MTP drafter
│ ├── qwen38_gdn.zig GDN implementation and kernels
│ ├── verify_qmm.zig verify-shape quantized matmul routing
│ ├── deepseek_v4.zig DeepSeek V4 model path
│ ├── expert_stream.zig packed expert I/O
│ └── expert_cache.zig bounded expert residency
├── kvcache/ KV-cache strategies
├── tokenizer/ tokenizer implementations
├── guided.zig regex and JSON-constrained decoding
└── trainer.zig local training experiments
scripts/ conversion, correctness, profiling, benchmarks
artifacts/ raw benchmark and diagnostic outputs
docs/ design notes and measured reports
Documentation
| Document | Purpose |
|---|---|
| DeepSeek V4 benchmark report | Current native benchmark, protocol, and telemetry |
| DeepSeek MoE technical notes | Packed experts and native MoE execution |
| Qwen3.8 MTP engineering history | Optimization campaign, measurement corrections, and remaining limits |
| MTP framework plan | Direction for a reusable speculative-decoding framework |
| Contributing | Development workflow |
| Changelog | Release history |
Some files under docs/analysis/ are engineering journals rather than current user documentation. Prefer the benchmark artifact and current source when a historical note conflicts with a measured result.
Acknowledgments
Custom kernels and techniques include work adapted from:
The project icon adapts Ziggy the Ziguana from the official Zig artwork repository, licensed under CC BY 4.0. Ziggy artwork copyright belongs to its original creator; the dmlx MLX-badge composition is an adaptation.
See source headers for per-kernel provenance and licenses. Adapted Apache-2.0 and MIT code retains its required attribution.
License
Explore projetos relacionados
Carregando…