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
8.34 kB
"""Step 1 (Lightweight Build): Synthesize Ultra-Fast 2-Adapter WSP Bundle for Inkling-2-Mini.
Reuses `captured_inkling2_hfinal.pt` (350 exact h_final receptors, 0 re-capture) and builds
ONLY 2 modular rank=8 GGUF LoRAs in `adapters_lite/` targeting the top 3 ultra-fast Atlas sites:
1. wsp_lite_think_close.gguf (output.weight + blk.17.loop_mlp_gain.weight)
2. wsp_lite_term_action.gguf (output.weight + blk.23.attn_output.weight)
"""
from __future__ import annotations
import gc
import json
import sys
import time
from pathlib import Path
from typing import Any, Dict, List
import numpy as np
import torch
from gguf import GGUFReader, dequantize
from tokenizers import Tokenizer
ROOT = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\inkling2-mini-wsp")
sys.path.insert(0, str(ROOT))
from build_inkling2_wsp import ( # noqa: E402
GGUF_PATH,
N_VOCAB_UNPADDED,
PT_PATH,
TOK_CONTENT_TEXT,
TOK_END_MSG,
TOK_TOOL_JSON,
build_attn_out_pair,
build_loop_ctrl_pairs,
solve_sparse_vocab_head,
unit_t,
write_lora_gguf,
)
LITE_ADAPTER_DIR = ROOT / "adapters_lite"
MANIFEST_PATH = ROOT / "wsp_lite_manifest.json"
RANK = 8
def main() -> None:
t0 = time.time()
LITE_ADAPTER_DIR.mkdir(parents=True, exist_ok=True)
dev = "cuda" if torch.cuda.is_available() else "cpu"
pt = torch.load(str(PT_PATH), map_location="cpu", weights_only=False)
H = pt["H_final"].to(dev)
meta = pt["metadata"]
tok = Tokenizer.from_file(str(ROOT / "tokenizer.json"))
def tids_word(w: str) -> List[int]:
out: List[int] = []
for cand in (w, " " + w):
tid = tok.token_to_id(cand)
if tid is not None:
out.append(int(tid))
if not out:
out.extend([int(i) for i in tok.encode(w, add_special_tokens=False).ids[:1]])
return list(dict.fromkeys(out))
t_wait = tids_word("Wait") + tids_word("Actually") + tids_word("Hmm") + tids_word("However") + tids_word("Alternatively")
t_exec = tids_word("exec")
t_write = tids_word("write")
t_read = tids_word("read")
reader = GGUFReader(str(GGUF_PATH), "r")
arch = str(reader.fields["general.architecture"].contents())
tmap = {t.name: t for t in reader.tensors}
n_vocab_padded = int(tmap["output.weight"].shape[1])
W_out = np.asarray(
dequantize(tmap["output.weight"].data, tmap["output.weight"].tensor_type),
dtype=np.float32,
)[:N_VOCAB_UNPADDED]
W_out_norm = torch.from_numpy(np.array(tmap["output_norm.weight"].data, dtype=np.float32).reshape(-1)).to(dev)
W_out_t = torch.from_numpy(W_out).to(dev)
mean_u = W_out_t.mean(dim=0)
def u_dir(ids: List[int], neg: List[int] = ()) -> torch.Tensor:
p = unit_t((W_out_t[ids] - mean_u).mean(dim=0) * W_out_norm)
if neg:
n = unit_t((W_out_t[neg] - mean_u).mean(dim=0) * W_out_norm)
return unit_t(p - 0.5 * n)
return p
del W_out
gc.collect()
def idx_by(fam: str, **conds: Any) -> List[int]:
out: List[int] = []
for i, m in enumerate(meta):
if m["family"] != fam:
continue
ok = True
for k, v in conds.items():
if isinstance(v, (tuple, list, set)):
if m.get(k) not in v:
ok = False
elif m.get(k) != v:
ok = False
if ok:
out.append(i)
return out
early_think = idx_by("early_think_null")
early_mid_stem = idx_by("early_mid_stem_null")
syntax_null = idx_by("syntax_code_prose_null")
late_fast = idx_by("late_think_fast")
late_stem = idx_by("late_think_stem")
b_exec = idx_by("phase2_tool_boundary", label="boundary_exec")
b_write = idx_by("phase2_tool_boundary", label="boundary_write")
b_read = idx_by("phase2_tool_boundary", label="boundary_read")
b_escal = idx_by("phase2_tool_boundary", label="boundary_escal")
b_text = idx_by("phase2_tool_boundary", label="boundary_text_restraint")
X_base_null = H[early_think + early_mid_stem + syntax_null]
manifest: Dict[str, Any] = {
"arch": arch,
"rank": RANK,
"adapters": {},
"total_kb": 0.0,
"total_mb": 0.0,
}
# 1. wsp_lite_think_close.gguf (output.weight + blk.17.loop_mlp_gain.weight)
print("Synthesizing Lightweight 2-Adapter Bundle (rank=8)...", flush=True)
tc_attempts = [
("late_fast+late_stem", late_fast + late_stem, 38.0),
("late_fast+late_stem", late_fast + late_stem, 50.0),
("late_fast", late_fast, 38.0),
("late_fast", late_fast, 50.0),
]
la_tc = lb_tc = None
st_tc_head: Dict[str, Any] = {}
X_tc = H[late_fast + late_stem]
tc_mode_used = ""
tc_lam_used = 38.0
for mode_lbl, idxs, lam in tc_attempts:
X_cand = H[idxs]
Y_cand = [{TOK_END_MSG: +26.0, **{w: -14.0 for w in t_wait}} for _ in range(len(idxs))]
la_c, lb_c, st_c = solve_sparse_vocab_head(
X_cand, Y_cand, X_base_null, n_vocab_padded, rank=RANK, lam_null=lam
)
la_tc, lb_tc, st_tc_head = la_c, lb_c, st_c
X_tc = X_cand
tc_mode_used = mode_lbl
tc_lam_used = lam
print(f" [think_close try {mode_lbl}, lam={lam}] head={st_c}", flush=True)
if st_c["null_leak_pct"] <= 4.0:
break
u_close_steer = u_dir([TOK_END_MSG], neg=t_wait)
p_tc_loop, st_tc_loop = build_loop_ctrl_pairs(
[17],
tmap,
X_tc,
X_base_null,
r_gain_dir=-u_close_steer,
r_forget_dir=None,
W_out_norm=W_out_norm,
gain_mag=0.45,
rank=RANK,
)
pairs_tc = {"output.weight": (la_tc, lb_tc), **p_tc_loop}
sz_tc = write_lora_gguf(
LITE_ADAPTER_DIR / "wsp_lite_think_close.gguf",
arch,
"wsp_lite_think_close",
RANK,
pairs_tc,
)
manifest["adapters"]["wsp_lite_think_close"] = {
"kb": sz_tc,
"rank": RANK,
"tensors": sorted(pairs_tc.keys()),
"target_subset": tc_mode_used,
"lam_null": tc_lam_used,
"n_target_states": int(X_tc.shape[0]),
"n_null_states": int(X_base_null.shape[0]),
"head": st_tc_head,
"loop": st_tc_loop,
}
print(f" -> wsp_lite_think_close.gguf ({sz_tc} KB): tensors={sorted(pairs_tc.keys())}", flush=True)
# 2. wsp_lite_term_action.gguf (output.weight + blk.23.attn_output.weight)
b_exec_nl_tb = [
i for i in b_exec
if meta[i]["group"] in ("cal_nl2bash", "cal_tbench", "cal_s9_recov", "cal_recov_extra")
]
X_ta = H[b_exec_nl_tb]
X_ta_null = H[b_text + b_write + b_read + b_escal + syntax_null + early_think]
Y_ta = [
{e: +24.0 for e in t_exec} | {TOK_TOOL_JSON: +18.0, TOK_CONTENT_TEXT: -22.0}
for _ in b_exec_nl_tb
]
la_ta, lb_ta, st_ta_head = solve_sparse_vocab_head(
X_ta, Y_ta, X_ta_null, n_vocab_padded, rank=RANK, lam_null=30.0
)
u_exec_steer = u_dir(t_exec + [TOK_TOOL_JSON], neg=[TOK_CONTENT_TEXT] + t_write)
k_ta_attn, p_ta_attn, st_ta_attn = build_attn_out_pair(
23, tmap, u_exec_steer, X_ta_null, W_out_norm, target_frob=0.25, rank=RANK
)
pairs_ta = {"output.weight": (la_ta, lb_ta), k_ta_attn: p_ta_attn}
sz_ta = write_lora_gguf(
LITE_ADAPTER_DIR / "wsp_lite_term_action.gguf",
arch,
"wsp_lite_term_action",
RANK,
pairs_ta,
)
manifest["adapters"]["wsp_lite_term_action"] = {
"kb": sz_ta,
"rank": RANK,
"tensors": sorted(pairs_ta.keys()),
"n_target_states": int(X_ta.shape[0]),
"n_null_states": int(X_ta_null.shape[0]),
"head": st_ta_head,
"attn": st_ta_attn,
}
print(f" -> wsp_lite_term_action.gguf ({sz_ta} KB): head={st_ta_head} | attn={st_ta_attn}", flush=True)
tot_kb = round(sz_tc + sz_ta, 2)
manifest["total_kb"] = tot_kb
manifest["total_mb"] = round(tot_kb / 1024.0, 2)
manifest["synthesis_s"] = round(time.time() - t0, 2)
MANIFEST_PATH.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
print(f"\nSaved {MANIFEST_PATH} | total={tot_kb} KB ({manifest['total_mb']} MB) in {manifest['synthesis_s']}s", flush=True)
if __name__ == "__main__":
main()