Sadanie commited on
Commit
cedee5b
·
0 Parent(s):

Inkling 2 Mini MS-MoE

Browse files
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
NOTICE ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ This repository contains add-on files for Inkling 2 Mini (thinkingmachines/Inkling-2-Mini), which is
2
+ Copyright Thinking Machines and licensed under the Apache License, Version 2.0.
3
+
4
+ embed_f16.npy is the token embedding table of Inkling 2 Mini, converted to fp16 and otherwise unchanged.
5
+ router.safetensors and attention_lora.safetensors are fine-tuned from weights of Inkling 2 Mini.
6
+
7
+ The receptionist uses Qwen3-Embedding-0.6B (Qwen/Qwen3-Embedding-0.6B, Apache License 2.0), which is
8
+ downloaded separately.
9
+
10
+ The files in this repository are licensed under the Apache License, Version 2.0:
11
+ https://www.apache.org/licenses/LICENSE-2.0
README.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model: thinkingmachines/Inkling-2-Mini
4
+ base_model_relation: adapter
5
+ library_name: mlx
6
+ pipeline_tag: text-generation
7
+ language: en
8
+ tags:
9
+ - mlx
10
+ - apple-silicon
11
+ - mixture-of-experts
12
+ - inkling
13
+ - lora
14
+ - memory-sparse-moe
15
+ ---
16
+
17
+ # Inkling 2 Mini: 2x memory efficient
18
+
19
+ Inkling 2 Mini is 17.3 GB at 4-bit, so it doesn't fit on a 16 GB Mac. With the files in this repository it runs in about 9 GB at about 10 tokens per second on an M1, and scores within 2.5 points of the full model on code, math and knowledge tests.
20
+
21
+ A mixture-of-experts model is compute-efficient: each token only runs through a few experts (8 of 128 per layer here), not through the whole network. It is not memory-efficient, because all 128 are still held in memory. That isn't necessary: an answer mostly uses a subset of the experts, and fine-tuning makes the model work even better with only that subset.
22
+
23
+ **Memory-Sparse MoE (MS-MoE)** is the approach used here: keep only the experts a question needs in memory. A small prediction model (the receptionist) reads the question first and picks 64 experts per layer. Only those are loaded. The router and a small attention adapter are fine-tuned so the model works with that team. The experts themselves are unchanged.
24
+
25
+ Full write-up: [Mixture-of-experts models are built wrong for laptops and local hardware](https://medium.com/@rotteveeladan/mixture-of-experts-models-are-built-wrong-for-laptops-and-local-hardware-9a45165d65d6)
26
+
27
+ ## Results
28
+
29
+ Inkling 2 Mini with half of the experts in memory (64 of 128 per layer), greedy decoding, thinking effort 0.
30
+
31
+ | Test | Full model | Ours, no fine-tuning | **MS-MoE (ours)** |
32
+ |---|---|---|---|
33
+ | Code, MBPP (257 problems) | 91.4% | 73.2% | **89.1%** |
34
+ | Math, GSM8K (1,319 problems) | 95.4% | 92.6% | **95.3%** |
35
+ | Knowledge, MMLU (3,000 questions) | 78.0% | 75.4% | **76.0%** |
36
+
37
+ On a 16 GB M1 MacBook: 9.0 GB peak memory, about 10 tokens per second, about 20 seconds to load the experts for the first question.
38
+
39
+ ## Usage
40
+
41
+ You need an Apple Silicon Mac with 16 GB of memory and about 20 GB of free disk space.
42
+
43
+ ```bash
44
+ pip install "mlx==0.32.4" "mlx-lm @ git+https://github.com/ml-explore/mlx-lm.git@0c4c99192230f1943dd468d297f0b8a64ae7b7c2" transformers safetensors numpy huggingface_hub
45
+ hf download Sadanie/Inkling-2-Mini-Memory-Sparse-MoE --local-dir inkling-ms-moe
46
+ cd inkling-ms-moe
47
+ python run.py "Write a Python function that checks if a word is a palindrome."
48
+ python run.py --chat
49
+ ```
50
+
51
+ The 4-bit base model ([mlx-community/Inkling-2-Mini-4bit](https://huggingface.co/mlx-community/Inkling-2-Mini-4bit), 17 GB) is downloaded on first use. If you already have it, set `INKLING_DIR=/path/to/Inkling-2-Mini-4bit`. The pinned mlx-lm commit is the one that adds Inkling support.
52
+
53
+ `python run.py --check` compares the experts picked on your Mac with reference picks. It should report about 99%.
54
+
55
+ Close other heavy apps first. The script checks free memory and warns you if there isn't enough.
56
+
57
+ ## Files
58
+
59
+ - `run.py`: the program. It picks the experts, loads only those, and answers.
60
+ - `receptionist.safetensors`: the prediction model that picks the experts. A small network on top of [Qwen3-Embedding-0.6B](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B) and Inkling's own token embeddings.
61
+ - `router.safetensors`: fine-tuned router weights for all 24 layers.
62
+ - `attention_lora.safetensors`: fine-tuned LoRA (rank 16) on the attention projections.
63
+ - `expert_prior.npy`, `meta.json`: tie-breaks and settings for the receptionist, plus the reference picks for `--check`.
64
+ - `embed_f16.npy`: Inkling 2 Mini's token embedding table in fp16, used by the receptionist (0.9 GB, unchanged from the original model).
65
+
66
+ ## How MS-MoE was applied to Inkling
67
+
68
+ - The full model answered 18,271 questions (code, math, science, general chat, several languages), and we recorded which experts each answer used.
69
+ - The receptionist was trained to predict that from the question alone. Its 64 picks per layer cover about 90% of the expert use of an answer.
70
+ - The router and the attention LoRA were then fine-tuned for two epochs with the team restricted to the receptionist's picks, using the full model's outputs as the target. The expert weights were frozen.
71
+
72
+ In chat, each new message gets its own picks, mixed half and half with the picks so far, so only a few experts are swapped between messages.
73
+
74
+ ## Limits
75
+
76
+ - Mac only for now (MLX).
77
+
78
+ ## Credits
79
+
80
+ Inkling 2 Mini is made by [Thinking Machines](https://huggingface.co/thinkingmachines/Inkling-2-Mini) and released under Apache 2.0. The 4-bit MLX conversion is from mlx-community. This repository adds files on top of that model and does not change its expert weights.
attention_lora.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:37d0b189aa005d2c1229fc01d2a85be1be628d7b0127af4e9a9651d63e981c58
3
+ size 39153544
config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "method": "memory-sparse-moe",
3
+ "base_model": "thinkingmachines/Inkling-2-Mini",
4
+ "base_model_mlx": "mlx-community/Inkling-2-Mini-4bit",
5
+ "layers": 24,
6
+ "experts_per_layer": 128,
7
+ "experts_kept_per_layer": 64,
8
+ "experts_per_token": 8,
9
+ "selector_text_encoder": "Qwen/Qwen3-Embedding-0.6B",
10
+ "lora_rank": 16,
11
+ "lora_scale": 2.0
12
+ }
embed_f16.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0593a73c8eade24e23b21b294c41b5e3b3867f4cd508c8154c090b135f3740ab
3
+ size 926318720
expert_prior.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:adcae8f150d1b51712208aaa2f1987870bf9e2ef01297b50986ef19b7ad00ad5
3
+ size 12416
meta.json ADDED
The diff for this file is too large to render. See raw diff
 
receptionist.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1a3d10bdea00b4919f938d3e8a441ef3c64647b178e5fa3d0efb868d289d7118
3
+ size 30456416
router.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fbb7210cceb3abb4cb8ce9994a16926d182752acac3c5a3ce142341d45de3030
3
+ size 28313784
run.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Inkling 2 Mini on a 16 GB Apple Silicon Mac, with only half of its experts in memory.
2
+
3
+ python run.py "your question" # one question
4
+ python run.py --chat # chat (the team of experts follows the conversation)
5
+ python run.py --check # check the install: compares this Mac's expert picks with reference picks
6
+
7
+ How it works:
8
+ 1. The receptionist reads the question (Qwen3-Embedding-0.6B + Inkling's own word embeddings -> small network)
9
+ and scores all 128 experts in each of the 24 layers. The top 64 per layer form the team.
10
+ 2. Only the team's expert weights are read from disk. The other experts are never loaded.
11
+ 3. The router uses fine-tuned weights and may only choose team members, and the attention layers get a small
12
+ fine-tuned adapter (LoRA). Then the model answers as usual.
13
+
14
+ The 4-bit base model (mlx-community/Inkling-2-Mini-4bit, 17 GB) is downloaded on first use. To use a copy you
15
+ already have, set INKLING_DIR=/path/to/Inkling-2-Mini-4bit.
16
+ """
17
+ import argparse
18
+ import gc
19
+ import json
20
+ import os
21
+ import struct
22
+ import sys
23
+ import time
24
+ from concurrent.futures import ThreadPoolExecutor
25
+
26
+ import mlx.core as mx
27
+ import mlx.nn as nn
28
+ import numpy as np
29
+ from safetensors.numpy import load_file
30
+
31
+ HERE = os.path.dirname(os.path.abspath(__file__))
32
+ BASE = "mlx-community/Inkling-2-Mini-4bit"
33
+ MODEL_DIR = os.environ.get("INKLING_DIR", "")
34
+ PIECES = HERE
35
+ READER = "Qwen/Qwen3-Embedding-0.6B"
36
+ KEEP = 64
37
+ CHUNK = 16 << 20
38
+ DTYPES = {"U32": np.uint32, "U8": np.uint8, "F32": np.float32, "F16": np.float16}
39
+ LORA_SCALE = 2.0
40
+ LORA_NAMES = {"q_proj.linear": "q_proj", "k_proj.linear": "k_proj", "v_proj.linear": "v_proj",
41
+ "relative_position_bias.linear": "r_proj", "o_proj.linear": "o_proj", "o_proj.gate_proj": "gate_proj"}
42
+
43
+
44
+ def gb(x):
45
+ return f"{x / 1e9:.1f} GB"
46
+
47
+
48
+ def base_model_dir():
49
+ """Folder with the 4-bit base model: $INKLING_DIR if set, otherwise downloaded from the Hub (17 GB, once)."""
50
+ global MODEL_DIR
51
+ if not MODEL_DIR:
52
+ from huggingface_hub import snapshot_download
53
+ print(f"base model: {BASE} (downloaded on first use, 17 GB)")
54
+ MODEL_DIR = snapshot_download(BASE)
55
+ return MODEL_DIR
56
+
57
+
58
+ class Receptionist:
59
+ def __init__(self):
60
+ meta = json.load(open(os.path.join(PIECES, "meta.json")))
61
+ self.feature, self.L, self.E = meta["feature"], meta["L"], meta["E"]
62
+ assert self.feature == "qwen+tok", self.feature
63
+ w = load_file(os.path.join(PIECES, "receptionist.safetensors"))
64
+ self.w = {k: mx.array(v) for k, v in w.items()}
65
+ self.glob = np.load(os.path.join(PIECES, "expert_prior.npy"))
66
+ self.meta = meta
67
+
68
+ def read_questions(self, texts, trunc="right"):
69
+ """Qwen3-Embedding: last token of the last layer, normalised."""
70
+ from mlx_lm.models import qwen3
71
+ if not hasattr(self, "_reader"):
72
+ from huggingface_hub import snapshot_download
73
+ from transformers import AutoTokenizer
74
+ pats = ["*.json", "*.safetensors", "*.txt"]
75
+ try:
76
+ path = snapshot_download(READER, allow_patterns=pats, local_files_only=True)
77
+ except Exception:
78
+ path = snapshot_download(READER, allow_patterns=pats)
79
+ self._reader = (AutoTokenizer.from_pretrained(path, padding_side="left", truncation_side=trunc), path)
80
+ tok, path = self._reader
81
+ model = qwen3.Model(qwen3.ModelArgs.from_dict(json.load(open(os.path.join(path, "config.json")))))
82
+ w = {}
83
+ for f in sorted(os.listdir(path)):
84
+ if f.endswith(".safetensors"):
85
+ w.update(mx.load(os.path.join(path, f)))
86
+ model.load_weights([(k if k.startswith("model.") else f"model.{k}", v) for k, v in w.items()], strict=False)
87
+ out = []
88
+ for t in texts:
89
+ ids = tok(t, truncation=True, max_length=512)["input_ids"]
90
+ h = model.model(mx.array([ids]))[0, -1].astype(mx.float32)
91
+ out.append(h / mx.linalg.norm(h))
92
+ out = mx.stack(out)
93
+ mx.eval(out)
94
+ del model
95
+ gc.collect()
96
+ mx.clear_cache()
97
+ return out
98
+
99
+ def scores(self, reader_vecs, tok_vecs):
100
+ x = mx.concatenate([reader_vecs, tok_vecs], axis=1)
101
+ x = (x - self.w["mu"]) / self.w["sd"]
102
+ for i in ("0", "3"):
103
+ x = nn.gelu(x @ self.w[f"{i}.weight"].T + self.w[f"{i}.bias"])
104
+ x = x @ self.w["6.weight"].T + self.w["6.bias"]
105
+ return np.array(mx.softmax(x.reshape(-1, self.L, self.E), axis=-1))
106
+
107
+ def team(self, scores, keep):
108
+ """(L, E) scores -> per layer the `keep` best experts (sorted ids)."""
109
+ s = scores.astype(np.float64) + 1e-7 * self.glob / self.glob.max(axis=-1, keepdims=True)
110
+ return [np.sort(np.argsort(-s[l])[:keep]) for l in range(self.L)]
111
+
112
+
113
+ class TeamRouter(nn.Module):
114
+ """Original router maths with our practised weights; experts outside the team are blocked."""
115
+
116
+ def __init__(self, weight, bias, top_k, route_scale):
117
+ super().__init__()
118
+ self.weight, self.bias = weight, bias
119
+ self.top_k, self.route_scale = top_k, route_scale
120
+ self.allowed = None
121
+ self.to_local = None
122
+
123
+ def __call__(self, h):
124
+ logits = h.astype(mx.float32) @ self.weight.T
125
+ scores = mx.sigmoid(logits)
126
+ biased = mx.where(self.allowed, scores + self.bias, -mx.inf)
127
+ idx = mx.argpartition(-biased, kth=self.top_k - 1, axis=-1)[..., : self.top_k]
128
+ w = mx.take_along_axis(scores, idx, axis=-1)
129
+ w = w / (w.sum(axis=-1, keepdims=True) + 1e-20)
130
+ return self.to_local[idx], w * self.route_scale
131
+
132
+
133
+ class LoRALinear(nn.Module):
134
+ def __init__(self, base, A, B, scale):
135
+ super().__init__()
136
+ self.base, self.A, self.B, self.scale = base, A, B, scale
137
+
138
+ def __call__(self, x):
139
+ y = self.base(x)
140
+ return y + self.scale * ((x @ self.A.T.astype(x.dtype)) @ self.B.T.astype(x.dtype)).astype(y.dtype)
141
+
142
+
143
+ class TeamModel:
144
+ def __init__(self):
145
+ from mlx_lm import load
146
+ t0 = time.time()
147
+ base_model_dir()
148
+ self.model, self.tokenizer = load(MODEL_DIR, lazy=True)
149
+ self.lm = self.model.model.language_model if hasattr(self.model.model, "language_model") else self.model.language_model
150
+ self.layers = self.lm.layers
151
+ self.index = json.load(open(os.path.join(MODEL_DIR, "model.safetensors.index.json")))["weight_map"]
152
+ router = load_file(os.path.join(PIECES, "router.safetensors"))
153
+ lora = load_file(os.path.join(PIECES, "attention_lora.safetensors"))
154
+ for i, layer in enumerate(self.layers):
155
+ g = layer.mlp.gate
156
+ layer.mlp.gate = TeamRouter(mx.array(router[f"layers.{i}.gate.weight"]), g.e_score_correction_bias,
157
+ g.top_k, g.routed_scaling_factor)
158
+ att = layer.self_attn
159
+ for cloud, mlx_name in LORA_NAMES.items():
160
+ A, B = lora[f"layers.{i}.{cloud}.A"], lora[f"layers.{i}.{cloud}.B"]
161
+ base = getattr(att, mlx_name)
162
+ setattr(att, mlx_name, LoRALinear(base, mx.array(A).astype(mx.bfloat16), mx.array(B).astype(mx.bfloat16), LORA_SCALE))
163
+ self.team = None
164
+ self.setup_seconds = time.time() - t0
165
+
166
+ def hf_tokenizer(self):
167
+ return getattr(self.tokenizer, "_tokenizer", self.tokenizer)
168
+
169
+ def chat_ids(self, messages):
170
+ t = self.hf_tokenizer()
171
+ text = t.apply_chat_template(messages, add_generation_prompt=True, tokenize=False, reasoning_effort="none")
172
+ return t.encode(text, add_special_tokens=False)
173
+
174
+ def word_embedding_mean(self, question):
175
+ """Mean word embedding of the chat prompt, from the exact (unquantised) table the receptionist was trained."""
176
+ if not hasattr(self, "_embed"):
177
+ self._embed = np.load(os.path.join(PIECES, "embed_f16.npy"), mmap_mode="r")
178
+ ids = self.chat_ids([{"role": "user", "content": question}])
179
+ x = mx.array(np.asarray(self._embed[ids], np.float32)).astype(mx.bfloat16)
180
+ e = self.lm.embed_norm(x).astype(mx.float32).mean(axis=0)
181
+ return e.astype(mx.float16).astype(mx.float32)
182
+
183
+ def _read_rows(self, name, rows):
184
+ """Read only the given experts (first dimension) of one stacked tensor from disk, with parallel reads."""
185
+ if not hasattr(self, "_files"):
186
+ self._files, self._pool = {}, ThreadPoolExecutor(8)
187
+ fn = self.index[name]
188
+ if fn not in self._files:
189
+ fd = os.open(os.path.join(MODEL_DIR, fn), os.O_RDONLY)
190
+ n = struct.unpack("<Q", os.pread(fd, 8, 0))[0]
191
+ self._files[fn] = (fd, json.loads(os.pread(fd, n, 8)), 8 + n)
192
+ fd, head, base = self._files[fn]
193
+ t = head[name]
194
+ shape, (a0, a1) = t["shape"], t["data_offsets"]
195
+ row_bytes = (a1 - a0) // shape[0]
196
+ buf = np.empty((len(rows), *shape[1:]), DTYPES[t["dtype"]])
197
+ view = memoryview(buf).cast("B")
198
+ rows = [int(r) for r in rows]
199
+ jobs, pos, start = [], 0, 0
200
+ for j in range(1, len(rows) + 1):
201
+ if j == len(rows) or rows[j] != rows[j - 1] + 1:
202
+ off, n = base + a0 + rows[start] * row_bytes, (j - start) * row_bytes
203
+ jobs += [(pos + k, off + k, min(CHUNK, n - k)) for k in range(0, n, CHUNK)]
204
+ pos, start = pos + n, j
205
+
206
+ def read(job):
207
+ p, off, n = job
208
+ got = 0
209
+ while got < n:
210
+ got += os.preadv(fd, [view[p + got:p + n]], off + got)
211
+
212
+ list(self._pool.map(read, jobs))
213
+ return buf
214
+
215
+ def load_team(self, team):
216
+ """team: per layer the expert ids to keep."""
217
+ t0, read, joined = time.time(), 0, 0
218
+ first = self.team is None
219
+ slots_all = []
220
+ for i, (layer, ids) in enumerate(zip(self.layers, team)):
221
+ prefix = f"model.language_model.layers.{i}.mlp.experts"
222
+ ids = [int(e) for e in ids]
223
+ if first:
224
+ slots, free, joining = list(ids), list(range(len(ids))), list(ids)
225
+ else:
226
+ slots = list(self.team[i])
227
+ want = set(ids)
228
+ free = [s for s, e in enumerate(slots) if e not in want]
229
+ joining = sorted(want - set(slots))
230
+ for s, e in zip(free, joining):
231
+ slots[s] = e
232
+ joined += len(joining)
233
+ for proj in ("gate_up_proj", "down_proj"):
234
+ mod = getattr(layer.mlp.experts, proj)
235
+ for field in ("weight", "scales", "global_scale"):
236
+ name = f"{prefix}.{proj}.{field}"
237
+ if name not in self.index or not joining:
238
+ continue
239
+ order = np.argsort(joining)
240
+ fresh = self._read_rows(name, [joining[k] for k in order])
241
+ read += fresh.nbytes
242
+ if first:
243
+ setattr(mod, field, mx.array(fresh))
244
+ else:
245
+ cur = getattr(mod, field)
246
+ cur[mx.array([free[k] for k in order])] = mx.array(fresh)
247
+ mx.eval(cur)
248
+ E = layer.mlp.gate.weight.shape[0]
249
+ allowed = np.zeros(E, bool)
250
+ allowed[slots] = True
251
+ to_local = np.zeros(E, np.int32)
252
+ to_local[slots] = np.arange(len(slots), dtype=np.int32)
253
+ layer.mlp.gate.allowed = mx.array(allowed)
254
+ layer.mlp.gate.to_local = mx.array(to_local)
255
+ mx.eval(layer.mlp.experts.parameters())
256
+ slots_all.append(slots)
257
+ self.team = slots_all
258
+ mx.clear_cache()
259
+ return dict(seconds=time.time() - t0, read=read, joined=joined / len(team))
260
+
261
+
262
+ def answer(tm, messages, max_tokens, show_thinking=True):
263
+ from mlx_lm import stream_generate
264
+ from mlx_lm.sample_utils import make_sampler
265
+ ids = tm.chat_ids(messages)
266
+ toks, text, t0, first = [], "", time.time(), None
267
+ thinking = True
268
+ print("\n\033[2m", end="", flush=True)
269
+ for r in stream_generate(tm.model, tm.tokenizer, prompt=ids, max_tokens=max_tokens, sampler=make_sampler(temp=0.0)):
270
+ if first is None:
271
+ first = time.time() - t0
272
+ toks.append(r.token)
273
+ piece = tm.hf_tokenizer().decode([r.token], skip_special_tokens=False)
274
+ if "<|content_text|>" in piece:
275
+ thinking = False
276
+ print("\033[0m\n", end="", flush=True)
277
+ continue
278
+ if piece.startswith("<|") and piece.endswith("|>"):
279
+ continue
280
+ if thinking and not show_thinking:
281
+ continue
282
+ print(piece, end="", flush=True)
283
+ dt = time.time() - t0
284
+ print("\033[0m")
285
+ raw = tm.hf_tokenizer().decode(toks, skip_special_tokens=False)
286
+ final = raw.split("<|content_text|>")[-1]
287
+ for s in ("<|end_message|>", "<|content_model_end_sampling|>"):
288
+ final = final.replace(s, "")
289
+ n = len(toks)
290
+ return dict(answer=final.strip(), tokens=n, first_token_s=round(first or 0, 2),
291
+ tok_per_s=round((n - 1) / max(dt - (first or 0), 1e-6), 1))
292
+
293
+
294
+ FADE = 0.5
295
+
296
+
297
+ def pick_and_load(tm, rec, newest, keep, running=None):
298
+ """The receptionist scores only the newest message (the kind of input it was trained on); the team is the top."""
299
+ t0 = time.time()
300
+ reader = rec.read_questions([newest])
301
+ tokv = mx.stack([tm.word_embedding_mean(newest)])
302
+ s = rec.scores(reader, tokv)[0]
303
+ running = s if running is None else FADE * s + (1 - FADE) * running
304
+ team = rec.team(running, keep)
305
+ pick = time.time() - t0
306
+ info = tm.load_team(team)
307
+ info["pick"] = pick
308
+ return running, info
309
+
310
+
311
+ def preflight():
312
+ """The model needs about 9.5 GB of memory."""
313
+ import shutil
314
+ import subprocess
315
+ need = 9.5
316
+ free_disk = shutil.disk_usage("/").free / 1e9
317
+ try:
318
+ vm = subprocess.run(["vm_stat"], capture_output=True, text=True).stdout
319
+ page = int(vm.split("page size of ")[1].split()[0])
320
+ pages = {l.split(":")[0]: int(l.split(":")[1].strip().rstrip(".")) for l in vm.splitlines()[1:] if ":" in l}
321
+ avail = sum(pages.get(k, 0) for k in ("Pages free", "Pages inactive", "Pages speculative")) * page / 1e9
322
+ except Exception:
323
+ avail = None
324
+ print(f"memory available ~{avail:.1f} GB, needed ~{need} GB; free disk {free_disk:.0f} GB" if avail is not None
325
+ else f"free disk {free_disk:.0f} GB")
326
+ if (avail is not None and avail < need) or free_disk < 10:
327
+ print("WARNING: your Mac may become slow (it will swap to disk). Close heavy apps (browser, other models), "
328
+ "or free some disk space.")
329
+ if sys.stdin.isatty() and input("continue anyway? [y/N] ").strip().lower() != "y":
330
+ sys.exit(0)
331
+
332
+
333
+ def main():
334
+ ap = argparse.ArgumentParser()
335
+ ap.add_argument("question", nargs="?")
336
+ ap.add_argument("--max-tokens", type=int, default=2048)
337
+ ap.add_argument("--chat", action="store_true")
338
+ ap.add_argument("--preload", action="store_true", help="load a default team at start, then only swap the difference")
339
+ ap.add_argument("--hide-thinking", action="store_true")
340
+ ap.add_argument("--check", action="store_true", help="compare this Mac's expert picks with the reference picks")
341
+ args = ap.parse_args()
342
+ rec = Receptionist()
343
+
344
+ if args.check:
345
+ qs = [c["question"] for c in rec.meta["check"]]
346
+ reader = rec.read_questions(qs)
347
+ tm = TeamModel()
348
+ tokv = mx.stack([tm.word_embedding_mean(q) for q in qs])
349
+ sc = rec.scores(reader, tokv)
350
+ ov = [np.mean([len(set(rec.team(s, 64)[l].tolist()) & set(c["top64"][l])) / 64 for l in range(rec.L)])
351
+ for s, c in zip(sc, rec.meta["check"])]
352
+ print(f"same experts picked as the reference: {100 * np.mean(ov):.1f}% "
353
+ f"(min {100 * min(ov):.1f}%) over {len(ov)} questions; expect about 99%")
354
+ return
355
+
356
+ preflight()
357
+ mx.set_cache_limit(512 * 1024**2)
358
+ tm = TeamModel()
359
+ print(f"model skeleton ready in {tm.setup_seconds:.1f}s (expert weights not loaded yet)")
360
+ if args.preload:
361
+ info = tm.load_team(rec.team(rec.glob.astype(np.float64), KEEP))
362
+ print(f"default team loaded: {gb(info['read'])} in {info['seconds']:.1f}s")
363
+ history, running = [], None
364
+ while True:
365
+ q = args.question if not args.chat else input("\nyou> ").strip()
366
+ if not q:
367
+ if args.chat:
368
+ continue
369
+ ap.error("give a question or use --chat")
370
+ if q in ("exit", "quit"):
371
+ break
372
+ history.append({"role": "user", "content": q})
373
+ t0 = time.time()
374
+ running, info = pick_and_load(tm, rec, q, KEEP, running)
375
+ print(f"receptionist picked {KEEP} of 128 experts per layer in {info['pick']:.1f}s; loaded {info['joined']:.0f} "
376
+ f"per layer ({gb(info['read'])}) in {info['seconds']:.1f}s")
377
+ res = answer(tm, history, args.max_tokens, show_thinking=not args.hide_thinking)
378
+ history.append({"role": "assistant", "content": res["answer"]})
379
+ ttft = info["pick"] + info["seconds"] + res["first_token_s"]
380
+ print(f"[{res['tokens']} tokens, {res['tok_per_s']} tok/s, time to first token {ttft:.1f}s "
381
+ f"(pick {info['pick']:.1f} + load {info['seconds']:.1f} + read prompt {res['first_token_s']:.1f}), "
382
+ f"total {time.time() - t0:.1f}s, peak memory {gb(mx.get_peak_memory())}]")
383
+ if not args.chat:
384
+ break
385
+
386
+
387
+ if __name__ == "__main__":
388
+ main()