deimos-stream 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. deimos_stream-0.1.0/.github/workflows/ci.yml +21 -0
  2. deimos_stream-0.1.0/.github/workflows/publish-pypi.yml +29 -0
  3. deimos_stream-0.1.0/.gitignore +39 -0
  4. deimos_stream-0.1.0/LICENSE +21 -0
  5. deimos_stream-0.1.0/PKG-INFO +236 -0
  6. deimos_stream-0.1.0/README.md +200 -0
  7. deimos_stream-0.1.0/assets/icon.png +0 -0
  8. deimos_stream-0.1.0/assets/icon.svg +34 -0
  9. deimos_stream-0.1.0/include/deimos_sha256.h +93 -0
  10. deimos_stream-0.1.0/include/deimos_stream.h +214 -0
  11. deimos_stream-0.1.0/pyproject.toml +75 -0
  12. deimos_stream-0.1.0/src/deimos_stream/__init__.py +62 -0
  13. deimos_stream-0.1.0/src/deimos_stream/__main__.py +6 -0
  14. deimos_stream-0.1.0/src/deimos_stream/arena.py +485 -0
  15. deimos_stream-0.1.0/src/deimos_stream/backbone.py +316 -0
  16. deimos_stream-0.1.0/src/deimos_stream/cli.py +420 -0
  17. deimos_stream-0.1.0/src/deimos_stream/converter.py +412 -0
  18. deimos_stream-0.1.0/src/deimos_stream/detokenizer.py +62 -0
  19. deimos_stream-0.1.0/src/deimos_stream/engine.py +454 -0
  20. deimos_stream-0.1.0/src/deimos_stream/kv_cache.py +202 -0
  21. deimos_stream-0.1.0/src/deimos_stream/merkle_builder.py +445 -0
  22. deimos_stream-0.1.0/src/deimos_stream/native/deimos_arena.mm +428 -0
  23. deimos_stream-0.1.0/src/deimos_stream/native/deimos_merkle.mm +486 -0
  24. deimos_stream-0.1.0/src/deimos_stream/server.py +495 -0
  25. deimos_stream-0.1.0/tests/__init__.py +1 -0
  26. deimos_stream-0.1.0/tests/test_kv_converter_and_cli.py +171 -0
  27. deimos_stream-0.1.0/tests/test_lookahead_and_dynamick.py +137 -0
  28. deimos_stream-0.1.0/tests/test_merkle_and_arena.py +389 -0
  29. deimos_stream-0.1.0/tests/test_server_and_packaging.py +173 -0
