File size: 17,499 Bytes
cedee5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
"""Inkling 2 Mini on a 16 GB Apple Silicon Mac, with only half of its experts in memory.

    python run.py "your question"        # one question
    python run.py --chat                 # chat (the team of experts follows the conversation)
    python run.py --check                # check the install: compares this Mac's expert picks with reference picks

How it works:
  1. The receptionist reads the question (Qwen3-Embedding-0.6B + Inkling's own word embeddings -> small network)
     and scores all 128 experts in each of the 24 layers. The top 64 per layer form the team.
  2. Only the team's expert weights are read from disk. The other experts are never loaded.
  3. The router uses fine-tuned weights and may only choose team members, and the attention layers get a small
     fine-tuned adapter (LoRA). Then the model answers as usual.

The 4-bit base model (mlx-community/Inkling-2-Mini-4bit, 17 GB) is downloaded on first use. To use a copy you
already have, set INKLING_DIR=/path/to/Inkling-2-Mini-4bit.
"""
import argparse
import gc
import json
import os
import struct
import sys
import time
from concurrent.futures import ThreadPoolExecutor

import mlx.core as mx
import mlx.nn as nn
import numpy as np
from safetensors.numpy import load_file

HERE = os.path.dirname(os.path.abspath(__file__))
BASE = "mlx-community/Inkling-2-Mini-4bit"
MODEL_DIR = os.environ.get("INKLING_DIR", "")
PIECES = HERE
READER = "Qwen/Qwen3-Embedding-0.6B"
KEEP = 64
CHUNK = 16 << 20
DTYPES = {"U32": np.uint32, "U8": np.uint8, "F32": np.float32, "F16": np.float16}
LORA_SCALE = 2.0
LORA_NAMES = {"q_proj.linear": "q_proj", "k_proj.linear": "k_proj", "v_proj.linear": "v_proj",
              "relative_position_bias.linear": "r_proj", "o_proj.linear": "o_proj", "o_proj.gate_proj": "gate_proj"}


def gb(x):
    return f"{x / 1e9:.1f} GB"


def base_model_dir():
    """Folder with the 4-bit base model: $INKLING_DIR if set, otherwise downloaded from the Hub (17 GB, once)."""
    global MODEL_DIR
    if not MODEL_DIR:
        from huggingface_hub import snapshot_download
        print(f"base model: {BASE} (downloaded on first use, 17 GB)")
        MODEL_DIR = snapshot_download(BASE)
    return MODEL_DIR


class Receptionist:
    def __init__(self):
        meta = json.load(open(os.path.join(PIECES, "meta.json")))
        self.feature, self.L, self.E = meta["feature"], meta["L"], meta["E"]
        assert self.feature == "qwen+tok", self.feature
        w = load_file(os.path.join(PIECES, "receptionist.safetensors"))
        self.w = {k: mx.array(v) for k, v in w.items()}
        self.glob = np.load(os.path.join(PIECES, "expert_prior.npy"))
        self.meta = meta

    def read_questions(self, texts, trunc="right"):
        """Qwen3-Embedding: last token of the last layer, normalised."""
        from mlx_lm.models import qwen3
        if not hasattr(self, "_reader"):
            from huggingface_hub import snapshot_download
            from transformers import AutoTokenizer
            pats = ["*.json", "*.safetensors", "*.txt"]
            try:
                path = snapshot_download(READER, allow_patterns=pats, local_files_only=True)
            except Exception:
                path = snapshot_download(READER, allow_patterns=pats)
            self._reader = (AutoTokenizer.from_pretrained(path, padding_side="left", truncation_side=trunc), path)
        tok, path = self._reader
        model = qwen3.Model(qwen3.ModelArgs.from_dict(json.load(open(os.path.join(path, "config.json")))))
        w = {}
        for f in sorted(os.listdir(path)):
            if f.endswith(".safetensors"):
                w.update(mx.load(os.path.join(path, f)))
        model.load_weights([(k if k.startswith("model.") else f"model.{k}", v) for k, v in w.items()], strict=False)
        out = []
        for t in texts:
            ids = tok(t, truncation=True, max_length=512)["input_ids"]
            h = model.model(mx.array([ids]))[0, -1].astype(mx.float32)
            out.append(h / mx.linalg.norm(h))
        out = mx.stack(out)
        mx.eval(out)
        del model
        gc.collect()
        mx.clear_cache()
        return out

    def scores(self, reader_vecs, tok_vecs):
        x = mx.concatenate([reader_vecs, tok_vecs], axis=1)
        x = (x - self.w["mu"]) / self.w["sd"]
        for i in ("0", "3"):
            x = nn.gelu(x @ self.w[f"{i}.weight"].T + self.w[f"{i}.bias"])
        x = x @ self.w["6.weight"].T + self.w["6.bias"]
        return np.array(mx.softmax(x.reshape(-1, self.L, self.E), axis=-1))

    def team(self, scores, keep):
        """(L, E) scores -> per layer the `keep` best experts (sorted ids)."""
        s = scores.astype(np.float64) + 1e-7 * self.glob / self.glob.max(axis=-1, keepdims=True)
        return [np.sort(np.argsort(-s[l])[:keep]) for l in range(self.L)]


