🌐 English | 中文说明 | Русское описание
Running Qwen3-Coder-30B-A3B-Instruct (30.5B total parameters, 3.3B active per token, 128 MoE experts) on a 16 GB or 18 GB Apple Silicon Mac (M1/M2/M3/M4 Pro) normally forces a painful trade-off:
~17.2 GiB): Exceeds available GPU wired memory on 16–18 GB Macs as soon as context grows past 4k–8k tokens, causing severe SSD swap thrashing.~12.4 GiB): Fits in RAM, but quantizing self_attn (q_proj, k_proj, v_proj, o_proj) and lm_head to 3 bits (~18.5% reconstruction error) breaks RoPE attention at 15k–25k+ context in agentic coding tools (OpenCode, Cline, Roo Code), causing hallucinated line numbers and infinite repetition loops.Ternary2x solves both problems using a Hybrid Multi-Plane Ternary (-1, 0, +1) decomposition packed into standard bitwise-compatible MLX format (uint32 + scales + biases, group_size=64):
| Model Component | Parameters | Quantization Format | MLX Bitwidth | Relative Error |
|---|---|---|---|---|
MoE Routed Experts (mlp.switch_mlp.{gate,up,down}_proj, 128 experts) |
29.0B (95.1%) | 2-Plane Ternary (-1, 0, +1) with neighbor residual compensation ($\mathbf{w} \approx \alpha_1 \mathbf{t}_1 + \alpha_2 \mathbf{t}_2$) |
bits=3, gs=64 |
~18.5% |
Attention + Embeddings + LM Head (self_attn.{q,k,v,o}_proj, embed_tokens, lm_head) |
1.52B (4.9%) | 3-Plane Ternary (-1, 0, +1) ($\mathbf{w} \approx \alpha_1 \mathbf{t}_1 + \alpha_2 \mathbf{t}_2 + \alpha_3 \mathbf{t}_3$) |
bits=6, gs=64 |
~2.20% |
MoE Router & Norms (mlp.gate, *layernorm*, q_norm, k_norm) |
0.01B | Full bfloat16 |
16-bit | 0.00% |
| Variant | Weights Size | Fits 16–18 GB Mac at 25k–64k Context? | Attention (q,k,v,o) Error |
Prefill Speed (20k ctx) | Decode Speed | Long-Context Agentic Coding (OpenCode / Cline) |
|---|---|---|---|---|---|---|
Standard 4-bit (mlx-community) |
~17.2 GiB | ❌ OOM / heavy swap above 8k ctx | ~5.0% | Slow (swap) | Slow (swap) | Unusable on 16–18 GB RAM |
Standard 3-bit (mlx-community) |
~12.4 GiB | ✅ Yes | ❌ ~18.5% | ~95 tok/s | ~54 tok/s | ❌ Hallucinates line numbers & loops at >15k ctx |
| Ternary2x Hybrid (This repo) | 12.99 GiB | ✅ Yes (~3–4 GB free for KV cache) | ✅ 2.20% | 240.4 tok/s | 53.5 tok/s | ✅ Exact line-number citations & zero looping at 25k+ ctx |
mlx_lm / LM Studio / vllm-mlx (Works out of the box, no patches required)Because the ternary planes are mapped into standard MLX affine uint32 quantization tables, any MLX engine loads the checkpoint natively:
mlx_lm.generate \
--model ToxeH/Qwen3-Coder-30B-A3B-Instruct-Ternary2x \
--prompt "Write a thread-safe LRU cache in Rust with unit tests" \
--max-tokens 1024
mlx-serve + Custom Metal Ternary Kernel (libternary2x_mlxserve.c)For maximum speed with mlx-serve, compile the included Metal shader interceptor (libternary2x_mlxserve.c), which decodes 2-plane ternary -1, 0, +1 bit-planes directly in GPU registers:
clang -dynamiclib -O3 -fobjc-arc -framework Foundation -framework Metal \
libternary2x_mlxserve.c -o libternary2x_mlxserve.dylib
DYLD_INSERT_LIBRARIES=./libternary2x_mlxserve.dylib \
mlx-serve serve \
--model ToxeH/Qwen3-Coder-30B-A3B-Instruct-Ternary2x \
--ctx-size 65536 --kv-quant 4 --no-decode-attn-quant --no-pld
Recommended Sampling Parameters for Agentic Coding (
OpenCode,Cline,Roo Code):temperature: 0.1–0.2,top_p: 0.9,top_k: 20,repetition_penalty: 1.12,presence_penalty: 0.50.
在 16 GB 或 18 GB 统一内存的 Apple Silicon Mac(M1/M2/M3/M4 Pro)上运行 Qwen3-Coder-30B-A3B-Instruct(总参数 30.5B,每次激活 3.3B,128 个 MoE 专家)通常面临两难选择:
~17.2 GiB): 权重本身几乎占满内存,上下文超过 4k–8k tokens 就会触发严重的 SSD 交换(Swap),速度骤降。~12.4 GiB): 虽然能放进内存,但将注意力层 self_attn (q,k,v,o_proj) 和 lm_head 压缩到 3-bit(重构误差高达 ~18.5%)会严重破坏长上下文 RoPE 注意力。在 OpenCode、Cline、Roo Code 等 Agent 编程工具中,当上下文达到 15k–25k+ tokens 时,模型会出现幻觉(编造不存在的代码行号)并陷入死循环。Ternary2x 混合三值化方案 (12.99 GiB) 完美解决了这一问题:
-1, 0, +1)($\mathbf{w} \approx \alpha_1 \mathbf{t}_1 + \alpha_2 \mathbf{t}_2$,bits=3, group_size=64),体积小、解码极快(53.5 tok/s)。-1, 0, +1)($\mathbf{w} \approx \alpha_1 \mathbf{t}_1 + \alpha_2 \mathbf{t}_2 + \alpha_3 \mathbf{t}_3$,bits=6, group_size=64),将重构误差从 18.5% 降至 2.20%,同时将 20k 长上下文 Prefill 速度提升了 2.5 倍(达到 240.4 tok/s)!bfloat16 精度,确保 128 选 8 专家路由零偏差。mlx_lm、LM Studio、vllm-mlx 和 mlx-serve,无需打补丁;同时附带专用 Metal 内核源码 libternary2x_mlxserve.c 与转换脚本 convert_qwen3_coder_30b_ternary2x.py。При запуске Qwen3-Coder-30B-A3B-Instruct (30.5B параметров, 128 экспертов MoE, 8 активных на токен) на Mac с 16 ГБ или 18 ГБ памяти (M1/M2/M3/M4 Pro) стандартные квантизации дают плохую развилку:
~17.2 ГиБ): Не оставляет места под KV-кэш на 16–18 ГБ Mac и уходит в swap уже на 8k контекста.~12.4 ГиБ): Помещается в память, но сжатие матриц внимания self_attn.{q,k,v,o}_proj и lm_head в 3 бита (погрешность ~18.5%) разрушает точность RoPE-внимания на длинном контексте (15k–25k+ токенов). В агентских IDE (OpenCode, Cline, Roo Code) модель начинает выдумывать несуществующие номера строк кода и зацикливаться.Гибридная троичная сборка Ternary2x (12.99 ГиБ) решает обе проблемы:
| Компонент модели | Параметры | Формат | Биты MLX | Ошибка реконструкции |
|---|---|---|---|---|
MoE Experts (mlp.switch_mlp.{gate,up,down}_proj, 128 экспертов) |
29.0B (95.1%) | 2-слойный троичный -1, 0, +1 с групповой компенсацией соседей ($\mathbf{w} \approx \alpha_1 \mathbf{t}_1 + \alpha_2 \mathbf{t}_2$) |
bits=3, gs=64 |
~18.5% |
Attention + Embeddings + LM Head (self_attn.{q,k,v,o}_proj, embed_tokens, lm_head) |
1.52B (4.9%) | 3-слойный троичный -1, 0, +1 ($\mathbf{w} \approx \alpha_1 \mathbf{t}_1 + \alpha_2 \mathbf{t}_2 + \alpha_3 \mathbf{t}_3$) |
bits=6, gs=64 |
~2.20% |
MoE Router & Norms (mlp.gate, *layernorm*, q_norm, k_norm) |
0.01B | bfloat16 |
16-bit | 0.00% |
OpenCode (25 000 токенов контекста, 22 вызова чтения файлов): 100% точное цитирование методов и номеров строк без галлюцинаций и без зацикливаний.libternary2x_mlxserve.c — динамический интерцептор Metal-шейдеров для mlx-serve (прямое вычисление 2-слойных троичных битовых планов в регистрах GPU).convert_qwen3_coder_30b_ternary2x.py — полный скрипт конвертации BF16 -> Hybrid Ternary2x на GPU (MPS / CUDA).upgrade_attn_3planes.py — скрипт быстрого обновления матриц self_attn, embed_tokens и lm_head через HTTP Range-запросы к Hugging Face CDN (скачивает только ~2.97 ГБ вместо 61 ГБ).model-00001-of-00013.safetensors 1.3 GBmodel-00004-of-00013.safetensors 1.1 GBmodel-00005-of-00013.safetensors 1.1 GBmodel-00006-of-00013.safetensors 1.1 GBmodel-00007-of-00013.safetensors 1.1 GBmodel-00008-of-00013.safetensors 1.1 GBmodel-00009-of-00013.safetensors 1.1 GBmodel-00010-of-00013.safetensors 1.1 GBmodel-00011-of-00013.safetensors 1.1 GBmodel-00012-of-00013.safetensors 1.1 GBmodel-00003-of-00013.safetensors 1.1 GBmodel-00002-of-00013.safetensors 1.1 GBmodel-00013-of-00013.safetensors 341 MBQwen/Qwen3-Coder-30B-A3B-Instruct