Inkling-2-Mini-Weight-Space-Programming / scripts /explore_weight_space_sites.py
jstarks's picture
Upload Inkling-2-Mini Lightweight 2-Adapter Fast WSP bundle (6.32 MB, 136/155)
b15e76d verified
Raw History Blame Contribute Delete
14.6 kB
"""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()