@@ -0,0 +1,21 @@
1
+ name: CI Tests
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ test:
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+ - uses: astral-sh/setup-uv@v4
15
+ - name: Ensure C++17 compiler is available
16
+ run: which c++ || (sudo apt-get update && sudo apt-get install -y --no-install-recommends g++)
17
+ - name: Install dependencies & run C++17 + Python pytest suite
18
+ run: |
19
+ uv venv --python 3.12
20
+ uv pip install -e ".[dev]"
21
+ uv run pytest -v
@@ -0,0 +1,29 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ release:
6
+ types: [published]
7
+
8
+ jobs:
9
+ build-and-publish:
10
+ name: Build dist & publish to PyPI
11
+ runs-on: ubuntu-latest
12
+ permissions:
13
+ contents: read
14
+ id-token: write
15
+ env:
16
+ HAS_PYPI_TOKEN: ${{ secrets.PYPI_API_TOKEN != '' }}
17
+ steps:
18
+ - uses: actions/checkout@v4
19
+ - uses: astral-sh/setup-uv@v4
20
+ - name: Build wheel and sdist
21
+ run: uv build
22
+ - name: Publish to PyPI via API Token
23
+ if: env.HAS_PYPI_TOKEN == 'true'
24
+ uses: pypa/gh-action-pypi-publish@release/v1
25
+ with:
26
+ password: ${{ secrets.PYPI_API_TOKEN }}
27
+ - name: Publish to PyPI via OIDC Trusted Publisher
28
+ if: env.HAS_PYPI_TOKEN != 'true'
29
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,39 @@
1
+ # Python & Virtual Environments
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.egg-info/
6
+ .eggs/
7
+ dist/
8
+ build/
9
+ .venv/
10
+ venv/
11
+ .pytest_cache/
12
+ .mypy_cache/
13
+ .ruff_cache/
14
+
15
+ # Compiled Native Shared Libraries & Object Files
16
+ *.dylib
17
+ *.so
18
+ *.o
19
+ *.a
20
+ *.dSYM/
21
+
22
+ # Model Checkpoints, Merkle Indices & KV Prefix Caches
23
+ *.bin
24
+ *.idx
25
+ *.safetensors
26
+ *.gguf
27
+ *.npz
28
+ *.pt
29
+ *.pth
30
+ *merkle_store*
31
+ kv_cache_blocks/
32
+ checkpoints/
33
+ models/
34
+
35
+ # OS & Editor Metadata
36
+ .DS_Store
37
+ *.swp
38
+ .idea/
39
+ .vscode/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 martianacademy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,236 @@
1
+ Metadata-Version: 2.5
2
+ Name: deimos-stream
3
+ Version: 0.1.0
4
+ Summary: Universal Low-VRAM Sparse MoE & LLM Merkle-Paged Streaming Engine (Metal • MLX • C++17)
5
+ Project-URL: Homepage, https://github.com/martianacademy/deimos-stream
6
+ Project-URL: Repository, https://github.com/martianacademy/deimos-stream
7
+ Project-URL: Issues, https://github.com/martianacademy/deimos-stream/issues
8
+ Author-email: Martian Academy <research@martian.academy>
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: apple-silicon,deepseek,llm,low-vram,merkle-tree,mixtral,mixture-of-experts,mlx,moe,offloading,olmoe,paged-memory,qwen-moe
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: MacOS :: MacOS X
17
+ Classifier: Programming Language :: C++
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: fastapi>=0.115.0
25
+ Requires-Dist: mlx-lm>=0.21.0; sys_platform == 'darwin' and platform_machine == 'arm64'
26
+ Requires-Dist: mlx>=0.22.0; sys_platform == 'darwin' and platform_machine == 'arm64'
27
+ Requires-Dist: numpy>=1.26.0
28
+ Requires-Dist: pydantic>=2.8.0
29
+ Requires-Dist: safetensors>=0.4.5
30
+ Requires-Dist: tokenizers>=0.19.0
31
+ Requires-Dist: uvicorn>=0.30.0
32
+ Provides-Extra: dev
33
+ Requires-Dist: httpx>=0.27.0; extra == 'dev'
34
+ Requires-Dist: pytest>=8.0.0; extra == 'dev'
35
+ Description-Content-Type: text/markdown
36
+
37
+ # <img src="https://raw.githubusercontent.com/martianacademy/deimos-stream/main/assets/icon.png" width="42" align="top" alt="DeimosStream Icon" /> DeimosStream
38
+
39
+ [![CI Tests](https://github.com/martianacademy/deimos-stream/actions/workflows/ci.yml/badge.svg)](https://github.com/martianacademy/deimos-stream/actions/workflows/ci.yml)
40
+ [![Martian Suite: PhobosStream](https://img.shields.io/badge/Twin_Engine-PhobosStream-EE6A3E)](https://github.com/martianacademy/phobos-stream)
41
+ [![Backend](https://img.shields.io/badge/Metal_%E2%80%A2_MLX_%E2%80%A2_C%2B%2B17-DEIMIDX2-EE6A3E)](https://github.com/martianacademy/deimos-stream)
42
+ [![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-brightgreen.svg)](https://www.python.org/)
43
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/martianacademy/deimos-stream/blob/main/LICENSE)
44
+
45
+ **DeimosStream** is a universal low-VRAM **Sparse Mixture-of-Experts (MoE) LLM streaming engine** — the language-model twin to [**PhobosStream**](https://github.com/martianacademy/phobos-stream) — built to run large Sparse MoE models (**`OLMoE`**, **`Qwen2/3-MoE`**, **`Mixtral`**, **`DeepSeek-MoE`**) inside a tiny, strictly bounded GPU memory footprint with **cryptographic Merkle proof verification** on every cold expert page streamed from NVMe SSD.
46
+
47
+ By combining a **16 KB Page-Aligned 4-Bit Cryptographic Merkle Store (`DEIMIDX2`)**, a **Pre-Allocated Unified-Memory `PagedExpertArena`** (`mx.gather_qmm`), **Zero-GIL C++17 Cross-Layer Residual Lookahead**, and **Cache-Aware Miss-Only Nucleus Dynamic-K**, DeimosStream cuts Peak Metal GPU Memory on a real **13.20 GiB (`6.92B`) Sparse MoE model from `13,613.4 MiB` down to `1,086.8–1,518.8 MiB` (`88.8%–92.0%` VRAM reduction)** while sustaining **`45.5–57.4 tok/s`** with **zero prefill VRAM spikes** and **no perplexity degradation**.
48
+
49
+ ---
50
+
51
+ ## 📊 Verified Empirical Benchmarks (`OLMoE-1B-7B`, 6.92B Params / 13.20 GiB FP16)
52
+
53
+ *Measured end-to-end on Apple Silicon (`M4 Max` Metal GPU, real `F_NOCACHE` random NVMe `pread` measured at `2.03–2.96 GiB/s`) on `allenai/OLMoE-1B-7B-0125-Instruct` (`16 layers × 64 experts = 1,024` SwiGLU experts, `Top-8` active per token):*
54
+
55
+ | Execution Mode | Active / Peak Metal VRAM | Peak VRAM Saved | Process RSS | Expert Cache Hit Rate | Decode Speed | Held-Out Quality (PPL ↓) |
56
+ | :--- | :---: | :---: | :---: | :---: | :---: | :--- |
57
+ | **1. Monolithic FP16 Baseline** *(All weights in GPU)* | `13,261.5` / **13,613.4 MiB** | `0.0%` | `13,680+ MiB` | `100.0%` *(Pinned)* | `142.24 tok/s` | `6.4182` *(FP16 Ref)* |
58
+ | **2. Naive On-Demand FP16 Streaming** *(`mx.stack`)* | `1,709.4` / **4,567.9 MiB** *(+2.85 GiB spike)* | `66.4%` | `~4,600 MiB` | `19.0%` | `4.71 tok/s` | `6.4182` |
59
+ | **3. DeimosStream Full-Pinned Q4 (`--slots 64`)** | `4,108.8` / **4,154.5 MiB** | **`69.5%`** | `~4,220 MiB` | `100.0%` *(Pinned)* | **251.48 tok/s** *(1.77x)* | **6.2229** |
60
+ | **4. DeimosStream Low-VRAM Champion (`--slots 16 --tau 0.85`)** | `1,516.8` / **1,518.8 MiB** *(0 spike)* | **`88.8%`** | **1,309.8 MiB** | **92.2%–93.3%** | **55.62 tok/s** *(57.4 @ τ=0.78)* | **6.2285** |
61
+ | **5. DeimosStream Ultra-Low `1.06 GiB` (`--slots 8 --tau 0.85`)** | `1,084.8` / **1,086.8 MiB** *(0 spike)* | **`92.0%`** | **881.7 MiB** | **88.4%** | **45.53 tok/s** | **6.2541** *(0.0 diff @ τ=1.0)* |
62
+
63
+ * **Bit-Exact Streaming Guarantee (`--tau 1.0`)**: Running `DeimosPagedMoEEngine(..., slots_per_layer=8, miss_tail_tau=1.0)` produces **`0.00000000` (`0.0`) maximum logit difference** and **100% identical greedy tokens** against Full-64-Slot Pinned Q4 despite continuous LFU+LRU page evictions.
64
+ * **Warm Multi-Turn Merkle KV-Prefix Cache**: Across full process restarts on a 54-token prompt, `MerkleKVPrefixCache` verifies and restores `48/54` cached prompt tokens in `O(1)` via `DEIMIDX2` Robin-Hood hashing, cutting cold-restart TTFT **`4.29x` (`1,014.5 ms -> 236.4 ms`)** with exact output parity.
65
+
66
+ ---
67
+
68
+ ## 🏛️ System Architecture
69
+
70
+ ```mermaid
71
+ flowchart TD
72
+ subgraph STORE["DEIMIDX2 Cryptographic Merkle Store (NVMe SSD)"]
73
+ IDX["merkle_tree.idx (320B Header + Flat XOR Tree + Robin-Hood KV Table)"]
74
+ CAS[("cas_experts_q4.bin (16 KB Page-Aligned Q4 Expert Leaves)")]
75
+ CORE["shared_core.bin + embed_tokens.bin + lm_head_int8.bin"]
76
+ end
77
+
78
+ subgraph PREFILL["Stage 1: Chained SHA-256 Merkle KV-Prefix Cache"]
79
+ TOK["Prompt Token IDs"] --> KVH["16-Token Block Hash Chain from model_merkle_root"]
80
+ KVH -->|"Robin-Hood Hit"| KVR["Restore .safetensors KV Blocks (4.29x Faster TTFT)"]
81
+ end
82
+
83
+ subgraph LAYER["Stage 2: Per-Layer Paged MoE Execution + Residual Lookahead"]
84
+ KVR --> ATTN["UniversalAttention (Fused MHA/GQA + Full/Per-Head/None QK-Norm)"]
85
+ ATTN --> LA["Residual Lookahead: W_gate^(l+1) * RMSNorm(h^(l)) (83.9% Recall)"]
86
+ LA -.->|"Zero-GIL C++17 Async Worker (F_NOCACHE pread + CC_SHA256)"| NEXT["Disjoint PagedExpertArena[l+1]"]
87
+ CAS ==>|"Cold Leaf DMA + Tier-2 SHA-256 Proof"| NEXT
88
+ ATTN --> DYNK["Cache-Aware Miss-Only Nucleus Dynamic-K (tau=0.85)"]
89
+ DYNK --> QMM["Zero-Copy mx.gather_qmm on PagedExpertArena[l]"]
90
+ end
91
+ ```
92
+
93
+ ### Core Architectural Mechanisms
94
+
95
+ 1. **Universal `DEIMIDX2` Cryptographic Merkle Index (`deimos_merkle.mm`)**:
96
+ - Supports arbitrary `(num_layers, num_experts, vocab_size)` topologies (non-power-of-2 leaf counts automatically padded to `tree_leaf_cap = 2^⌈log2(L·E)⌉`).
97
+ - **Tier-1 Startup Proof**: Verifies all leaf-to-root XOR sibling paths and the 4-branch `model_merkle_root` (`embedding || shared_core || expert_tree || lm_head`) in **`2.08 ms`** (`3.1 ns` `O(1)` C-struct lookup).
98
+ - **Tier-2 Cold Leaf Proof**: Hardware-accelerated ARMv8 `CC_SHA256` verifies every cold expert's raw 4-bit payload bytes on NVMe `pread`/`mmap` before weights enter GPU memory, raising `DeimosMerkleIntegrityError` on even a **1-bit disk flip**.
99
+ 2. **Pre-Allocated Unified-Memory `PagedExpertArena` (`deimos_arena.mm`)**:
100
+ - Eliminates `mx.stack` allocation spikes by pre-allocating a fixed `[C, ...]` Q4 tensor pool per layer in Apple Silicon Unified Memory.
101
+ - Cache hits execute directly in-place via `mx.gather_qmm(..., rhs_indices=phys_slots)` with **zero intermediate tensor copies**; cache misses overwrite the LFU+LRU victim slot in-place via zero-GIL C++17 `memcpy` + `POSIX_MADV_DONTNEED`.
102
+ 3. **Cross-Layer Residual Lookahead (`83.91%` Top-8 Recall)**:
103
+ - Exploits residual stream continuity ($h^{(l+1)} = h^{(l)} + \Delta_{\text{MoE}}^{(l)} + \Delta_{\text{Attn}}^{(l+1)}$): predicts Layer `l+1` experts using $W_{\text{gate}}^{(l+1)} \cdot \text{RMSNorm}(h_{\text{post-attn}}^{(l)})$ and stages cold `l+1` leaves on a background C++17 worker thread into **disjoint `arena[l+1]`** while the Metal GPU computes `MoE(l)` and `Attention(l+1)` — eliminating **83.6% of synchronous SSD misses** with zero race conditions.
104
+ 4. **Cache-Aware Miss-Only Nucleus Dynamic-K (`--tau`)**:
105
+ - Never drops experts already resident in GPU VRAM (since cache hits cost `<0.05 ms` on Metal). Only skips **low-weight tail SSD misses** beyond `min_k` once cumulative routing mass reaches $\tau$ (`0.85`), rescaling kept weights to preserve layer activation norm.
106
+
107
+ ---
108
+
109
+ ## 📐 Scaling Envelope & Honest Hardware Scope
110
+
111
+ Why Sparse MoE streaming achieves `45–57 tok/s` while dense weight streaming cannot:
112
+ * A **dense** model touches **100%** of its parameters on every single token (`e.g. 14 GB / 3 GB/s ≈ 0.2 tok/s` physics ceiling).
113
+ * A **Sparse MoE** activates only **$k / E$ (`3%–12.5%`)** of expert parameters per token, exhibits strong conversational topic locality (`88%–93%` hit rate in a `12.5%–25%` slot arena), and exposes cross-layer residual predictability (`~84%` lookahead recall).
114
+
115
+ | Sparse MoE Model Class | Original FP16 Size | Q4 `DEIMIDX2` Disk Store | Active Backbone + KV | Paged Arena (`16–25%` Slots) | Total GPU VRAM Needed |
116
+ | :--- | :---: | :---: | :---: | :---: | :---: |
117
+ | **`OLMoE-1B-7B` (6.9B, A1.3B)** *(Verified)* | `13.2 GiB` | `3.38 GiB` | `~0.65 GiB` | `0.43–0.86 GiB` (`8–16/64`) | **`1.08 – 1.52 GiB`** |
118
+ | **`Qwen3-30B-A3B` (30.5B, 128E Top-8)** | `~61 GiB` | `~15.5 GiB` | `~1.6 GiB` | `~2.4 GiB` (`20/128`) | **`~4.0 – 4.5 GiB`** *(8 GB Mac)* |
119
+ | **`Mixtral-8x7B` (46.7B, 8E Top-2)** | `~93 GiB` | `~23.5 GiB` | `~2.1 GiB` | `~3.8 GiB` (`2–3/8`) | **`~5.8 – 6.5 GiB`** *(8–16 GB Mac)* |
120
+ | **`Qwen3-235B-A22B` (235B, 128E Top-8)** | `~470 GiB` | `~118 GiB` | `~8.5 GiB` | `~11.5 GiB` (`16/128`) | **`~20 – 22 GiB`** *(24–32 GB Mac)* |
121
+
122
+ *(Note: `OLMoE-1B-7B` figures are live hardware measurements on M4 Max; larger rows show analytical `DEIMIDX2` Q4 memory footprints from exact tensor dimensions.)*
123
+
124
+ ---
125
+
126
+ ## ⚡ Quick Start
127
+
128
+ ### 1. Install (`PyPI` or Source on macOS Apple Silicon `arm64`)
129
+
130
+ ```bash
131
+ pip install deimos-stream
132
+ ```
133
+
134
+ Or install from source for development:
135
+ ```bash
136
+ git clone https://github.com/martianacademy/deimos-stream.git
137
+ cd deimos-stream
138
+ uv venv --python 3.12 && source .venv/bin/activate
139
+ uv pip install -e ".[dev]"
140
+ pytest -v
141
+ ```
142
+ *(Requires macOS `arm64` with Xcode Command Line Tools `clang++` for automatic `libdeimos_stream.dylib` compilation; `DEIMIDX2` inspection & Merkle verification also compile natively on Linux C++17.)*
143
+
144
+ ### 2. Convert Any `.safetensors` Sparse MoE Checkpoint & Stream Chat
145
+
146
+ Supports HuggingFace & MLX `.safetensors` checkpoints across **`OLMoE`**, **`Qwen2-MoE` / `Qwen3-MoE`** (including GQA, per-head QK-Norm, and `shared_expert`), **`Mixtral`** (`w1/w2/w3`), and **`DeepSeek-MoE`**:
147
+
148
+ ```bash
149
+ # 1. Convert a .safetensors Sparse MoE checkpoint into a 16 KB page-aligned DEIMIDX2 Q4 store:
150
+ deimos-stream convert \
151
+ --model-dir /path/to/OLMoE-1B-7B-0125-Instruct \
152
+ --output-dir ./olmoe_deimos_q4
153
+
154
+ # 2. Cryptographically verify the Tier-1 XOR Merkle tree & all Tier-2 SHA-256 expert leaves:
155
+ deimos-stream inspect --store-dir ./olmoe_deimos_q4 --verify-leaves
156
+
157
+ # 3. Launch interactive Low-VRAM streaming chat (1.52 GiB VRAM @ ~56 tok/s):
158
+ deimos-stream chat --store-dir ./olmoe_deimos_q4 --slots 16 --tau 0.85
159
+
160
+ # Ultra-Low 1.08 GiB VRAM mode (8 slots/layer):
161
+ deimos-stream chat --store-dir ./olmoe_deimos_q4 --slots 8 --tau 0.85
162
+ ```
163
+
164
+ Inside interactive `deimos-stream chat`, switch VRAM budgets and routing thresholds live:
165
+ * `/slots <8|16|32|64>` — hot-rebuild `PagedExpertArena` capacity on the fly
166
+ * `/tau <0.50..1.00>` — adjust Miss-Only Nucleus Dynamic-K (`1.00` = bit-exact Top-K)
167
+ * `/lookahead <on|off>` — toggle C++17 cross-layer Residual Lookahead prefetch
168
+
169
+ ### 3. OpenAI-Compatible API Gateway (`deimos-stream serve`)
170
+
171
+ Expose any `DEIMIDX2` Sparse MoE store as a local OpenAI `/v1/chat/completions` server (streaming SSE + JSON, compatible with the `openai` SDK, Cursor, Continue, OpenCode, and OpenWebUI):
172
+
173
+ ```bash
174
+ deimos-stream serve \
175
+ --store-dir ./olmoe_deimos_q4 \
176
+ --host 127.0.0.1 \
177
+ --port 8080 \
178
+ --slots 16 \
179
+ --tau 0.85 \
180
+ --model-name olmoe-1b-7b-q4
181
+ ```
182
+
183
+ ```bash
184
+ curl http://127.0.0.1:8080/v1/chat/completions \
185
+ -H "Content-Type: application/json" \
186
+ -d '{
187
+ "model": "olmoe-1b-7b-q4",
188
+ "stream": true,
189
+ "max_tokens": 128,
190
+ "messages": [{"role": "user", "content": "Explain Merkle trees in two sentences."}]
191
+ }'
192
+ ```
193
+
194
+ ### 4. Python API (`DeimosPagedMoEEngine`)
195
+
196
+ ```python
197
+ from pathlib import Path
198
+ from deimos_stream import DeimosPagedMoEEngine, convert_safetensors_moe_to_deimos_q4
199
+
200
+ # One-time conversion from HuggingFace / MLX .safetensors:
201
+ store_dir = convert_safetensors_moe_to_deimos_q4(
202
+ source_model_dir=Path("/path/to/moe-checkpoint"),
203
+ output_store_dir=Path("./moe_deimos_q4"),
204
+ )
205
+
206
+ # Run inside a fixed 16-slot/layer Unified-Memory Arena:
207
+ engine = DeimosPagedMoEEngine(
208
+ store_dir=store_dir,
209
+ slots_per_layer=16,
210
+ use_nocache_pread=True,
211
+ enable_lookahead=True,
212
+ miss_tail_tau=0.85, # Set 1.0 for bit-exact parity vs full-pinned Q4
213
+ )
214
+ try:
215
+ metrics = engine.benchmark_generation(
216
+ "<|user|>\nExplain Merkle trees in two sentences.\n<|assistant|>\n",
217
+ max_new_tokens=64,
218
+ )
219
+ print(metrics["generated_text"])
220
+ print(f"Peak VRAM: {metrics['peak_vram_mb']} MiB | Speed: {metrics['decode_tok_per_s']} tok/s")
221
+ finally:
222
+ engine.close()
223
+ ```
224
+
225
+ ---
226
+
227
+ ## 🌌 Martian Academy Streaming Suite
228
+
229
+ * [**PhobosStream**](https://github.com/martianacademy/phobos-stream) — Universal Zero-VRAM **Video & Image Diffusion (`DiT`)** Streaming Engine (`Wan2.1`, `FLUX.1`, `HunyuanVideo`, `Z-Image-Turbo` • `93.9%–95.3%` VRAM saved).
230
+ * [**DeimosStream**](https://github.com/martianacademy/deimos-stream) — Universal Low-VRAM **Sparse MoE & LLM** Merkle-Paged Streaming Engine (`OLMoE`, `Qwen2/3-MoE`, `Mixtral`, `DeepSeek-MoE` • `88.8%–92.0%` VRAM saved).
231
+
232
+ ---
233
+
234
+ ## 📜 License
235
+
236
+ [MIT License](https://github.com/martianacademy/deimos-stream/blob/main/LICENSE) — free for commercial and personal use.
@@ -0,0 +1,200 @@
1
+ # <img src="https://raw.githubusercontent.com/martianacademy/deimos-stream/main/assets/icon.png" width="42" align="top" alt="DeimosStream Icon" /> DeimosStream
2
+
3
+ [![CI Tests](https://github.com/martianacademy/deimos-stream/actions/workflows/ci.yml/badge.svg)](https://github.com/martianacademy/deimos-stream/actions/workflows/ci.yml)
4
+ [![Martian Suite: PhobosStream](https://img.shields.io/badge/Twin_Engine-PhobosStream-EE6A3E)](https://github.com/martianacademy/phobos-stream)
5
+ [![Backend](https://img.shields.io/badge/Metal_%E2%80%A2_MLX_%E2%80%A2_C%2B%2B17-DEIMIDX2-EE6A3E)](https://github.com/martianacademy/deimos-stream)
6
+ [![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-brightgreen.svg)](https://www.python.org/)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/martianacademy/deimos-stream/blob/main/LICENSE)
8
+
9
+ **DeimosStream** is a universal low-VRAM **Sparse Mixture-of-Experts (MoE) LLM streaming engine** — the language-model twin to [**PhobosStream**](https://github.com/martianacademy/phobos-stream) — built to run large Sparse MoE models (**`OLMoE`**, **`Qwen2/3-MoE`**, **`Mixtral`**, **`DeepSeek-MoE`**) inside a tiny, strictly bounded GPU memory footprint with **cryptographic Merkle proof verification** on every cold expert page streamed from NVMe SSD.
10
+
11
+ By combining a **16 KB Page-Aligned 4-Bit Cryptographic Merkle Store (`DEIMIDX2`)**, a **Pre-Allocated Unified-Memory `PagedExpertArena`** (`mx.gather_qmm`), **Zero-GIL C++17 Cross-Layer Residual Lookahead**, and **Cache-Aware Miss-Only Nucleus Dynamic-K**, DeimosStream cuts Peak Metal GPU Memory on a real **13.20 GiB (`6.92B`) Sparse MoE model from `13,613.4 MiB` down to `1,086.8–1,518.8 MiB` (`88.8%–92.0%` VRAM reduction)** while sustaining **`45.5–57.4 tok/s`** with **zero prefill VRAM spikes** and **no perplexity degradation**.
12
+
13
+ ---
14
+
15
+ ## 📊 Verified Empirical Benchmarks (`OLMoE-1B-7B`, 6.92B Params / 13.20 GiB FP16)
16
+
17
+ *Measured end-to-end on Apple Silicon (`M4 Max` Metal GPU, real `F_NOCACHE` random NVMe `pread` measured at `2.03–2.96 GiB/s`) on `allenai/OLMoE-1B-7B-0125-Instruct` (`16 layers × 64 experts = 1,024` SwiGLU experts, `Top-8` active per token):*
18
+
19
+ | Execution Mode | Active / Peak Metal VRAM | Peak VRAM Saved | Process RSS | Expert Cache Hit Rate | Decode Speed | Held-Out Quality (PPL ↓) |
20
+ | :--- | :---: | :---: | :---: | :---: | :---: | :--- |
21
+ | **1. Monolithic FP16 Baseline** *(All weights in GPU)* | `13,261.5` / **13,613.4 MiB** | `0.0%` | `13,680+ MiB` | `100.0%` *(Pinned)* | `142.24 tok/s` | `6.4182` *(FP16 Ref)* |
22
+ | **2. Naive On-Demand FP16 Streaming** *(`mx.stack`)* | `1,709.4` / **4,567.9 MiB** *(+2.85 GiB spike)* | `66.4%` | `~4,600 MiB` | `19.0%` | `4.71 tok/s` | `6.4182` |
23
+ | **3. DeimosStream Full-Pinned Q4 (`--slots 64`)** | `4,108.8` / **4,154.5 MiB** | **`69.5%`** | `~4,220 MiB` | `100.0%` *(Pinned)* | **251.48 tok/s** *(1.77x)* | **6.2229** |
24
+ | **4. DeimosStream Low-VRAM Champion (`--slots 16 --tau 0.85`)** | `1,516.8` / **1,518.8 MiB** *(0 spike)* | **`88.8%`** | **1,309.8 MiB** | **92.2%–93.3%** | **55.62 tok/s** *(57.4 @ τ=0.78)* | **6.2285** |
25
+ | **5. DeimosStream Ultra-Low `1.06 GiB` (`--slots 8 --tau 0.85`)** | `1,084.8` / **1,086.8 MiB** *(0 spike)* | **`92.0%`** | **881.7 MiB** | **88.4%** | **45.53 tok/s** | **6.2541** *(0.0 diff @ τ=1.0)* |
26
+
27
+ * **Bit-Exact Streaming Guarantee (`--tau 1.0`)**: Running `DeimosPagedMoEEngine(..., slots_per_layer=8, miss_tail_tau=1.0)` produces **`0.00000000` (`0.0`) maximum logit difference** and **100% identical greedy tokens** against Full-64-Slot Pinned Q4 despite continuous LFU+LRU page evictions.
28
+ * **Warm Multi-Turn Merkle KV-Prefix Cache**: Across full process restarts on a 54-token prompt, `MerkleKVPrefixCache` verifies and restores `48/54` cached prompt tokens in `O(1)` via `DEIMIDX2` Robin-Hood hashing, cutting cold-restart TTFT **`4.29x` (`1,014.5 ms -> 236.4 ms`)** with exact output parity.
29
+
30
+ ---
31
+
32
+ ## 🏛️ System Architecture
33
+
34
+ ```mermaid
35
+ flowchart TD
36
+ subgraph STORE["DEIMIDX2 Cryptographic Merkle Store (NVMe SSD)"]
37
+ IDX["merkle_tree.idx (320B Header + Flat XOR Tree + Robin-Hood KV Table)"]
38
+ CAS[("cas_experts_q4.bin (16 KB Page-Aligned Q4 Expert Leaves)")]
39
+ CORE["shared_core.bin + embed_tokens.bin + lm_head_int8.bin"]
40
+ end
41
+
42
+ subgraph PREFILL["Stage 1: Chained SHA-256 Merkle KV-Prefix Cache"]
43
+ TOK["Prompt Token IDs"] --> KVH["16-Token Block Hash Chain from model_merkle_root"]
44
+ KVH -->|"Robin-Hood Hit"| KVR["Restore .safetensors KV Blocks (4.29x Faster TTFT)"]
45
+ end
46
+
47
+ subgraph LAYER["Stage 2: Per-Layer Paged MoE Execution + Residual Lookahead"]
48
+ KVR --> ATTN["UniversalAttention (Fused MHA/GQA + Full/Per-Head/None QK-Norm)"]
49
+ ATTN --> LA["Residual Lookahead: W_gate^(l+1) * RMSNorm(h^(l)) (83.9% Recall)"]
50
+ LA -.->|"Zero-GIL C++17 Async Worker (F_NOCACHE pread + CC_SHA256)"| NEXT["Disjoint PagedExpertArena[l+1]"]
51
+ CAS ==>|"Cold Leaf DMA + Tier-2 SHA-256 Proof"| NEXT
52
+ ATTN --> DYNK["Cache-Aware Miss-Only Nucleus Dynamic-K (tau=0.85)"]
53
+ DYNK --> QMM["Zero-Copy mx.gather_qmm on PagedExpertArena[l]"]
54
+ end
55
+ ```
56
+
57
+ ### Core Architectural Mechanisms
58
+
59
+ 1. **Universal `DEIMIDX2` Cryptographic Merkle Index (`deimos_merkle.mm`)**:
60
+ - Supports arbitrary `(num_layers, num_experts, vocab_size)` topologies (non-power-of-2 leaf counts automatically padded to `tree_leaf_cap = 2^⌈log2(L·E)⌉`).
61
+ - **Tier-1 Startup Proof**: Verifies all leaf-to-root XOR sibling paths and the 4-branch `model_merkle_root` (`embedding || shared_core || expert_tree || lm_head`) in **`2.08 ms`** (`3.1 ns` `O(1)` C-struct lookup).
62
+ - **Tier-2 Cold Leaf Proof**: Hardware-accelerated ARMv8 `CC_SHA256` verifies every cold expert's raw 4-bit payload bytes on NVMe `pread`/`mmap` before weights enter GPU memory, raising `DeimosMerkleIntegrityError` on even a **1-bit disk flip**.
63
+ 2. **Pre-Allocated Unified-Memory `PagedExpertArena` (`deimos_arena.mm`)**:
64
+ - Eliminates `mx.stack` allocation spikes by pre-allocating a fixed `[C, ...]` Q4 tensor pool per layer in Apple Silicon Unified Memory.
65
+ - Cache hits execute directly in-place via `mx.gather_qmm(..., rhs_indices=phys_slots)` with **zero intermediate tensor copies**; cache misses overwrite the LFU+LRU victim slot in-place via zero-GIL C++17 `memcpy` + `POSIX_MADV_DONTNEED`.
66
+ 3. **Cross-Layer Residual Lookahead (`83.91%` Top-8 Recall)**:
67
+ - Exploits residual stream continuity ($h^{(l+1)} = h^{(l)} + \Delta_{\text{MoE}}^{(l)} + \Delta_{\text{Attn}}^{(l+1)}$): predicts Layer `l+1` experts using $W_{\text{gate}}^{(l+1)} \cdot \text{RMSNorm}(h_{\text{post-attn}}^{(l)})$ and stages cold `l+1` leaves on a background C++17 worker thread into **disjoint `arena[l+1]`** while the Metal GPU computes `MoE(l)` and `Attention(l+1)` — eliminating **83.6% of synchronous SSD misses** with zero race conditions.
68
+ 4. **Cache-Aware Miss-Only Nucleus Dynamic-K (`--tau`)**:
69
+ - Never drops experts already resident in GPU VRAM (since cache hits cost `<0.05 ms` on Metal). Only skips **low-weight tail SSD misses** beyond `min_k` once cumulative routing mass reaches $\tau$ (`0.85`), rescaling kept weights to preserve layer activation norm.
70
+
71
+ ---
72
+
73
+ ## 📐 Scaling Envelope & Honest Hardware Scope
74
+
75
+ Why Sparse MoE streaming achieves `45–57 tok/s` while dense weight streaming cannot:
76
+ * A **dense** model touches **100%** of its parameters on every single token (`e.g. 14 GB / 3 GB/s ≈ 0.2 tok/s` physics ceiling).
77
+ * A **Sparse MoE** activates only **$k / E$ (`3%–12.5%`)** of expert parameters per token, exhibits strong conversational topic locality (`88%–93%` hit rate in a `12.5%–25%` slot arena), and exposes cross-layer residual predictability (`~84%` lookahead recall).
78
+
79
+ | Sparse MoE Model Class | Original FP16 Size | Q4 `DEIMIDX2` Disk Store | Active Backbone + KV | Paged Arena (`16–25%` Slots) | Total GPU VRAM Needed |
80
+ | :--- | :---: | :---: | :---: | :---: | :---: |
81
+ | **`OLMoE-1B-7B` (6.9B, A1.3B)** *(Verified)* | `13.2 GiB` | `3.38 GiB` | `~0.65 GiB` | `0.43–0.86 GiB` (`8–16/64`) | **`1.08 – 1.52 GiB`** |
82
+ | **`Qwen3-30B-A3B` (30.5B, 128E Top-8)** | `~61 GiB` | `~15.5 GiB` | `~1.6 GiB` | `~2.4 GiB` (`20/128`) | **`~4.0 – 4.5 GiB`** *(8 GB Mac)* |
83
+ | **`Mixtral-8x7B` (46.7B, 8E Top-2)** | `~93 GiB` | `~23.5 GiB` | `~2.1 GiB` | `~3.8 GiB` (`2–3/8`) | **`~5.8 – 6.5 GiB`** *(8–16 GB Mac)* |
84
+ | **`Qwen3-235B-A22B` (235B, 128E Top-8)** | `~470 GiB` | `~118 GiB` | `~8.5 GiB` | `~11.5 GiB` (`16/128`) | **`~20 – 22 GiB`** *(24–32 GB Mac)* |
85
+
86
+ *(Note: `OLMoE-1B-7B` figures are live hardware measurements on M4 Max; larger rows show analytical `DEIMIDX2` Q4 memory footprints from exact tensor dimensions.)*
87
+
88
+ ---
89
+
90
+ ## ⚡ Quick Start
91
+
92
+ ### 1. Install (`PyPI` or Source on macOS Apple Silicon `arm64`)
93
+
94
+ ```bash
95
+ pip install deimos-stream
96
+ ```
97
+
98
+ Or install from source for development:
99
+ ```bash
100
+ git clone https://github.com/martianacademy/deimos-stream.git
101
+ cd deimos-stream
102
+ uv venv --python 3.12 && source .venv/bin/activate
103
+ uv pip install -e ".[dev]"
104
+ pytest -v
105
+ ```
106
+ *(Requires macOS `arm64` with Xcode Command Line Tools `clang++` for automatic `libdeimos_stream.dylib` compilation; `DEIMIDX2` inspection & Merkle verification also compile natively on Linux C++17.)*
107
+
108
+ ### 2. Convert Any `.safetensors` Sparse MoE Checkpoint & Stream Chat
109
+
110
+ Supports HuggingFace & MLX `.safetensors` checkpoints across **`OLMoE`**, **`Qwen2-MoE` / `Qwen3-MoE`** (including GQA, per-head QK-Norm, and `shared_expert`), **`Mixtral`** (`w1/w2/w3`), and **`DeepSeek-MoE`**:
111
+
112
+ ```bash
113
+ # 1. Convert a .safetensors Sparse MoE checkpoint into a 16 KB page-aligned DEIMIDX2 Q4 store:
114
+ deimos-stream convert \
115
+ --model-dir /path/to/OLMoE-1B-7B-0125-Instruct \
116
+ --output-dir ./olmoe_deimos_q4
117
+
118
+ # 2. Cryptographically verify the Tier-1 XOR Merkle tree & all Tier-2 SHA-256 expert leaves:
119
+ deimos-stream inspect --store-dir ./olmoe_deimos_q4 --verify-leaves
120
+
121
+ # 3. Launch interactive Low-VRAM streaming chat (1.52 GiB VRAM @ ~56 tok/s):
122
+ deimos-stream chat --store-dir ./olmoe_deimos_q4 --slots 16 --tau 0.85
123
+
124
+ # Ultra-Low 1.08 GiB VRAM mode (8 slots/layer):
125
+ deimos-stream chat --store-dir ./olmoe_deimos_q4 --slots 8 --tau 0.85
126
+ ```
127
+
128
+ Inside interactive `deimos-stream chat`, switch VRAM budgets and routing thresholds live:
129
+ * `/slots <8|16|32|64>` — hot-rebuild `PagedExpertArena` capacity on the fly
130
+ * `/tau <0.50..1.00>` — adjust Miss-Only Nucleus Dynamic-K (`1.00` = bit-exact Top-K)
131
+ * `/lookahead <on|off>` — toggle C++17 cross-layer Residual Lookahead prefetch
132
+
133
+ ### 3. OpenAI-Compatible API Gateway (`deimos-stream serve`)
134
+
135
+ Expose any `DEIMIDX2` Sparse MoE store as a local OpenAI `/v1/chat/completions` server (streaming SSE + JSON, compatible with the `openai` SDK, Cursor, Continue, OpenCode, and OpenWebUI):
136
+
137
+ ```bash
138
+ deimos-stream serve \
139
+ --store-dir ./olmoe_deimos_q4 \
140
+ --host 127.0.0.1 \
141
+ --port 8080 \
142
+ --slots 16 \
143
+ --tau 0.85 \
144
+ --model-name olmoe-1b-7b-q4
145
+ ```
146
+
147
+ ```bash
148
+ curl http://127.0.0.1:8080/v1/chat/completions \
149
+ -H "Content-Type: application/json" \
150
+ -d '{
151
+ "model": "olmoe-1b-7b-q4",
152
+ "stream": true,
153
+ "max_tokens": 128,
154
+ "messages": [{"role": "user", "content": "Explain Merkle trees in two sentences."}]
155
+ }'
156
+ ```
157
+
158
+ ### 4. Python API (`DeimosPagedMoEEngine`)
159
+
160
+ ```python
161
+ from pathlib import Path
162
+ from deimos_stream import DeimosPagedMoEEngine, convert_safetensors_moe_to_deimos_q4
163
+
164
+ # One-time conversion from HuggingFace / MLX .safetensors:
165
+ store_dir = convert_safetensors_moe_to_deimos_q4(
166
+ source_model_dir=Path("/path/to/moe-checkpoint"),
167
+ output_store_dir=Path("./moe_deimos_q4"),
168
+ )
169
+
170
+ # Run inside a fixed 16-slot/layer Unified-Memory Arena:
171
+ engine = DeimosPagedMoEEngine(
172
+ store_dir=store_dir,
173
+ slots_per_layer=16,
174
+ use_nocache_pread=True,
175
+ enable_lookahead=True,
176
+ miss_tail_tau=0.85, # Set 1.0 for bit-exact parity vs full-pinned Q4
177
+ )
178
+ try:
179
+ metrics = engine.benchmark_generation(
180
+ "<|user|>\nExplain Merkle trees in two sentences.\n<|assistant|>\n",
181
+ max_new_tokens=64,
182
+ )
183
+ print(metrics["generated_text"])
184
+ print(f"Peak VRAM: {metrics['peak_vram_mb']} MiB | Speed: {metrics['decode_tok_per_s']} tok/s")
185
+ finally:
186
+ engine.close()
187
+ ```
188
+
189
+ ---
190
+
191
+ ## 🌌 Martian Academy Streaming Suite
192
+
193
+ * [**PhobosStream**](https://github.com/martianacademy/phobos-stream) — Universal Zero-VRAM **Video & Image Diffusion (`DiT`)** Streaming Engine (`Wan2.1`, `FLUX.1`, `HunyuanVideo`, `Z-Image-Turbo` • `93.9%–95.3%` VRAM saved).
194
+ * [**DeimosStream**](https://github.com/martianacademy/deimos-stream) — Universal Low-VRAM **Sparse MoE & LLM** Merkle-Paged Streaming Engine (`OLMoE`, `Qwen2/3-MoE`, `Mixtral`, `DeepSeek-MoE` • `88.8%–92.0%` VRAM saved).
195
+
196
+ ---
197
+
198
+ ## 📜 License
199
+
200
+ [MIT License](https://github.com/martianacademy/deimos-stream/blob/main/LICENSE) — free for commercial and personal use.
Binary file
@@ -0,0 +1,34 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400" width="400" height="400">
2
+ <rect width="400" height="400" fill="#181110" />
3
+
4
+ <!-- Symmetric Outer Deimos Orbital Stream Arcs -->
5
+ <path d="M 58.9 146.4 A 144 144 0 0 1 206.0 71.4"
6
+ fill="none" stroke="#FFF7F0" stroke-width="24" stroke-linecap="round" />
7
+ <path d="M 328.6 194.0 A 144 144 0 0 1 253.6 341.1"
8
+ fill="none" stroke="#FFF7F0" stroke-width="24" stroke-linecap="round" />
9
+
10
+ <!-- Mars Sphere -->
11
+ <circle cx="186" cy="214" r="102" fill="#EE6A3E" />
12
+
13
+ <!-- Knockout Channels Across Mars -->
14
+ <g fill="none" stroke="#181110" stroke-width="50" stroke-linecap="round" stroke-linejoin="round">
15
+ <path d="M 76 236 L 186 214" />
16
+ <path d="M 164 324 L 186 214" />
17
+ <path d="M 186 214 L 304 96" />
18
+ </g>
19
+ <circle cx="76" cy="236" r="32" fill="#181110" />
20
+ <circle cx="164" cy="324" r="32" fill="#181110" />
21
+ <circle cx="186" cy="214" r="31" fill="#181110" />
22
+ <circle cx="304" cy="96" r="42" fill="#181110" />
23
+
24
+ <!-- Binary Merkle Stream + Paged Leaf Nodes + Deimos Root Moon -->
25
+ <g fill="none" stroke="#FFF7F0" stroke-width="22" stroke-linecap="round" stroke-linejoin="round">
26
+ <path d="M 76 236 L 186 214" />
27
+ <path d="M 164 324 L 186 214" />
28
+ <path d="M 186 214 L 304 96" />
29
+ </g>
30
+ <circle cx="76" cy="236" r="18" fill="#FFF7F0" />
31
+ <circle cx="164" cy="324" r="18" fill="#FFF7F0" />
32
+ <circle cx="186" cy="214" r="17" fill="#FFF7F0" />
33
+ <circle cx="304" cy="96" r="26" fill="#FFF7F0" />
34
+ </svg>