class TeamRouter(nn.Module):
    """Original router maths with our practised weights; experts outside the team are blocked."""

    def __init__(self, weight, bias, top_k, route_scale):
        super().__init__()
        self.weight, self.bias = weight, bias
        self.top_k, self.route_scale = top_k, route_scale
        self.allowed = None
        self.to_local = None

    def __call__(self, h):
        logits = h.astype(mx.float32) @ self.weight.T
        scores = mx.sigmoid(logits)
        biased = mx.where(self.allowed, scores + self.bias, -mx.inf)
        idx = mx.argpartition(-biased, kth=self.top_k - 1, axis=-1)[..., : self.top_k]
        w = mx.take_along_axis(scores, idx, axis=-1)
        w = w / (w.sum(axis=-1, keepdims=True) + 1e-20)
        return self.to_local[idx], w * self.route_scale


class LoRALinear(nn.Module):
    def __init__(self, base, A, B, scale):
        super().__init__()
        self.base, self.A, self.B, self.scale = base, A, B, scale

    def __call__(self, x):
        y = self.base(x)
        return y + self.scale * ((x @ self.A.T.astype(x.dtype)) @ self.B.T.astype(x.dtype)).astype(y.dtype)


class TeamModel:
    def __init__(self):
        from mlx_lm import load
        t0 = time.time()
        base_model_dir()
        self.model, self.tokenizer = load(MODEL_DIR, lazy=True)
        self.lm = self.model.model.language_model if hasattr(self.model.model, "language_model") else self.model.language_model
        self.layers = self.lm.layers
        self.index = json.load(open(os.path.join(MODEL_DIR, "model.safetensors.index.json")))["weight_map"]
        router = load_file(os.path.join(PIECES, "router.safetensors"))
        lora = load_file(os.path.join(PIECES, "attention_lora.safetensors"))
        for i, layer in enumerate(self.layers):
            g = layer.mlp.gate
            layer.mlp.gate = TeamRouter(mx.array(router[f"layers.{i}.gate.weight"]), g.e_score_correction_bias,
                                        g.top_k, g.routed_scaling_factor)
            att = layer.self_attn
            for cloud, mlx_name in LORA_NAMES.items():
                A, B = lora[f"layers.{i}.{cloud}.A"], lora[f"layers.{i}.{cloud}.B"]
                base = getattr(att, mlx_name)
                setattr(att, mlx_name, LoRALinear(base, mx.array(A).astype(mx.bfloat16), mx.array(B).astype(mx.bfloat16), LORA_SCALE))
        self.team = None
        self.setup_seconds = time.time() - t0

    def hf_tokenizer(self):
        return getattr(self.tokenizer, "_tokenizer", self.tokenizer)

    def chat_ids(self, messages):
        t = self.hf_tokenizer()
        text = t.apply_chat_template(messages, add_generation_prompt=True, tokenize=False, reasoning_effort="none")
        return t.encode(text, add_special_tokens=False)

    def word_embedding_mean(self, question):
        """Mean word embedding of the chat prompt, from the exact (unquantised) table the receptionist was trained."""
        if not hasattr(self, "_embed"):
            self._embed = np.load(os.path.join(PIECES, "embed_f16.npy"), mmap_mode="r")
        ids = self.chat_ids([{"role": "user", "content": question}])
        x = mx.array(np.asarray(self._embed[ids], np.float32)).astype(mx.bfloat16)
        e = self.lm.embed_norm(x).astype(mx.float32).mean(axis=0)
        return e.astype(mx.float16).astype(mx.float32)

    def _read_rows(self, name, rows):
        """Read only the given experts (first dimension) of one stacked tensor from disk, with parallel reads."""
        if not hasattr(self, "_files"):
            self._files, self._pool = {}, ThreadPoolExecutor(8)
        fn = self.index[name]
        if fn not in self._files:
            fd = os.open(os.path.join(MODEL_DIR, fn), os.O_RDONLY)
            n = struct.unpack("<Q", os.pread(fd, 8, 0))[0]
            self._files[fn] = (fd, json.loads(os.pread(fd, n, 8)), 8 + n)
        fd, head, base = self._files[fn]
        t = head[name]
        shape, (a0, a1) = t["shape"], t["data_offsets"]
        row_bytes = (a1 - a0) // shape[0]
        buf = np.empty((len(rows), *shape[1:]), DTYPES[t["dtype"]])
        view = memoryview(buf).cast("B")
        rows = [int(r) for r in rows]
        jobs, pos, start = [], 0, 0
        for j in range(1, len(rows) + 1):
            if j == len(rows) or rows[j] != rows[j - 1] + 1:
                off, n = base + a0 + rows[start] * row_bytes, (j - start) * row_bytes
                jobs += [(pos + k, off + k, min(CHUNK, n - k)) for k in range(0, n, CHUNK)]
                pos, start = pos + n, j

        def read(job):
            p, off, n = job
            got = 0
            while got < n:
                got += os.preadv(fd, [view[p + got:p + n]], off + got)

        list(self._pool.map(read, jobs))
        return buf

    def load_team(self, team):
        """team: per layer the expert ids to keep."""
        t0, read, joined = time.time(), 0, 0
        first = self.team is None
        slots_all = []
        for i, (layer, ids) in enumerate(zip(self.layers, team)):
            prefix = f"model.language_model.layers.{i}.mlp.experts"
            ids = [int(e) for e in ids]
            if first:
                slots, free, joining = list(ids), list(range(len(ids))), list(ids)
            else:
                slots = list(self.team[i])
                want = set(ids)
                free = [s for s, e in enumerate(slots) if e not in want]
                joining = sorted(want - set(slots))
                for s, e in zip(free, joining):
                    slots[s] = e
            joined += len(joining)
            for proj in ("gate_up_proj", "down_proj"):
                mod = getattr(layer.mlp.experts, proj)
                for field in ("weight", "scales", "global_scale"):
                    name = f"{prefix}.{proj}.{field}"
                    if name not in self.index or not joining:
                        continue
                    order = np.argsort(joining)
                    fresh = self._read_rows(name, [joining[k] for k in order])
                    read += fresh.nbytes
                    if first:
                        setattr(mod, field, mx.array(fresh))
                    else:
                        cur = getattr(mod, field)
                        cur[mx.array([free[k] for k in order])] = mx.array(fresh)
                        mx.eval(cur)
            E = layer.mlp.gate.weight.shape[0]
            allowed = np.zeros(E, bool)
            allowed[slots] = True
            to_local = np.zeros(E, np.int32)
            to_local[slots] = np.arange(len(slots), dtype=np.int32)
            layer.mlp.gate.allowed = mx.array(allowed)
            layer.mlp.gate.to_local = mx.array(to_local)
            mx.eval(layer.mlp.experts.parameters())
            slots_all.append(slots)
        self.team = slots_all
        mx.clear_cache()
        return dict(seconds=time.time() - t0, read=read, joined=joined / len(team))


