deimos-stream 0.1.0__py3-none-any.whl
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.
- deimos_stream/__init__.py +62 -0
- deimos_stream/__main__.py +6 -0
- deimos_stream/arena.py +485 -0
- deimos_stream/backbone.py +316 -0
- deimos_stream/cli.py +420 -0
- deimos_stream/converter.py +412 -0
- deimos_stream/detokenizer.py +62 -0
- deimos_stream/engine.py +454 -0
- deimos_stream/include/deimos_sha256.h +93 -0
- deimos_stream/include/deimos_stream.h +214 -0
- deimos_stream/kv_cache.py +202 -0
- deimos_stream/merkle_builder.py +445 -0
- deimos_stream/native/deimos_arena.mm +428 -0
- deimos_stream/native/deimos_merkle.mm +486 -0
- deimos_stream/server.py +495 -0
- deimos_stream-0.1.0.dist-info/METADATA +236 -0
- deimos_stream-0.1.0.dist-info/RECORD +20 -0
- deimos_stream-0.1.0.dist-info/WHEEL +4 -0
- deimos_stream-0.1.0.dist-info/entry_points.txt +2 -0
- deimos_stream-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""
|
|
2
|
+
DeimosStream — Universal Low-VRAM Sparse MoE & LLM Merkle-Paged Streaming Engine
|
|
3
|
+
================================================================================
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from deimos_stream.arena import (
|
|
7
|
+
ArenaStats,
|
|
8
|
+
DeimosMerkleBridge,
|
|
9
|
+
DeimosMerkleIntegrityError,
|
|
10
|
+
PagedExpertArena,
|
|
11
|
+
)
|
|
12
|
+
from deimos_stream.converter import (
|
|
13
|
+
convert_safetensors_moe_to_deimos_q4,
|
|
14
|
+
normalize_moe_config,
|
|
15
|
+
)
|
|
16
|
+
from deimos_stream.detokenizer import IncrementalStreamingDetokenizer
|
|
17
|
+
from deimos_stream.engine import BenchmarkMetrics, DeimosPagedMoEEngine
|
|
18
|
+
from deimos_stream.kv_cache import MerkleKVPrefixCache
|
|
19
|
+
from deimos_stream.merkle_builder import (
|
|
20
|
+
PAGE_SIZE,
|
|
21
|
+
build_deimidx2_file,
|
|
22
|
+
compile_deimos_dylib,
|
|
23
|
+
compute_q4_leaf_layout,
|
|
24
|
+
convert_fp16_cas_store_to_q4,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
__version__ = "0.1.0"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def __getattr__(name: str) -> object:
|
|
31
|
+
if name in {"DeimosChatSession", "inspect_store"}:
|
|
32
|
+
from deimos_stream import cli
|
|
33
|
+
|
|
34
|
+
return getattr(cli, name)
|
|
35
|
+
if name == "create_deimos_app":
|
|
36
|
+
from deimos_stream.server import create_deimos_app
|
|
37
|
+
|
|
38
|
+
return create_deimos_app
|
|
39
|
+
raise AttributeError(f"module 'deimos_stream' has no attribute {name!r}")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
__all__ = [
|
|
43
|
+
"PAGE_SIZE",
|
|
44
|
+
"ArenaStats",
|
|
45
|
+
"BenchmarkMetrics",
|
|
46
|
+
"DeimosChatSession",
|
|
47
|
+
"DeimosMerkleBridge",
|
|
48
|
+
"DeimosMerkleIntegrityError",
|
|
49
|
+
"DeimosPagedMoEEngine",
|
|
50
|
+
"IncrementalStreamingDetokenizer",
|
|
51
|
+
"MerkleKVPrefixCache",
|
|
52
|
+
"PagedExpertArena",
|
|
53
|
+
"__version__",
|
|
54
|
+
"build_deimidx2_file",
|
|
55
|
+
"compile_deimos_dylib",
|
|
56
|
+
"compute_q4_leaf_layout",
|
|
57
|
+
"convert_fp16_cas_store_to_q4",
|
|
58
|
+
"convert_safetensors_moe_to_deimos_q4",
|
|
59
|
+
"create_deimos_app",
|
|
60
|
+
"inspect_store",
|
|
61
|
+
"normalize_moe_config",
|
|
62
|
+
]
|
deimos_stream/arena.py
ADDED
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
DeimosStream Pre-Allocated Quantized Expert VRAM Pool (`src/deimos_stream/arena.py`)
|
|
4
|
+
====================================================================================
|
|
5
|
+
Wraps `libdeimos_stream.dylib` (`DeimosMerkleBridge` + C++17 `DeimosArenaManager`):
|
|
6
|
+
- Allocates ONE fixed per-layer 4-bit Expert Pool in Unified GPU Memory.
|
|
7
|
+
- Executes LFU+LRU page mapping, zero-GIL background Residual Lookahead staging,
|
|
8
|
+
and Cache-Aware Miss-Only Nucleus Dynamic-K filtering in native C++17.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import ctypes
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Dict, List, Optional, Tuple, TypedDict
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
|
|
19
|
+
try:
|
|
20
|
+
import mlx.core as mx
|
|
21
|
+
except ImportError:
|
|
22
|
+
mx = None # type: ignore[assignment]
|
|
23
|
+
|
|
24
|
+
from deimos_stream.merkle_builder import (
|
|
25
|
+
compile_deimos_dylib,
|
|
26
|
+
compute_q4_leaf_layout,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class DeimosMerkleIntegrityError(RuntimeError):
|
|
31
|
+
"""Raised when `DEIMIDX2` Tier-1 or Tier-2 cryptographic Merkle verification fails."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class _CStats(ctypes.Structure):
|
|
35
|
+
_fields_ = [
|
|
36
|
+
("xor_proofs_verified", ctypes.c_uint64),
|
|
37
|
+
("byte_proofs_verified", ctypes.c_uint64),
|
|
38
|
+
("dma_slot_stages", ctypes.c_uint64),
|
|
39
|
+
("dma_bytes_staged", ctypes.c_uint64),
|
|
40
|
+
("evictions_issued", ctypes.c_uint64),
|
|
41
|
+
("prefetches_issued", ctypes.c_uint64),
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class _CArenaTelemetry(ctypes.Structure):
|
|
46
|
+
_fields_ = [
|
|
47
|
+
("cache_hits", ctypes.c_uint64),
|
|
48
|
+
("cache_misses", ctypes.c_uint64),
|
|
49
|
+
("evictions", ctypes.c_uint64),
|
|
50
|
+
("lookahead_submitted", ctypes.c_uint64),
|
|
51
|
+
("lookahead_staged", ctypes.c_uint64),
|
|
52
|
+
("lookahead_useful_hits", ctypes.c_uint64),
|
|
53
|
+
("tail_misses_skipped", ctypes.c_uint64),
|
|
54
|
+
("total_experts_evaluated", ctypes.c_uint64),
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class _CHeader(ctypes.Structure):
|
|
59
|
+
_pack_ = 1
|
|
60
|
+
_fields_ = [
|
|
61
|
+
("magic", ctypes.c_char * 8),
|
|
62
|
+
("version", ctypes.c_uint32),
|
|
63
|
+
("num_layers", ctypes.c_uint32),
|
|
64
|
+
("num_experts", ctypes.c_uint32),
|
|
65
|
+
("tree_leaf_cap", ctypes.c_uint32),
|
|
66
|
+
("vocab_size", ctypes.c_uint32),
|
|
67
|
+
("hidden_size", ctypes.c_uint32),
|
|
68
|
+
("intermediate_size", ctypes.c_uint32),
|
|
69
|
+
("quant_bits", ctypes.c_uint32),
|
|
70
|
+
("quant_group_size", ctypes.c_uint32),
|
|
71
|
+
("num_cow_leaves", ctypes.c_uint32),
|
|
72
|
+
("expert_stride_bytes", ctypes.c_uint64),
|
|
73
|
+
("expert_payload_bytes", ctypes.c_uint64),
|
|
74
|
+
("offset_xor_tree", ctypes.c_uint64),
|
|
75
|
+
("offset_expert_table", ctypes.c_uint64),
|
|
76
|
+
("offset_token_table", ctypes.c_uint64),
|
|
77
|
+
("offset_kv_table", ctypes.c_uint64),
|
|
78
|
+
("total_idx_bytes", ctypes.c_uint64),
|
|
79
|
+
("orig_safetensors_bytes", ctypes.c_uint64),
|
|
80
|
+
("base_model_root", ctypes.c_uint8 * 32),
|
|
81
|
+
("active_model_root", ctypes.c_uint8 * 32),
|
|
82
|
+
("embedding_root", ctypes.c_uint8 * 32),
|
|
83
|
+
("shared_core_root", ctypes.c_uint8 * 32),
|
|
84
|
+
("expert_tree_root", ctypes.c_uint8 * 32),
|
|
85
|
+
("output_head_root", ctypes.c_uint8 * 32),
|
|
86
|
+
("kv_table_slots", ctypes.c_uint32),
|
|
87
|
+
("reserved", ctypes.c_uint8 * 12),
|
|
88
|
+
]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class ArenaStats(TypedDict):
|
|
92
|
+
slots_per_layer: int
|
|
93
|
+
total_physical_slots: int
|
|
94
|
+
pool_vram_mb: float
|
|
95
|
+
cache_hits: int
|
|
96
|
+
cache_misses: int
|
|
97
|
+
hit_rate_pct: float
|
|
98
|
+
evictions: int
|
|
99
|
+
lookahead_submitted: int
|
|
100
|
+
lookahead_staged: int
|
|
101
|
+
lookahead_useful_hits: int
|
|
102
|
+
tail_misses_skipped: int
|
|
103
|
+
avg_active_k: float
|
|
104
|
+
xor_proofs_verified: int
|
|
105
|
+
byte_proofs_verified: int
|
|
106
|
+
dma_bytes_staged_mb: float
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class DeimosMerkleBridge:
|
|
110
|
+
"""Typed `ctypes` binding to `libdeimos_stream.dylib` (`DEIMIDX2` C++17 core)."""
|
|
111
|
+
|
|
112
|
+
def __init__(
|
|
113
|
+
self,
|
|
114
|
+
store_dir: Path,
|
|
115
|
+
cas_filename: str = "cas_experts_q4.bin",
|
|
116
|
+
enable_nocache_fd: bool = True,
|
|
117
|
+
):
|
|
118
|
+
dylib_path = compile_deimos_dylib(force=False)
|
|
119
|
+
self.lib = ctypes.CDLL(str(dylib_path))
|
|
120
|
+
self._bind_signatures()
|
|
121
|
+
|
|
122
|
+
self.store_dir: Path = Path(store_dir).resolve()
|
|
123
|
+
self.handle: Optional[int] = self.lib.deimos_open(
|
|
124
|
+
str(self.store_dir).encode("utf-8"),
|
|
125
|
+
cas_filename.encode("utf-8"),
|
|
126
|
+
1 if enable_nocache_fd else 0,
|
|
127
|
+
)
|
|
128
|
+
if not self.handle:
|
|
129
|
+
raise DeimosMerkleIntegrityError(
|
|
130
|
+
f"DEIMIDX2 Tier-1 Merkle verification or mmap init failed at {self.store_dir}"
|
|
131
|
+
)
|
|
132
|
+
hdr = _CHeader()
|
|
133
|
+
rc = self.lib.deimos_get_header(self.handle, ctypes.byref(hdr))
|
|
134
|
+
if rc != 0:
|
|
135
|
+
self.close()
|
|
136
|
+
raise DeimosMerkleIntegrityError(f"Failed to read DEIMIDX2 header (rc={rc})")
|
|
137
|
+
self.header: _CHeader = hdr
|
|
138
|
+
|
|
139
|
+
def _bind_signatures(self) -> None:
|
|
140
|
+
L = self.lib
|
|
141
|
+
L.deimos_open.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int]
|
|
142
|
+
L.deimos_open.restype = ctypes.c_void_p
|
|
143
|
+
L.deimos_close.argtypes = [ctypes.c_void_p]
|
|
144
|
+
L.deimos_close.restype = None
|
|
145
|
+
|
|
146
|
+
L.deimos_get_header.argtypes = [ctypes.c_void_p, ctypes.POINTER(_CHeader)]
|
|
147
|
+
L.deimos_get_header.restype = ctypes.c_int
|
|
148
|
+
L.deimos_verify_leaf.argtypes = [
|
|
149
|
+
ctypes.c_void_p,
|
|
150
|
+
ctypes.c_int,
|
|
151
|
+
ctypes.c_int,
|
|
152
|
+
ctypes.c_int,
|
|
153
|
+
]
|
|
154
|
+
L.deimos_verify_leaf.restype = ctypes.c_int
|
|
155
|
+
L.deimos_get_stats.argtypes = [ctypes.c_void_p, ctypes.POINTER(_CStats)]
|
|
156
|
+
L.deimos_get_stats.restype = None
|
|
157
|
+
|
|
158
|
+
L.deimos_kv_lookup.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_double]
|
|
159
|
+
L.deimos_kv_lookup.restype = ctypes.c_int
|
|
160
|
+
L.deimos_kv_insert.argtypes = [
|
|
161
|
+
ctypes.c_void_p,
|
|
162
|
+
ctypes.c_char_p,
|
|
163
|
+
ctypes.c_char_p,
|
|
164
|
+
ctypes.c_uint32,
|
|
165
|
+
ctypes.c_double,
|
|
166
|
+
ctypes.c_char_p,
|
|
167
|
+
]
|
|
168
|
+
L.deimos_kv_insert.restype = ctypes.c_int
|
|
169
|
+
|
|
170
|
+
L.deimos_arena_create.argtypes = [
|
|
171
|
+
ctypes.c_void_p,
|
|
172
|
+
ctypes.c_int,
|
|
173
|
+
ctypes.c_int,
|
|
174
|
+
ctypes.c_int,
|
|
175
|
+
ctypes.c_size_t,
|
|
176
|
+
ctypes.c_size_t,
|
|
177
|
+
ctypes.c_size_t,
|
|
178
|
+
ctypes.c_size_t,
|
|
179
|
+
ctypes.c_int,
|
|
180
|
+
ctypes.c_int,
|
|
181
|
+
]
|
|
182
|
+
L.deimos_arena_create.restype = ctypes.c_void_p
|
|
183
|
+
L.deimos_arena_destroy.argtypes = [ctypes.c_void_p]
|
|
184
|
+
L.deimos_arena_destroy.restype = None
|
|
185
|
+
|
|
186
|
+
L.deimos_arena_bind_layer_ptrs.argtypes = [
|
|
187
|
+
ctypes.c_void_p,
|
|
188
|
+
ctypes.c_int,
|
|
189
|
+
ctypes.c_void_p,
|
|
190
|
+
ctypes.c_void_p,
|
|
191
|
+
ctypes.c_void_p,
|
|
192
|
+
ctypes.c_void_p,
|
|
193
|
+
ctypes.c_void_p,
|
|
194
|
+
ctypes.c_void_p,
|
|
195
|
+
]
|
|
196
|
+
L.deimos_arena_bind_layer_ptrs.restype = ctypes.c_int
|
|
197
|
+
L.deimos_arena_preload_all.argtypes = [ctypes.c_void_p]
|
|
198
|
+
L.deimos_arena_preload_all.restype = ctypes.c_int
|
|
199
|
+
|
|
200
|
+
L.deimos_arena_resolve_and_prefetch.argtypes = [
|
|
201
|
+
ctypes.c_void_p,
|
|
202
|
+
ctypes.c_int,
|
|
203
|
+
ctypes.POINTER(ctypes.c_int32),
|
|
204
|
+
ctypes.POINTER(ctypes.c_float),
|
|
205
|
+
ctypes.c_int,
|
|
206
|
+
ctypes.c_int,
|
|
207
|
+
ctypes.c_float,
|
|
208
|
+
ctypes.c_int,
|
|
209
|
+
ctypes.c_int,
|
|
210
|
+
ctypes.POINTER(ctypes.c_int32),
|
|
211
|
+
ctypes.c_int,
|
|
212
|
+
ctypes.POINTER(ctypes.c_int32),
|
|
213
|
+
ctypes.POINTER(ctypes.c_float),
|
|
214
|
+
ctypes.POINTER(ctypes.c_int),
|
|
215
|
+
]
|
|
216
|
+
L.deimos_arena_resolve_and_prefetch.restype = ctypes.c_int
|
|
217
|
+
|
|
218
|
+
L.deimos_arena_wait_idle.argtypes = [ctypes.c_void_p]
|
|
219
|
+
L.deimos_arena_wait_idle.restype = None
|
|
220
|
+
L.deimos_arena_get_telemetry.argtypes = [
|
|
221
|
+
ctypes.c_void_p,
|
|
222
|
+
ctypes.POINTER(_CArenaTelemetry),
|
|
223
|
+
]
|
|
224
|
+
L.deimos_arena_get_telemetry.restype = None
|
|
225
|
+
L.deimos_arena_reset_telemetry.argtypes = [ctypes.c_void_p]
|
|
226
|
+
L.deimos_arena_reset_telemetry.restype = None
|
|
227
|
+
|
|
228
|
+
def verify_leaf(self, layer_idx: int, expert_idx: int, verify_bytes: bool = True) -> None:
|
|
229
|
+
rc = self.lib.deimos_verify_leaf(
|
|
230
|
+
self.handle, int(layer_idx), int(expert_idx), 1 if verify_bytes else 0
|
|
231
|
+
)
|
|
232
|
+
if rc != 0:
|
|
233
|
+
raise DeimosMerkleIntegrityError(
|
|
234
|
+
f"Merkle proof failed for L{layer_idx}E{expert_idx} (rc={rc})"
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
def kv_lookup(self, prefix_hash32: bytes, now_ts: float) -> bool:
|
|
238
|
+
return bool(self.lib.deimos_kv_lookup(self.handle, prefix_hash32, float(now_ts)) == 1)
|
|
239
|
+
|
|
240
|
+
def kv_insert(
|
|
241
|
+
self, prefix_hash32: bytes, parent_hash32: bytes, token_end: int, now_ts: float
|
|
242
|
+
) -> Optional[str]:
|
|
243
|
+
evicted_buf = ctypes.create_string_buffer(32)
|
|
244
|
+
rc = self.lib.deimos_kv_insert(
|
|
245
|
+
self.handle, prefix_hash32, parent_hash32, int(token_end), float(now_ts), evicted_buf
|
|
246
|
+
)
|
|
247
|
+
if rc == 1:
|
|
248
|
+
return bytes(evicted_buf.raw).hex()
|
|
249
|
+
return None
|
|
250
|
+
|
|
251
|
+
def get_stats(self) -> Dict[str, int]:
|
|
252
|
+
st = _CStats()
|
|
253
|
+
if self.handle:
|
|
254
|
+
self.lib.deimos_get_stats(self.handle, ctypes.byref(st))
|
|
255
|
+
return {
|
|
256
|
+
"xor_proofs_verified": int(st.xor_proofs_verified),
|
|
257
|
+
"byte_proofs_verified": int(st.byte_proofs_verified),
|
|
258
|
+
"dma_slot_stages": int(st.dma_slot_stages),
|
|
259
|
+
"dma_bytes_staged": int(st.dma_bytes_staged),
|
|
260
|
+
"evictions_issued": int(st.evictions_issued),
|
|
261
|
+
"prefetches_issued": int(st.prefetches_issued),
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
def close(self) -> None:
|
|
265
|
+
if self.handle:
|
|
266
|
+
self.lib.deimos_close(self.handle)
|
|
267
|
+
self.handle = None
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
class PagedExpertArena:
|
|
271
|
+
"""
|
|
272
|
+
Fixed-VRAM Per-Layer Q4 Expert Pool backed by C++17 `DeimosArenaManager`
|
|
273
|
+
for O(1) page mapping, zero-GIL Residual Lookahead prefetching, and Miss-Only Dynamic-K.
|
|
274
|
+
"""
|
|
275
|
+
|
|
276
|
+
def __init__(
|
|
277
|
+
self,
|
|
278
|
+
bridge: DeimosMerkleBridge,
|
|
279
|
+
slots_per_layer: int = 16,
|
|
280
|
+
verify_merkle_on_cold: bool = True,
|
|
281
|
+
use_nocache_pread: bool = False,
|
|
282
|
+
):
|
|
283
|
+
self.bridge: DeimosMerkleBridge = bridge
|
|
284
|
+
h = bridge.header
|
|
285
|
+
self.num_layers: int = int(h.num_layers)
|
|
286
|
+
self.num_experts: int = int(h.num_experts)
|
|
287
|
+
self.hidden_size: int = int(h.hidden_size)
|
|
288
|
+
self.intermediate_size: int = int(h.intermediate_size)
|
|
289
|
+
self.group_size: int = int(h.quant_group_size)
|
|
290
|
+
self.slots_per_layer: int = max(1, min(self.num_experts, int(slots_per_layer)))
|
|
291
|
+
self.is_fully_pinned: bool = self.slots_per_layer == self.num_experts
|
|
292
|
+
self.use_nocache_pread: bool = bool(use_nocache_pread)
|
|
293
|
+
|
|
294
|
+
layout = compute_q4_leaf_layout(
|
|
295
|
+
self.hidden_size, self.intermediate_size, group_size=self.group_size
|
|
296
|
+
)
|
|
297
|
+
self.payload_bytes: int = layout["payload_bytes"]
|
|
298
|
+
|
|
299
|
+
C = self.slots_per_layer
|
|
300
|
+
gu_out = 2 * self.intermediate_size
|
|
301
|
+
self.gu_w: List[mx.array] = [
|
|
302
|
+
mx.zeros((C, gu_out, self.hidden_size // 8), dtype=mx.uint32)
|
|
303
|
+
for _ in range(self.num_layers)
|
|
304
|
+
]
|
|
305
|
+
self.gu_s: List[mx.array] = [
|
|
306
|
+
mx.zeros((C, gu_out, self.hidden_size // self.group_size), dtype=mx.float16)
|
|
307
|
+
for _ in range(self.num_layers)
|
|
308
|
+
]
|
|
309
|
+
self.gu_b: List[mx.array] = [
|
|
310
|
+
mx.zeros((C, gu_out, self.hidden_size // self.group_size), dtype=mx.float16)
|
|
311
|
+
for _ in range(self.num_layers)
|
|
312
|
+
]
|
|
313
|
+
self.dn_w: List[mx.array] = [
|
|
314
|
+
mx.zeros((C, self.hidden_size, self.intermediate_size // 8), dtype=mx.uint32)
|
|
315
|
+
for _ in range(self.num_layers)
|
|
316
|
+
]
|
|
317
|
+
self.dn_s: List[mx.array] = [
|
|
318
|
+
mx.zeros(
|
|
319
|
+
(C, self.hidden_size, self.intermediate_size // self.group_size), dtype=mx.float16
|
|
320
|
+
)
|
|
321
|
+
for _ in range(self.num_layers)
|
|
322
|
+
]
|
|
323
|
+
self.dn_b: List[mx.array] = [
|
|
324
|
+
mx.zeros(
|
|
325
|
+
(C, self.hidden_size, self.intermediate_size // self.group_size), dtype=mx.float16
|
|
326
|
+
)
|
|
327
|
+
for _ in range(self.num_layers)
|
|
328
|
+
]
|
|
329
|
+
mx.eval(self.gu_w, self.gu_s, self.gu_b, self.dn_w, self.dn_s, self.dn_b)
|
|
330
|
+
mx.synchronize()
|
|
331
|
+
|
|
332
|
+
self.arena_handle: Optional[int] = self.bridge.lib.deimos_arena_create(
|
|
333
|
+
self.bridge.handle,
|
|
334
|
+
self.num_layers,
|
|
335
|
+
self.num_experts,
|
|
336
|
+
self.slots_per_layer,
|
|
337
|
+
layout["gu_w_bytes"],
|
|
338
|
+
layout["gu_s_bytes"],
|
|
339
|
+
layout["dn_w_bytes"],
|
|
340
|
+
layout["dn_s_bytes"],
|
|
341
|
+
1 if verify_merkle_on_cold else 0,
|
|
342
|
+
1 if use_nocache_pread else 0,
|
|
343
|
+
)
|
|
344
|
+
if not self.arena_handle:
|
|
345
|
+
raise RuntimeError("Failed to initialize C++17 DeimosArenaManager")
|
|
346
|
+
|
|
347
|
+
self._views_keepalive: List[Tuple[np.ndarray, ...]] = []
|
|
348
|
+
for l_idx in range(self.num_layers):
|
|
349
|
+
vw = np.frombuffer(memoryview(self.gu_w[l_idx]), dtype=np.uint8)
|
|
350
|
+
vs = np.frombuffer(memoryview(self.gu_s[l_idx]), dtype=np.uint8)
|
|
351
|
+
vb = np.frombuffer(memoryview(self.gu_b[l_idx]), dtype=np.uint8)
|
|
352
|
+
vdw = np.frombuffer(memoryview(self.dn_w[l_idx]), dtype=np.uint8)
|
|
353
|
+
vds = np.frombuffer(memoryview(self.dn_s[l_idx]), dtype=np.uint8)
|
|
354
|
+
vdb = np.frombuffer(memoryview(self.dn_b[l_idx]), dtype=np.uint8)
|
|
355
|
+
self._views_keepalive.append((vw, vs, vb, vdw, vds, vdb))
|
|
356
|
+
self.bridge.lib.deimos_arena_bind_layer_ptrs(
|
|
357
|
+
self.arena_handle,
|
|
358
|
+
l_idx,
|
|
359
|
+
int(vw.ctypes.data),
|
|
360
|
+
int(vs.ctypes.data),
|
|
361
|
+
int(vb.ctypes.data),
|
|
362
|
+
int(vdw.ctypes.data),
|
|
363
|
+
int(vds.ctypes.data),
|
|
364
|
+
int(vdb.ctypes.data),
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
if self.is_fully_pinned:
|
|
368
|
+
rc = self.bridge.lib.deimos_arena_preload_all(self.arena_handle)
|
|
369
|
+
if rc == -2:
|
|
370
|
+
raise DeimosMerkleIntegrityError("Corrupted Q4 Merkle leaf detected during preload!")
|
|
371
|
+
if rc != 0:
|
|
372
|
+
raise RuntimeError(f"deimos_arena_preload_all failed (rc={rc})")
|
|
373
|
+
|
|
374
|
+
def resolve_and_prefetch(
|
|
375
|
+
self,
|
|
376
|
+
layer_idx: int,
|
|
377
|
+
routed_ids_np: np.ndarray,
|
|
378
|
+
routed_scores_np: np.ndarray,
|
|
379
|
+
miss_tail_tau: float = 1.0,
|
|
380
|
+
min_k: int = 4,
|
|
381
|
+
next_layer_idx: int = -1,
|
|
382
|
+
next_pred_ids_np: Optional[np.ndarray] = None,
|
|
383
|
+
) -> Tuple[np.ndarray, np.ndarray]:
|
|
384
|
+
"""
|
|
385
|
+
Single C++17 call joining `layer_idx` lookahead, staging unpredicted misses,
|
|
386
|
+
filtering cold tail misses (`miss_tail_tau`), and dispatching `next_layer_idx` lookahead.
|
|
387
|
+
"""
|
|
388
|
+
num_tokens, top_k = routed_ids_np.shape
|
|
389
|
+
ids_c = np.ascontiguousarray(routed_ids_np, dtype=np.int32)
|
|
390
|
+
sc_c = np.ascontiguousarray(routed_scores_np, dtype=np.float32)
|
|
391
|
+
|
|
392
|
+
out_phys = np.empty((num_tokens, top_k), dtype=np.int32)
|
|
393
|
+
out_sc = np.empty((num_tokens, top_k), dtype=np.float32)
|
|
394
|
+
eff_k = ctypes.c_int(top_k)
|
|
395
|
+
|
|
396
|
+
pred_ptr = None
|
|
397
|
+
pred_cnt = 0
|
|
398
|
+
pred_c: Optional[np.ndarray] = None
|
|
399
|
+
if next_layer_idx >= 0 and next_pred_ids_np is not None:
|
|
400
|
+
pred_c = np.ascontiguousarray(next_pred_ids_np.reshape(-1), dtype=np.int32)
|
|
401
|
+
pred_ptr = pred_c.ctypes.data_as(ctypes.POINTER(ctypes.c_int32))
|
|
402
|
+
pred_cnt = int(pred_c.size)
|
|
403
|
+
|
|
404
|
+
rc = self.bridge.lib.deimos_arena_resolve_and_prefetch(
|
|
405
|
+
self.arena_handle,
|
|
406
|
+
int(layer_idx),
|
|
407
|
+
ids_c.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)),
|
|
408
|
+
sc_c.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
|
|
409
|
+
int(num_tokens),
|
|
410
|
+
int(top_k),
|
|
411
|
+
float(miss_tail_tau),
|
|
412
|
+
int(min_k),
|
|
413
|
+
int(next_layer_idx),
|
|
414
|
+
pred_ptr,
|
|
415
|
+
pred_cnt,
|
|
416
|
+
out_phys.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)),
|
|
417
|
+
out_sc.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
|
|
418
|
+
ctypes.byref(eff_k),
|
|
419
|
+
)
|
|
420
|
+
if rc == -2:
|
|
421
|
+
raise DeimosMerkleIntegrityError(
|
|
422
|
+
f"Corrupted Q4 Merkle leaf rejected in layer {layer_idx}!"
|
|
423
|
+
)
|
|
424
|
+
if rc != 0:
|
|
425
|
+
raise RuntimeError(f"deimos_arena_resolve_and_prefetch failed (rc={rc})")
|
|
426
|
+
|
|
427
|
+
k_final = int(eff_k.value)
|
|
428
|
+
if k_final < top_k and num_tokens == 1:
|
|
429
|
+
return out_phys[:, :k_final], out_sc[:, :k_final]
|
|
430
|
+
return out_phys, out_sc
|
|
431
|
+
|
|
432
|
+
def wait_idle(self) -> None:
|
|
433
|
+
if self.arena_handle:
|
|
434
|
+
self.bridge.lib.deimos_arena_wait_idle(self.arena_handle)
|
|
435
|
+
|
|
436
|
+
def reset_telemetry(self) -> None:
|
|
437
|
+
if self.arena_handle:
|
|
438
|
+
self.bridge.lib.deimos_arena_reset_telemetry(self.arena_handle)
|
|
439
|
+
|
|
440
|
+
def pool_vram_mb(self) -> float:
|
|
441
|
+
return (self.num_layers * self.slots_per_layer * self.payload_bytes) / (1024.0 * 1024.0)
|
|
442
|
+
|
|
443
|
+
def get_stats(self, nominal_top_k: int = 8) -> ArenaStats:
|
|
444
|
+
c_st = self.bridge.get_stats()
|
|
445
|
+
a_st = _CArenaTelemetry()
|
|
446
|
+
if self.arena_handle:
|
|
447
|
+
self.bridge.lib.deimos_arena_get_telemetry(
|
|
448
|
+
self.arena_handle, ctypes.byref(a_st)
|
|
449
|
+
)
|
|
450
|
+
hits = int(a_st.cache_hits)
|
|
451
|
+
misses = int(a_st.cache_misses)
|
|
452
|
+
tot = hits + misses
|
|
453
|
+
skipped = int(a_st.tail_misses_skipped)
|
|
454
|
+
eval_e = int(a_st.total_experts_evaluated)
|
|
455
|
+
denom_calls = (eval_e + skipped) / max(1, nominal_top_k)
|
|
456
|
+
avg_k = (eval_e / denom_calls) if denom_calls > 0 else float(nominal_top_k)
|
|
457
|
+
return {
|
|
458
|
+
"slots_per_layer": self.slots_per_layer,
|
|
459
|
+
"total_physical_slots": self.num_layers * self.slots_per_layer,
|
|
460
|
+
"pool_vram_mb": round(self.pool_vram_mb(), 2),
|
|
461
|
+
"cache_hits": hits,
|
|
462
|
+
"cache_misses": misses,
|
|
463
|
+
"hit_rate_pct": round(100.0 * hits / tot, 2) if tot > 0 else 100.0,
|
|
464
|
+
"evictions": int(a_st.evictions),
|
|
465
|
+
"lookahead_submitted": int(a_st.lookahead_submitted),
|
|
466
|
+
"lookahead_staged": int(a_st.lookahead_staged),
|
|
467
|
+
"lookahead_useful_hits": int(a_st.lookahead_useful_hits),
|
|
468
|
+
"tail_misses_skipped": skipped,
|
|
469
|
+
"avg_active_k": round(avg_k, 2),
|
|
470
|
+
"xor_proofs_verified": c_st["xor_proofs_verified"],
|
|
471
|
+
"byte_proofs_verified": c_st["byte_proofs_verified"],
|
|
472
|
+
"dma_bytes_staged_mb": round(c_st["dma_bytes_staged"] / (1024.0 * 1024.0), 2),
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
def close(self) -> None:
|
|
476
|
+
if self.arena_handle:
|
|
477
|
+
self.bridge.lib.deimos_arena_destroy(self.arena_handle)
|
|
478
|
+
self.arena_handle = None
|
|
479
|
+
self._views_keepalive.clear()
|
|
480
|
+
self.gu_w.clear()
|
|
481
|
+
self.gu_s.clear()
|
|
482
|
+
self.gu_b.clear()
|
|
483
|
+
self.dn_w.clear()
|
|
484
|
+
self.dn_s.clear()
|
|
485
|
+
self.dn_b.clear()
|