File size: 14,580 Bytes
b15e76d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Step 1A: Probe 6 new Inkling-2-Mini LoRA sites and build the complete 10-site Weight-Space Atlas."""
from __future__ import annotations

import json
import math
import subprocess
import sys
import time
import urllib.request
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple

import numpy as np
from gguf import GGUFReader, GGUFWriter

ROOT = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\inkling2-mini-wsp")
LLAMA_SERVER = ROOT / "llama.cpp" / "llama-server.exe"
GGUF_PATH = ROOT / "gguf" / "Inkling-2-Mini-UD-IQ3_XXS.gguf"
PROBES_DIR = ROOT / "probes"
TRACK_A_PROBES = ROOT / "lora_probe_results.json"
OUT_PATH = ROOT / "site_atlas_results.json"
PORT = 8091
BASE_URL = f"http://127.0.0.1:{PORT}"
RANK = 4
ALPHA = 4.0
PROMPT = "The capital of France is"

NEW_TARGETS: List[Tuple[str, List[str], float]] = [
    ("probe_loop_gain", ["blk.17.loop_mlp_gain.weight"], 2.5),
    ("probe_loop_forget", ["blk.17.loop_mlp_forget.weight"], 2.5),
    ("probe_loop_down", ["blk.17.loop_mlp_down.weight"], 2.5),
    ("probe_attn_gate", ["blk.23.attn_gate.weight"], 2.5),
    ("probe_attn_sink", ["blk.23.attn_sink_proj.weight"], 1.5),
    ("probe_attn_rel_conv", ["blk.23.attn_rel.weight", "blk.23.attn_k_conv_proj.weight"], 2.0),
]


def vram_mb() -> Dict[str, int]:
    out = subprocess.check_output(
        ["nvidia-smi", "--query-gpu=memory.total,memory.used,memory.free", "--format=csv,noheader,nounits"],
        text=True,
        timeout=10,
    ).strip().splitlines()[0]
    tot, used, free = [int(x.strip()) for x in out.split(",")]
    return {"total_mb": tot, "used_mb": used, "free_mb": free}


def http_get_json(url: str, timeout: float = 10.0) -> Any:
    with urllib.request.urlopen(url, timeout=timeout) as r:
        return json.loads(r.read().decode("utf-8"))


def http_post_json(url: str, payload: Any, timeout: float = 120.0) -> Tuple[Any, float]:
    req = urllib.request.Request(
        url,
        data=json.dumps(payload).encode("utf-8"),
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    t0 = time.perf_counter()
    with urllib.request.urlopen(req, timeout=timeout) as r:
        raw = r.read().decode("utf-8")
    return (json.loads(raw) if raw.strip() else {}), (time.perf_counter() - t0) * 1000.0


def build_new_probes() -> Tuple[str, Dict[str, Dict[str, Any]]]:
    PROBES_DIR.mkdir(parents=True, exist_ok=True)
    reader = GGUFReader(str(GGUF_PATH), "r")
    arch = str(reader.fields["general.architecture"].contents())
    tmap = {t.name: t for t in reader.tensors}
    rng = np.random.default_rng(123)
    built: Dict[str, Dict[str, Any]] = {}

    for pname, tnames, target_frob in NEW_TARGETS:
        out_gguf = PROBES_DIR / f"{pname}.gguf"
        writer = GGUFWriter(str(out_gguf), arch)
        writer.add_string("general.type", "adapter")
        writer.add_string("adapter.type", "lora")
        writer.add_string("general.name", pname)
        writer.add_float32("adapter.lora.alpha", float(ALPHA))

        shapes_info = {}
        for tname in tnames:
            if tname not in tmap:
                raise KeyError(f"Missing tensor {tname}")
            ne = [int(x) for x in tmap[tname].shape]
            assert len(ne) == 2, f"Expected 2D tensor for {tname}, got {ne}"
            ne0, ne1 = ne
            a = rng.normal(0.0, 0.01, size=(RANK, ne0)).astype(np.float32)
            b = rng.normal(0.0, 0.01, size=(ne1, RANK)).astype(np.float32)
            frob = float(np.linalg.norm(b @ a))
            sc = math.sqrt(target_frob / max(frob, 1e-8))
            la = (a * sc).astype(np.float16)
            lb = (b * sc).astype(np.float16)
            writer.add_tensor(f"{tname}.lora_a", la)
            writer.add_tensor(f"{tname}.lora_b", lb)
            shapes_info[tname] = {"ggml_ne": ne, "lora_a": list(la.shape), "lora_b": list(lb.shape)}

        writer.write_header_to_file()
        writer.write_kv_data_to_file()
        writer.write_tensors_to_file()
        writer.close()

        built[pname] = {
            "path": str(out_gguf),
            "tensors": tnames,
            "shapes": shapes_info,
            "file_kb": round(out_gguf.stat().st_size / 1024.0, 2),
        }
        print(f"Synthesized {out_gguf.name} ({built[pname]['file_kb']} KB) -> {tnames}", flush=True)

    return arch, built


class ServerProc:
    def __init__(self, lora_paths: Optional[List[str]] = None, tag: str = "atlas"):
        self.lora_paths = lora_paths or []
        self.log_path = ROOT / f"probe_{tag}.log"
        self.proc = None
        self.fp = None

    def __enter__(self):
        cmd = [
            str(LLAMA_SERVER),
            "-m", str(GGUF_PATH),
            "--host", "127.0.0.1",
            "--port", str(PORT),
            "--jinja",
            "-np", "1",
            "-c", "8192",
            "-ctk", "q8_0",
            "-ctv", "q8_0",
            "-ngl", "99",
            "--n-cpu-moe", "4",
            "--fit", "off",
        ]
        if self.lora_paths:
            cmd += ["--lora-init-without-apply", "--lora", ",".join(self.lora_paths)]
        self.fp = open(self.log_path, "w", encoding="utf-8", errors="replace")
        self.proc = subprocess.Popen(cmd, stdout=self.fp, stderr=subprocess.STDOUT)
        deadline = time.time() + 180.0
        while time.time() < deadline:
            if self.proc.poll() is not None:
                self.fp.flush()
                tail = self.log_path.read_text(encoding="utf-8", errors="replace")[-2000:]
                raise RuntimeError(f"llama-server exited rc={self.proc.returncode}:\n{tail}")
            try:
                if http_get_json(f"{BASE_URL}/health", timeout=2.0).get("status") == "ok":
                    return self
            except Exception:
                pass
            time.sleep(0.4)
        raise TimeoutError("health timeout")

    def __exit__(self, *args):
        if self.proc is not None and self.proc.poll() is None:
            self.proc.terminate()
            try:
                self.proc.wait(timeout=8)
            except subprocess.TimeoutExpired:
                self.proc.kill()
                self.proc.wait(timeout=5)
        if self.fp is not None:
            self.fp.close()


def probe_next_token() -> Dict[str, Any]:
    res, ms = http_post_json(
        f"{BASE_URL}/completion",
        {"prompt": PROMPT, "n_predict": 1, "temperature": 0.0, "n_probs": 5, "cache_prompt": False},
    )
    cp = res.get("completion_probabilities") or []
    first = cp[0] if cp else {}
    entries = first.get("top_logprobs") or first.get("top_probs") or []
    top_map: Dict[str, float] = {}
    for e in entries:
        tok_s = e.get("token", "")
        if e.get("logprob") is not None:
            top_map[tok_s] = float(e["logprob"])
        elif e.get("prob") is not None:
            top_map[tok_s] = math.log(max(float(e["prob"]), 1e-30))
    tok = first.get("token") or res.get("content") or ""
    if first.get("logprob") is not None:
        tok_lp = float(first["logprob"])
    elif first.get("prob") is not None:
        tok_lp = math.log(max(float(first["prob"]), 1e-30))
    else:
        tok_lp = top_map.get(tok)
    return {
        "token": tok,
        "token_logprob": round(tok_lp, 6) if tok_lp is not None else None,
        "top_logprobs": {k: round(v, 6) for k, v in top_map.items()},
        "ms": round(ms, 1),
    }


def bench_64_tok() -> Dict[str, Any]:
    res, ms = http_post_json(
        f"{BASE_URL}/completion",
        {
            "prompt": "Write a concise explanation of how Mixture-of-Experts transformers route tokens:\n\n1.",
            "n_predict": 64,
            "temperature": 0.0,
            "cache_prompt": False,
        },
    )
    tim = res.get("timings") or {}
    return {
        "comp_tokens": int(res.get("tokens_predicted") or tim.get("predicted_n") or 0),
        "wall_ms": round(ms, 1),
        "predicted_per_second": round(float(tim.get("predicted_per_second") or 0.0), 2),
    }


def set_lora_scales(adapters: List[Dict[str, Any]], active_idx: Optional[int], scale_val: float = 1.0) -> float:
    payload = [{"id": int(a["id"]), "scale": float(scale_val if i == active_idx else 0.0)} for i, a in enumerate(adapters)]
    _, dt_ms = http_post_json(f"{BASE_URL}/lora-adapters", payload)
    return round(dt_ms, 2)


def main():
    arch, built = build_new_probes()
    track_a = json.loads(TRACK_A_PROBES.read_text(encoding="utf-8"))
    base_tok = track_a["no_lora"]["next_token"]
    base_lp_map = base_tok["top_logprobs"]

    new_results: Dict[str, Any] = {}
    all_paths = [built[p]["path"] for p, _, _ in NEW_TARGETS]

    print("\n1) Attempting combined load of all 6 NEW probes...", flush=True)
    combined_ok = False
    v_loaded = None
    try:
        with ServerProc(lora_paths=all_paths, tag="atlas6") as _:
            v_loaded = vram_mb()
            adapters = http_get_json(f"{BASE_URL}/lora-adapters")
            print(f"  Loaded {len(adapters)} new adapters | VRAM={v_loaded['used_mb']} MiB free={v_loaded['free_mb']} MiB", flush=True)

            hs0 = set_lora_scales(adapters, active_idx=None)
            tok0 = probe_next_token()
            spd0 = bench_64_tok()
            diff0 = abs((tok0["token_logprob"] or 0.0) - (base_tok["token_logprob"] or 0.0))
            print(f"  scale=0.0: next={tok0['token']!r} delta_vs_base={diff0:.6g} swap={hs0}ms | speed={spd0['predicted_per_second']} tok/s", flush=True)

            for idx, (pname, tnames, _) in enumerate(NEW_TARGETS):
                hs = set_lora_scales(adapters, active_idx=idx, scale_val=1.0)
                tok_a = probe_next_token()
                spd_a = bench_64_tok()
                b_str = base_tok["token"]
                b_lp = base_lp_map.get(b_str, base_tok["token_logprob"])
                n_lp = (tok_a["top_logprobs"] or {}).get(b_str)
                delta_lp = abs(n_lp - b_lp) if (n_lp is not None and b_lp is not None) else abs((tok_a["token_logprob"] or 0.0) - (base_tok["token_logprob"] or 0.0))
                top_changed = tok_a["token"] != b_str
                executed = bool(top_changed or delta_lp > 1e-4)
                new_results[pname] = {
                    "tensors": tnames,
                    "load_ok": True,
                    "scale0_parity_ok": diff0 <= 1e-4 and tok0["token"] == b_str,
                    "hotswap_ms": hs,
                    "delta_logprob": round(delta_lp, 6),
                    "top_token": tok_a["token"],
                    "top_token_changed": top_changed,
                    "graph_executed": executed,
                    "tok_s": spd_a["predicted_per_second"],
                    "file_kb": built[pname]["file_kb"],
                }
                print(
                    f"  [{pname:20s}] swap={hs:5.2f}ms delta_lp={delta_lp:.6f} changed={str(top_changed):5s} "
                    f"executed={str(executed):5s} speed={spd_a['predicted_per_second']} tok/s",
                    flush=True,
                )
            combined_ok = True
    except Exception as e:
        print(f"  Combined 6-probe load failed: {e}", flush=True)

    if not combined_ok:
        print("\n2) Falling back to individual testing of each of the 6 new probes...", flush=True)
        for pname, tnames, _ in NEW_TARGETS:
            try:
                with ServerProc(lora_paths=[built[pname]["path"]], tag=pname) as _:
                    adapters = http_get_json(f"{BASE_URL}/lora-adapters")
                    hs0 = set_lora_scales(adapters, active_idx=None)
                    tok0 = probe_next_token()
                    hs1 = set_lora_scales(adapters, active_idx=0, scale_val=1.0)
                    tok1 = probe_next_token()
                    spd1 = bench_64_tok()
                    b_str = base_tok["token"]
                    diff0 = abs((tok0["token_logprob"] or 0.0) - (base_tok["token_logprob"] or 0.0))
                    b_lp = base_lp_map.get(b_str, base_tok["token_logprob"])
                    n_lp = (tok1["top_logprobs"] or {}).get(b_str)
                    delta_lp = abs(n_lp - b_lp) if (n_lp is not None and b_lp is not None) else abs((tok1["token_logprob"] or 0.0) - (base_tok["token_logprob"] or 0.0))
                    top_changed = tok1["token"] != b_str
                    executed = bool(top_changed or delta_lp > 1e-4)
                    new_results[pname] = {
                        "tensors": tnames,
                        "load_ok": True,
                        "scale0_parity_ok": diff0 <= 1e-4 and tok0["token"] == b_str,
                        "hotswap_ms": hs1,
                        "delta_logprob": round(delta_lp, 6),
                        "top_token": tok1["token"],
                        "top_token_changed": top_changed,
                        "graph_executed": executed,
                        "tok_s": spd1["predicted_per_second"],
                        "file_kb": built[pname]["file_kb"],
                    }
                    print(f"  SOLO [{pname:20s}] OK | delta_lp={delta_lp:.6f} executed={executed} speed={spd1['predicted_per_second']} tok/s", flush=True)
            except Exception as exc:
                new_results[pname] = {"tensors": tnames, "load_ok": False, "error": str(exc)[:400], "file_kb": built[pname]["file_kb"]}
                print(f"  SOLO [{pname:20s}] FAIL -> {str(exc)[:180]}", flush=True)

    # Merge Track A 4 sites + 6 new sites into unified 10-site Atlas
    atlas_10 = {}
    for pname, info in track_a["combined"]["per_adapter"].items():
        atlas_10[pname] = {
            "source": "track_a",
            "tensors": [info["tensor"]],
            "load_ok": info["load_ok"],
            "scale0_parity_ok": info["scale0_parity_ok"],
            "hotswap_ms": info["hotswap_ms"],
            "delta_logprob": info["delta_logprob_vs_base_token"],
            "top_token_changed": info["top_token_changed"],
            "graph_executed": info["graph_executed"],
            "tok_s": info["speed_64"]["predicted_per_second"],
            "file_kb": track_a["built_probes"][pname]["file_kb"],
        }
    for pname, info in new_results.items():
        atlas_10[pname] = {"source": "track_b_step1", **info}

    report = {
        "arch": arch,
        "no_lora_baseline": track_a["no_lora"],
        "combined_6new_ok": combined_ok,
        "vram_6new": v_loaded,
        "atlas_10_sites": atlas_10,
    }
    OUT_PATH.write_text(json.dumps(report, indent=2), encoding="utf-8")
    print(f"\nSaved 10-site Weight-Space Atlas -> {OUT_PATH}", flush=True)


if __name__ == "__main__":
    main()