def answer(tm, messages, max_tokens, show_thinking=True):
    from mlx_lm import stream_generate
    from mlx_lm.sample_utils import make_sampler
    ids = tm.chat_ids(messages)
    toks, text, t0, first = [], "", time.time(), None
    thinking = True
    print("\n\033[2m", end="", flush=True)
    for r in stream_generate(tm.model, tm.tokenizer, prompt=ids, max_tokens=max_tokens, sampler=make_sampler(temp=0.0)):
        if first is None:
            first = time.time() - t0
        toks.append(r.token)
        piece = tm.hf_tokenizer().decode([r.token], skip_special_tokens=False)
        if "<|content_text|>" in piece:
            thinking = False
            print("\033[0m\n", end="", flush=True)
            continue
        if piece.startswith("<|") and piece.endswith("|>"):
            continue
        if thinking and not show_thinking:
            continue
        print(piece, end="", flush=True)
    dt = time.time() - t0
    print("\033[0m")
    raw = tm.hf_tokenizer().decode(toks, skip_special_tokens=False)
    final = raw.split("<|content_text|>")[-1]
    for s in ("<|end_message|>", "<|content_model_end_sampling|>"):
        final = final.replace(s, "")
    n = len(toks)
    return dict(answer=final.strip(), tokens=n, first_token_s=round(first or 0, 2),
                tok_per_s=round((n - 1) / max(dt - (first or 0), 1e-6), 1))


