"""Step 2: Capture strictly disjoint on-policy traces (Phase A) & exact h_final receptors (Phase B).""" from __future__ import annotations import gc 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 import torch from gguf import GGUFReader, dequantize from jinja2 import Environment from tokenizers import Tokenizer ROOT = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\inkling2-mini-wsp") sys.path.insert(0, str(ROOT)) sys.path.insert(0, r"C:\Users\jhjwi\.gemini\antigravity\scratch\wsp-5model-pipeline") import disjoint_inkling2_data as dd # noqa: E402 import wsp_tasks_9subspaces as tasks # noqa: E402 sys.stdout.reconfigure(encoding="utf-8", line_buffering=True) LLAMA_SERVER = ROOT / "llama.cpp" / "llama-server.exe" GGUF_PATH = ROOT / "gguf" / "Inkling-2-Mini-UD-IQ3_XXS.gguf" TRACES_PATH = ROOT / "captured_onpolicy_traces.json" OUT_PT_PATH = ROOT / "captured_inkling2_hfinal.pt" TOK_MSG_MODEL = 200001 TOK_CONTENT_TEXT = 200004 TOK_EOS = 200006 TOK_CONTENT_THINK = 200008 TOK_END_MSG = 200010 TOK_TOOL_JSON = 200049 def build_jinja_template(): tmpl_str = (ROOT / "chat_template.jinja").read_text(encoding="utf-8") tmpl_str = tmpl_str.replace("{%- generation -%}", "").replace("{%- endgeneration -%}", "") tmpl_str = tmpl_str.replace("{% generation %}", "").replace("{% endgeneration %}", "") env = Environment() env.filters["tojson"] = lambda x, sort_keys=False, separators=(",", ":"): json.dumps( x, sort_keys=sort_keys, separators=separators, ensure_ascii=False ) env.globals["raise_exception"] = lambda msg: (_ for _ in ()).throw(ValueError(msg)) return env.from_string(tmpl_str) def prepare_messages_for_jinja(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]: out = tasks.msgs_for_jinja(messages) last_name = "exec" id2name: Dict[str, str] = {} for m in out: if m.get("role") == "assistant" and isinstance(m.get("tool_calls"), list): for tc in m["tool_calls"]: fn = (tc.get("function") or {}).get("name") if fn: last_name = fn if tc.get("id"): id2name[tc["id"]] = fn elif m.get("role") == "tool" and not m.get("name"): m["name"] = id2name.get(m.get("tool_call_id"), last_name) return out class ManagedServer: def __init__(self, port: int, embeddings: bool = False, tag: str = "srv"): self.port = port self.embeddings = embeddings self.log_path = ROOT / f"capture_{tag}.log" self.base_url = f"http://127.0.0.1:{port}" self.proc = None self.fp = None def __enter__(self): cmd = [ str(LLAMA_SERVER), "-m", str(GGUF_PATH), "--host", "127.0.0.1", "--port", str(self.port), "-np", "1", "-c", "8192", "-ctk", "q8_0", "-ctv", "q8_0", "-ngl", "99", "--n-cpu-moe", "4", "--fit", "off", ] if self.embeddings: cmd += ["--embeddings", "--pooling", "last", "--embd-normalize", "-1"] else: cmd += ["--jinja"] 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")[-1500:] raise RuntimeError(f"Server rc={self.proc.returncode}:\n{tail}") try: with urllib.request.urlopen(f"{self.base_url}/health", timeout=2.0) as r: if json.loads(r.read().decode()).get("status") == "ok": return self except Exception: pass time.sleep(0.4) raise TimeoutError("Server 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 post_json(url: str, payload: dict, timeout: int = 180) -> dict: req = urllib.request.Request( url, data=json.dumps(payload).encode("utf-8"), headers={"Content-Type": "application/json"}, method="POST", ) with urllib.request.urlopen(req, timeout=timeout) as r: return json.loads(r.read().decode("utf-8")) def build_prompt_jobs(splits: Dict[str, Any], tmpl, tok: Tokenizer) -> List[Dict[str, Any]]: tr = splits["train"] jobs: List[Dict[str, Any]] = [] def add_job(group: str, item_id: str, messages: List[Dict[str, Any]], tools: Any, eff: float, n_predict: int, label: str): rendered = tmpl.render( messages=prepare_messages_for_jinja(messages), tools=tools, reasoning_effort=eff, ) + "<|message_model|><|content_thinking|>" p_ids = tok.encode(rendered, add_special_tokens=False).ids jobs.append({ "group": group, "id": item_id, "eff": eff, "n_predict": n_predict, "label": label, "p_ids": p_ids, }) # 1. CAL_THINK_FAST for idx, p in enumerate(tr["cal_s1_think"]): add_job("cal_s1_think", f"cs1_{idx}", [{"role": "user", "content": p}], None, 0.7, 768, "think_fast") for it in tr["cal_nl2bash_10"]: prompt = f"Execute a single Linux shell command via `exec` to accomplish this task: {it['query']}" add_job("cal_nl2bash", it["id"], [{"role": "user", "content": prompt}], tasks.WORKER_TOOLS, 0.7, 768, "boundary_exec") for it in tr["cal_tbench_6"]: sys_msg = ( "You are an autonomous Linux terminal agent working inside /app. " "Use the `exec` tool to run bash commands to inspect files, make changes, and verify your solution." ) add_job("cal_tbench", it["id"], [{"role": "system", "content": sys_msg}, {"role": "user", "content": it["instruction"]}], [tasks.WORKER_TOOLS[0]], 0.7, 768, "boundary_exec") # 2. CAL_STEM_DISJOINT (capture both eff=0.7 & eff=0.9 on hard ones for long derivations) for idx, it in enumerate(tr["cal_math_14"]): prompt = f"Solve the following mathematics problem carefully. Put your final simplified answer inside \\boxed{{}}.\n\n{it['problem']}" eff = 0.9 if idx % 2 == 1 else 0.7 add_job("cal_math", f"cmath_{idx:02d}", [{"role": "user", "content": prompt}], None, eff, 1024, "stem_math") for it in tr["cal_mcq_8"]: opts = it["options"] opt_lines = "\n".join(f"({chr(65 + i)}) {t}" for i, t in enumerate(opts)) prompt = ( f"Answer the following multiple-choice {it['subject']} question. " f"End your final response with `Answer: (X)` where X is the single capital letter A-{chr(64 + len(opts))}.\n\n" f"Question: {it['question']}\n\n{opt_lines}" ) add_job("cal_mcq", it["id"], [{"role": "user", "content": prompt}], None, 0.7, 896, "stem_mcq") # 3. CAL_TOOLS_DISJOINT for idx, (p, expected_tool) in enumerate(tr["cal_s3_router"]): lbl = { "exec": "boundary_exec", "write_file": "boundary_write", "read_file": "boundary_read", "web_search": "boundary_web", }[expected_tool] add_job("cal_s3_router", f"cs3_{idx}", [{"role": "user", "content": p}], tasks.WORKER_TOOLS, 0.2, 384, lbl) for it in tr["cal_tools_extra_6"]: lbl = f"boundary_{it['expected_tool'].split('_')[0]}" # write / read / web add_job("cal_tools_extra", it["id"], [{"role": "user", "content": it["prompt"]}], tasks.WORKER_TOOLS, 0.2, 384, lbl) for idx, msgs in enumerate(tr["cal_s6_handoff"]): add_job("cal_s6_handoff", f"cs6h_{idx}", msgs, tasks.ORCH_TOOLS_WITH_HANDOFF, 0.2, 384, "boundary_escal") for idx, msgs in enumerate(tr["cal_handoff_extra_3"]): add_job("cal_handoff_extra", f"che_{idx}", msgs, tasks.ORCH_TOOLS_WITH_HANDOFF, 0.2, 384, "boundary_escal") for idx, msgs in enumerate(tr["cal_s6_bounded"]): lbl = "boundary_text_restraint" if "Fibonacci" in msgs[0]["content"] else ("boundary_read" if "README" in msgs[0]["content"] else "boundary_exec") add_job("cal_s6_bounded", f"cs6b_{idx}", msgs, tasks.ORCH_TOOLS_WITH_HANDOFF, 0.2, 384, lbl) for idx, msgs in enumerate(tr["cal_s9_recov"]): lbl = "boundary_read" if "manifest" in msgs[0]["content"] else "boundary_exec" add_job("cal_s9_recov", f"cs9_{idx}", msgs, tasks.ORCH_TOOLS_WITH_HANDOFF, 0.2, 384, lbl) for it in tr["cal_recov_extra_3"]: add_job("cal_recov_extra", it["id"], it["messages"], tasks.ORCH_TOOLS_WITH_HANDOFF, 0.2, 384, "boundary_exec") for idx, p in enumerate(tr["cal_s2_restraint"]): add_job("cal_s2_restraint", f"cs2_{idx}", [{"role": "user", "content": p}], tasks.WORKER_TOOLS, 0.2, 384, "boundary_text_restraint") for idx, item in enumerate(tr["cal_s5_turn2_json"]): add_job("cal_s5_json", f"cs5_{idx}", item["messages"], tasks.WORKER_TOOLS, 0.2, 384, "boundary_text_restraint") for idx, msgs in enumerate(tr["cal_s7_inj"]): add_job("cal_s7_inj", f"cs7_{idx}", msgs, tasks.WORKER_TOOLS, 0.2, 384, "boundary_text_restraint") for idx, msgs in enumerate(tr["cal_s8_ground"]): add_job("cal_s8_ground", f"cs8_{idx}", msgs, tasks.WORKER_TOOLS, 0.2, 384, "boundary_text_restraint") return jobs def main(): dd.verify_zero_overlap() splits = dd.load_disjoint_splits() tok = Tokenizer.from_file(str(ROOT / "tokenizer.json")) tmpl = build_jinja_template() jobs = build_prompt_jobs(splits, tmpl, tok) print(f"Prepared {len(jobs)} strictly disjoint calibration jobs.", flush=True) # Identify ruminative pivot token IDs ruminate_words = ["Wait", "Actually", "Let", "Hmm", "However", "Alternatively", " wait", "Wait,"] ruminate_ids = set() for w in ruminate_words: for tid in tok.encode(w, add_special_tokens=False).ids: if tok.decode([tid]).strip().lower().rstrip(",") in ("wait", "actually", "hmm", "however", "alternative"): ruminate_ids.add(int(tid)) print(f"Ruminative token IDs: {sorted(ruminate_ids)}", flush=True) # Phase A: Generation (skip if TRACES_PATH already has matching jobs and user didn't pass --regen) if TRACES_PATH.exists() and len(json.loads(TRACES_PATH.read_text(encoding="utf-8"))) == len(jobs): print(f"Reusing existing {TRACES_PATH} ({len(jobs)} traces)...", flush=True) traces = json.loads(TRACES_PATH.read_text(encoding="utf-8")) else: print("\n=== Phase A: On-Policy Trace Generation (port 8091) ===", flush=True) traces = [] t0 = time.time() with ManagedServer(port=8091, embeddings=False, tag="gen") as srv: for idx, job in enumerate(jobs, 1): res = post_json( f"{srv.base_url}/completion", { "prompt": job["p_ids"], "n_predict": job["n_predict"], "temperature": 0.0, "return_tokens": True, "cache_prompt": False, }, timeout=180, ) gen_toks = [int(t) for t in (res.get("tokens") or [])] if TOK_END_MSG in gen_toks: sp = gen_toks.index(TOK_END_MSG) think_toks = gen_toks[:sp] phase2_toks = gen_toks[sp + 1:] else: think_toks = gen_toks phase2_toks = [] traces.append({ **job, "gen_toks": gen_toks, "think_toks": think_toks, "phase2_toks": phase2_toks, }) if idx % 10 == 0 or idx == len(jobs): el = time.time() - t0 eta = (len(jobs) - idx) * (el / idx) avg_th = round(sum(len(x["think_toks"]) for x in traces) / idx, 1) print(f" [Phase A {idx:2d}/{len(jobs)}] avg_think={avg_th}t | elapsed={el:.1f}s ETA={eta:.1f}s", flush=True) TRACES_PATH.write_text(json.dumps(traces), encoding="utf-8") print(f"Saved {TRACES_PATH} ({round(time.time() - t0, 1)}s)", flush=True) # Plan exact prefix queries across all 6 families prefix_records: List[Dict[str, Any]] = [] def add_prefix(family: str, p_ids: List[int], meta: Dict[str, Any]): if len(p_ids) <= 7800: prefix_records.append({"family": family, "ids": p_ids, "meta": meta}) for tr in traces: p_ids = tr["p_ids"] th = tr["think_toks"] p2 = tr["phase2_toks"] grp = tr["group"] lbl = tr["label"] # 1. Early thinking nullspace (20, 45 tokens inside <|content_thinking|>) if len(th) >= 35 and grp in ("cal_s1_think", "cal_nl2bash", "cal_tbench", "cal_math", "cal_mcq"): for off in (20, 45): if off < len(th) - 8: add_prefix("early_think_null", p_ids + th[:off], {"group": grp, "id": tr["id"], "off": off, "next_tok_id": th[off]}) # 2. Fast / Bash / TBench late thinking -> <|end_message|> if grp in ("cal_s1_think", "cal_nl2bash", "cal_tbench"): if len(th) >= 85: cand_offs = set() for frac in (0.65, 0.85, 0.96): cand_offs.add(max(65, int(len(th) * frac))) for pos in range(70, len(th) - 2): if th[pos] in ruminate_ids: cand_offs.add(pos + 1) if len(cand_offs) >= 6: break for off in sorted(cand_offs)[:5]: if off < len(th): add_prefix("late_think_fast", p_ids + th[:off], {"group": grp, "id": tr["id"], "off": off, "len_th": len(th)}) # 3. STEM early-mid null vs late settlement if grp in ("cal_math", "cal_mcq"): if len(th) >= 140: for off in (80, 150, 240, 320): if off < min(360, int(len(th) * 0.55)): add_prefix("early_mid_stem_null", p_ids + th[:off], {"group": grp, "id": tr["id"], "off": off}) if len(th) >= 420: cand_offs = set() for off in (480, 580, 700, 840, 960): if off < len(th): cand_offs.add(off) cand_offs.add(max(420, int(len(th) * 0.85))) for pos in range(400, len(th) - 2): if th[pos] in ruminate_ids: cand_offs.add(pos + 1) break for off in sorted(cand_offs)[:5]: if off < len(th): add_prefix("late_think_stem", p_ids + th[:off], {"group": grp, "id": tr["id"], "off": off, "len_th": len(th)}) # 4. Phase-2 boundary right at <|end_message|><|message_model|> if grp not in ("cal_math", "cal_mcq", "cal_s1_think"): add_prefix("phase2_tool_boundary", p_ids + th + [TOK_END_MSG, TOK_MSG_MODEL], {"group": grp, "id": tr["id"], "label": lbl}) # 5 & 6. Phase-2 post format & clean syntax/code/prose nullspace if p2 and len(p2) >= 6: if TOK_CONTENT_TEXT in p2: # Find offsets inside Phase-2 text body (before final TOK_END_MSG) end_p2 = p2.index(TOK_END_MSG) if TOK_END_MSG in p2 else len(p2) if grp in ("cal_math", "cal_s1_think", "cal_mcq") and end_p2 > 14: # Near tail right before boxed or Answer p2_txt = tok.decode(p2, skip_special_tokens=False) box_pos = None for i_tok in range(1, end_p2 - 2): sub = tok.decode(p2[max(0, i_tok - 2):i_tok + 1], skip_special_tokens=False) if "boxed{" in sub or "Answer:" in sub: box_pos = i_tok + 1 break if box_pos and box_pos < end_p2: add_prefix("phase2_post_format", p_ids + th + [TOK_END_MSG] + p2[:box_pos], {"group": grp, "id": tr["id"], "kind": "boxed_or_answer"}) # Also mid-solution clean STEM prose nullspace mid_off = max(4, end_p2 // 3) add_prefix("syntax_code_prose_null", p_ids + th + [TOK_END_MSG] + p2[:mid_off], {"group": grp, "id": tr["id"], "kind": "stem_prose"}) elif end_p2 > 8: # Code, JSON, bash command nullspace for frac in (0.35, 0.70): off2 = max(4, int(end_p2 * frac)) add_prefix("syntax_code_prose_null", p_ids + th + [TOK_END_MSG] + p2[:off2], {"group": grp, "id": tr["id"], "kind": grp}) # Add synthetic anti-{,} numeric comma states (e.g. "Therefore the answer is \boxed{70" -> suppress '{') num_prompts = [ ("Calculate 350 * 200. Put your final answer in \\boxed{}.", "Therefore, the final answer is \\boxed{70"), ("Calculate 420 * 100. Put your final answer in \\boxed{}.", "The product equals \\boxed{42"), ("What is 15000 + 2000? Put your final answer in \\boxed{}.", "Adding gives \\boxed{17"), ("What is 250 * 400? Put your final answer in \\boxed{}.", "Thus the total is \\boxed{100"), ] for idx, (q, ans_pref) in enumerate(num_prompts): base_r = tmpl.render(messages=[{"role": "user", "content": q}], tools=None, reasoning_effort=0.2) + "<|message_model|><|content_thinking|><|end_message|><|message_model|><|content_text|>" + ans_pref add_prefix("phase2_post_format", tok.encode(base_r, add_special_tokens=False).ids, {"group": "num_comma", "id": f"nc_{idx}", "kind": "anti_brace_comma"}) # Deduplicate identical prefix sequences while preserving metadata seen_seqs = set() uniq_records = [] for rec in prefix_records: key = tuple(rec["ids"]) if key not in seen_seqs: seen_seqs.add(key) uniq_records.append(rec) print(f"Prepared {len(uniq_records)} unique prefix probes for Phase B h_final capture.", flush=True) # Phase B: Exact h_final extraction on port 8092 print("\n=== Phase B: Extracting exact 2304-dim h_final via --embeddings (port 8092) ===", flush=True) H_list: List[np.ndarray] = [] meta_list: List[Dict[str, Any]] = [] t1 = time.time() with ManagedServer(port=8092, embeddings=True, tag="emb") as srv: # 5-point logit parity check first against GGUF output.weight reader = GGUFReader(str(GGUF_PATH), "r") tmap = {t.name: t for t in reader.tensors} W_out = np.asarray(dequantize(tmap["output.weight"].data, tmap["output.weight"].tensor_type), dtype=np.float32)[:200058] for idx, rec in enumerate(uniq_records, 1): er = post_json(f"{srv.base_url}/embedding", {"content": rec["ids"]}, timeout=60) vec = np.array(er[0]["embedding"][0] if isinstance(er, list) else er["embedding"], dtype=np.float32) H_list.append(vec) meta_list.append({"family": rec["family"], "len": len(rec["ids"]), **rec["meta"]}) if idx % 50 == 0 or idx == len(uniq_records): el = time.time() - t1 eta = (len(uniq_records) - idx) * (el / idx) print(f" [Phase B {idx:3d}/{len(uniq_records)}] elapsed={el:.1f}s ETA={eta:.1f}s", flush=True) H_tensor = torch.from_numpy(np.stack(H_list, axis=0)).to(torch.float32) # Parity check on first 5 states with known generated next_tok_id parity_checks = [] for k, vec in enumerate(H_list): if "next_tok_id" not in meta_list[k]: continue z = W_out @ vec logits = 30.0 * np.tanh(z / 30.0) top_id = int(np.argmax(logits)) exp_id = int(meta_list[k]["next_tok_id"]) parity_checks.append({ "family": meta_list[k]["family"], "len": meta_list[k]["len"], "h_norm": round(float(np.linalg.norm(vec)), 3), "top_token_id": top_id, "top_token_str": tok.decode([top_id], skip_special_tokens=False), "expected_next_id": exp_id, "expected_next_str": tok.decode([exp_id], skip_special_tokens=False), "top1_match": top_id == exp_id, "top_logit": round(float(logits[top_id]), 4), }) if len(parity_checks) >= 5: break del W_out gc.collect() fam_counts: Dict[str, int] = {} for m in meta_list: fam_counts[m["family"]] = fam_counts.get(m["family"], 0) + 1 torch.save({ "H_final": H_tensor, "metadata": meta_list, "family_counts": fam_counts, "parity_checks": parity_checks, }, str(OUT_PT_PATH)) print(f"\nSaved {OUT_PT_PATH} | shape={tuple(H_tensor.shape)} | counts={fam_counts}", flush=True) print("Parity samples:", json.dumps(parity_checks, indent=2), flush=True) if __name__ == "__main__": main()