FADE = 0.5


def pick_and_load(tm, rec, newest, keep, running=None):
    """The receptionist scores only the newest message (the kind of input it was trained on); the team is the top."""
    t0 = time.time()
    reader = rec.read_questions([newest])
    tokv = mx.stack([tm.word_embedding_mean(newest)])
    s = rec.scores(reader, tokv)[0]
    running = s if running is None else FADE * s + (1 - FADE) * running
    team = rec.team(running, keep)
    pick = time.time() - t0
    info = tm.load_team(team)
    info["pick"] = pick
    return running, info


def preflight():
    """The model needs about 9.5 GB of memory."""
    import shutil
    import subprocess
    need = 9.5
    free_disk = shutil.disk_usage("/").free / 1e9
    try:
        vm = subprocess.run(["vm_stat"], capture_output=True, text=True).stdout
        page = int(vm.split("page size of ")[1].split()[0])
        pages = {l.split(":")[0]: int(l.split(":")[1].strip().rstrip(".")) for l in vm.splitlines()[1:] if ":" in l}
        avail = sum(pages.get(k, 0) for k in ("Pages free", "Pages inactive", "Pages speculative")) * page / 1e9
    except Exception:
        avail = None
    print(f"memory available ~{avail:.1f} GB, needed ~{need} GB; free disk {free_disk:.0f} GB" if avail is not None
          else f"free disk {free_disk:.0f} GB")
    if (avail is not None and avail < need) or free_disk < 10:
        print("WARNING: your Mac may become slow (it will swap to disk). Close heavy apps (browser, other models), "
              "or free some disk space.")
        if sys.stdin.isatty() and input("continue anyway? [y/N] ").strip().lower() != "y":
            sys.exit(0)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("question", nargs="?")
    ap.add_argument("--max-tokens", type=int, default=2048)
    ap.add_argument("--chat", action="store_true")
    ap.add_argument("--preload", action="store_true", help="load a default team at start, then only swap the difference")
    ap.add_argument("--hide-thinking", action="store_true")
    ap.add_argument("--check", action="store_true", help="compare this Mac's expert picks with the reference picks")
    args = ap.parse_args()
    rec = Receptionist()

    if args.check:
        qs = [c["question"] for c in rec.meta["check"]]
        reader = rec.read_questions(qs)
        tm = TeamModel()
        tokv = mx.stack([tm.word_embedding_mean(q) for q in qs])
        sc = rec.scores(reader, tokv)
        ov = [np.mean([len(set(rec.team(s, 64)[l].tolist()) & set(c["top64"][l])) / 64 for l in range(rec.L)])
              for s, c in zip(sc, rec.meta["check"])]
        print(f"same experts picked as the reference: {100 * np.mean(ov):.1f}% "
              f"(min {100 * min(ov):.1f}%) over {len(ov)} questions; expect about 99%")
        return

    preflight()
    mx.set_cache_limit(512 * 1024**2)
    tm = TeamModel()
    print(f"model skeleton ready in {tm.setup_seconds:.1f}s (expert weights not loaded yet)")
    if args.preload:
        info = tm.load_team(rec.team(rec.glob.astype(np.float64), KEEP))
        print(f"default team loaded: {gb(info['read'])} in {info['seconds']:.1f}s")
    history, running = [], None
    while True:
        q = args.question if not args.chat else input("\nyou> ").strip()
        if not q:
            if args.chat:
                continue
            ap.error("give a question or use --chat")
        if q in ("exit", "quit"):
            break
        history.append({"role": "user", "content": q})
        t0 = time.time()
        running, info = pick_and_load(tm, rec, q, KEEP, running)
        print(f"receptionist picked {KEEP} of 128 experts per layer in {info['pick']:.1f}s; loaded {info['joined']:.0f} "
              f"per layer ({gb(info['read'])}) in {info['seconds']:.1f}s")
        res = answer(tm, history, args.max_tokens, show_thinking=not args.hide_thinking)
        history.append({"role": "assistant", "content": res["answer"]})
        ttft = info["pick"] + info["seconds"] + res["first_token_s"]
        print(f"[{res['tokens']} tokens, {res['tok_per_s']} tok/s, time to first token {ttft:.1f}s "
              f"(pick {info['pick']:.1f} + load {info['seconds']:.1f} + read prompt {res['first_token_s']:.1f}), "
              f"total {time.time() - t0:.1f}s, peak memory {gb(mx.get_peak_memory())}]")
        if not args.chat:
            break


if __name__ == "__main__":
    main()