File size: 17,503 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 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 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 | """Two-Phase Dynamic WSP Router for thinkingmachines/Inkling-2-Mini.
Executes Inkling-2-Mini natively via local Jinja chat_template + `/completion` SSE:
- Phase 1: pushes Phase-1 adapters via /lora-adapters, streams `<|content_thinking|>`
until exact special token 200010 (`<|end_message|>`), closing cleanly if hit.
- Phase 2: hot-swaps /lora-adapters (~0.7 ms) to `0.0` on Phase-1 and active on
routed Phase-2 adapter(s), continues on `<|end_message|><|message_model|>`
with `cache_prompt=True`, and parses text / native `<|content_invoke_tool_json|>` calls.
"""
from __future__ import annotations
import json
import re
import time
import urllib.request
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from jinja2 import Environment
from tokenizers import Tokenizer
ROOT = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\inkling2-mini-wsp")
ADAPTER_DIR = ROOT / "adapters"
TOK_MSG_MODEL = 200001
TOK_CONTENT_TEXT = 200004
TOK_EOS = 200006
TOK_CONTENT_THINK = 200008
TOK_END_MSG = 200010
TOK_TOOL_JSON = 200049
PROD_ADAPTER_NAMES = [
"wsp_s1_think_close",
"wsp_s2_loop_damp",
"wsp_s3_loop_refine",
"wsp_s4_tool_router",
"wsp_s5_handoff_gate",
"wsp_s6_term_action",
"wsp_s7_stem_settle",
"wsp_s8_post_format",
]
@dataclass
class ScalePreset:
name: str
s1: float = 0.80
s1_gentle: float = 0.40
s2: float = 0.70
s3: float = 0.65
s4: float = 1.00
s5: float = 1.00
s6: float = 0.85
s7: float = 0.80
s8: float = 0.80
DEFAULT_PRESET = ScalePreset("v2_med")
def load_jinja_and_tokenizer():
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))
tmpl = env.from_string(tmpl_str)
tok = Tokenizer.from_file(str(ROOT / "tokenizer.json"))
return tmpl, tok
def prepare_messages_for_jinja(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
out = []
last_name = "exec"
id2name: Dict[str, str] = {}
for m in messages:
mc = dict(m)
if mc.get("role") == "assistant" and isinstance(mc.get("tool_calls"), list):
new_tcs = []
for tc in mc["tool_calls"]:
tc_c = dict(tc)
fn_c = dict(tc_c.get("function") or {})
fn_name = fn_c.get("name")
if fn_name:
last_name = fn_name
if tc_c.get("id"):
id2name[tc_c["id"]] = fn_name
args = fn_c.get("arguments")
if isinstance(args, str):
try:
fn_c["arguments"] = json.loads(args)
except Exception:
pass
tc_c["function"] = fn_c
new_tcs.append(tc_c)
mc["tool_calls"] = new_tcs
elif mc.get("role") == "tool" and not mc.get("name"):
mc["name"] = id2name.get(mc.get("tool_call_id"), last_name)
out.append(mc)
return out
def parse_phase2_tokens(p2_text: str) -> Tuple[str, List[Dict[str, Any]], List[Dict[str, Any]]]:
"""Parse raw decoded Phase-2 text into clean content and normalized OpenAI tool_calls."""
raw_tcs: List[Dict[str, Any]] = []
parsed_tcs: List[Dict[str, Any]] = []
if "<|content_invoke_tool_json|>" in p2_text:
for idx, m in enumerate(
re.finditer(
r"(?:<\|message_model\|>)?([A-Za-z0-9_.\-]+)<\|content_invoke_tool_json\|>(.*?)(?:<\|end_message\|>|<\|content_model_end_sampling\|>|$)",
p2_text,
flags=re.S,
)
):
hint_name = m.group(1).strip()
body = m.group(2).strip()
try:
obj = json.loads(body)
name = str(obj.get("name") or hint_name)
args = obj.get("args", obj.get("arguments", {}))
if isinstance(args, str):
try:
args = json.loads(args)
except Exception:
args = {"_raw": args}
if not isinstance(args, dict):
args = {}
parsed_tcs.append({"name": name, "arguments": args})
raw_tcs.append({
"id": f"call_p2_{idx}",
"type": "function",
"function": {"name": name, "arguments": json.dumps(args, separators=(",", ":"))},
})
except Exception:
pass
clean = p2_text
clean = re.sub(r"(?:<\|message_model\|>)?[A-Za-z0-9_.\-]*<\|content_invoke_tool_json\|>.*?(?:<\|end_message\|>|$)", "", clean, flags=re.S)
m_txt = re.findall(r"<\|content_text\|>(.*?)(?:<\|end_message\|>|<\|content_model_end_sampling\|>|$)", clean, flags=re.S)
if m_txt:
content = "\n".join(x.strip() for x in m_txt if x.strip()).strip()
else:
for t in ("<|content_text|>", "<|end_message|>", "<|content_model_end_sampling|>", "<|message_model|>", "<|content_thinking|>"):
clean = clean.replace(t, "")
content = clean.strip()
return content, parsed_tcs, raw_tcs
def classify_regime(messages: List[Dict[str, Any]], tools: Optional[List[Dict[str, Any]]], preset: ScalePreset, mode: str = "wsp") -> Tuple[str, List[float], List[float]]:
"""Return (regime_name, phase1_scales[8], phase2_scales[8])."""
zeros = [0.0] * 8
if mode == "base":
return "base", list(zeros), list(zeros)
# Order of PROD_ADAPTER_NAMES:
# 0:s1_think_close, 1:s2_loop_damp, 2:s3_loop_refine, 3:s4_tool_router,
# 4:s5_handoff_gate, 5:s6_term_action, 6:s7_stem_settle, 7:s8_post_format
user_text = "\n".join(str(m.get("content", "")) for m in messages if m.get("role") == "user").lower()
sys_text = "\n".join(str(m.get("content", "")) for m in messages if m.get("role") == "system").lower()
tool_names = {((t.get("function") or {}).get("name") or "") for t in (tools or [])}
last_role = messages[-1].get("role") if messages else ""
if last_role == "tool":
tool_out = str(messages[-1].get("content", "")).lower()
p1 = [preset.s1_gentle * 0.7, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
if any(k in tool_out for k in ("403", "permissiondenied", "permission denied", "eacces", "access denied", "not authorized", "requires root")):
p2 = [0.0, 0.0, 0.0, 0.0, preset.s5, 0.0, 0.0, 0.0]
return "turn2_handoff", p1, p2
if any(k in tool_out for k in ("enoent", "not found", "unrecognized option", "no such file", "command not found", "is available")):
p2 = [0.0, 0.0, 0.0, 0.0, 0.0, preset.s6, 0.0, 0.0]
return "turn2_error_recov", p1, p2
return "turn2_synthesis", p1, list(zeros)
if tools:
if "autonomous linux terminal agent" in sys_text or ("exec" in tool_names and len(tool_names) == 1 and len(messages) > 2):
p1 = [preset.s1, preset.s2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
p2 = [0.0, 0.0, 0.0, 0.0, 0.0, preset.s6, 0.0, 0.0]
return "terminal_episode", p1, p2
if "execute a single linux shell command" in user_text or (tool_names == {"exec"}):
p1 = [preset.s1, preset.s2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
p2 = [0.0, 0.0, 0.0, 0.0, 0.0, preset.s6, 0.0, 0.0]
return "nl2bash_single", p1, p2
if any(t in tool_names for t in ("write_file", "read_file", "web_search", "escalate_handoff")):
p1 = [preset.s1_gentle, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
s5_val = preset.s5 if "escalate_handoff" in tool_names else 0.0
p2 = [0.0, 0.0, 0.0, preset.s4, s5_val, 0.0, 0.0, 0.0]
return "multi_tool_orch", p1, p2
# External BFCL irrelevance or unknown tools
return "other_tools", [preset.s1_gentle * 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], list(zeros)
# No tools: distinguish STEM math / science MCQ from code generation
is_code = ("```python" in user_text or "def " in user_text or "python function" in user_text) and "\\boxed" not in user_text and "multiple-choice" not in user_text
if not is_code and any(k in user_text for k in ("\\boxed", "answer: (x)", "multiple-choice", "solve the following", "compute", "calculate", "what is", "how many", "find the")):
p1 = [0.0, 0.0, preset.s3, 0.0, 0.0, 0.0, preset.s7, 0.0]
p2 = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, preset.s8]
return "stem_math_mcq", p1, p2
return "general_code_qa", list(zeros), list(zeros)
class Inkling2Router:
def __init__(self, base_url: str, adapter_ids: List[int], preset: ScalePreset = DEFAULT_PRESET):
self.base_url = base_url
self.adapter_ids = list(adapter_ids)
self.preset = preset
self.tmpl, self.tok = load_jinja_and_tokenizer()
self.last_scales: Optional[List[float]] = None
def push_scales(self, scales: List[float], force: bool = False) -> float:
if not self.adapter_ids:
return 0.0
target = [round(float(x), 4) for x in scales]
if (not force) and self.last_scales == target:
return 0.0
payload = [{"id": aid, "scale": s} for aid, s in zip(self.adapter_ids, target)]
req = urllib.request.Request(
f"{self.base_url}/lora-adapters",
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST",
)
t0 = time.perf_counter()
with urllib.request.urlopen(req, timeout=15) as r:
r.read()
self.last_scales = target
return (time.perf_counter() - t0) * 1000.0
def reset_kv_cache(self) -> None:
"""Evict slot KV cache cleanly between ablation arms that reuse identical prompt prefixes."""
self.push_scales([0.0] * len(self.adapter_ids), force=True)
req = urllib.request.Request(
f"{self.base_url}/completion",
data=json.dumps({"prompt": "reset", "n_predict": 1, "temperature": 0.0, "cache_prompt": False}).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=30) as r:
r.read()
def _stream_phase1(self, prompt_ids: List[int], max_p1: int, temp: float, seed: int) -> Tuple[List[int], bool, bool, Optional[float]]:
"""Stream Phase-1 thinking until token 200010 (<|end_message|>) or EOS 200006 or max_p1."""
body = {
"prompt": prompt_ids,
"n_predict": max_p1,
"temperature": temp,
"stream": True,
"return_tokens": True,
"cache_prompt": True,
}
if temp > 0:
body["seed"] = seed
req = urllib.request.Request(
f"{self.base_url}/completion",
data=json.dumps(body).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST",
)
toks: List[int] = []
hit_end_msg = False
hit_eos = False
p1_srv_tps: Optional[float] = None
with urllib.request.urlopen(req, timeout=240) as resp:
for raw_ln in resp:
ln = raw_ln.decode("utf-8", errors="replace").strip()
if not ln.startswith("data:"):
continue
obj = json.loads(ln[5:].strip())
tim = obj.get("timings")
if isinstance(tim, dict) and tim.get("predicted_per_second"):
p1_srv_tps = float(tim["predicted_per_second"])
chunk_t = obj.get("tokens") or []
stop_now = False
for t in chunk_t:
ti = int(t)
toks.append(ti)
if ti == TOK_END_MSG:
hit_end_msg = True
stop_now = True
break
if ti == TOK_EOS:
hit_eos = True
stop_now = True
break
if stop_now or obj.get("stop"):
break
return toks, hit_end_msg, hit_eos, p1_srv_tps
def _run_phase2(self, prompt_ids: List[int], max_p2: int, temp: float, seed: int) -> Tuple[List[int], bool, Optional[float]]:
body = {
"prompt": prompt_ids,
"n_predict": max_p2,
"temperature": temp,
"return_tokens": True,
"cache_prompt": True,
}
if temp > 0:
body["seed"] = seed
req = urllib.request.Request(
f"{self.base_url}/completion",
data=json.dumps(body).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=240) as resp:
res = json.loads(resp.read().decode("utf-8"))
toks = [int(t) for t in (res.get("tokens") or [])]
hit_len = bool(res.get("stopped_limit")) and (TOK_EOS not in toks)
tim = res.get("timings") or {}
p2_srv_tps = float(tim["predicted_per_second"]) if tim.get("predicted_per_second") else None
return toks, hit_len, p2_srv_tps
def chat_completion(
self,
messages: List[Dict[str, Any]],
tools: Optional[List[Dict[str, Any]]] = None,
max_tokens: int = 1024,
temperature: float = 0.0,
reasoning_effort: float = 0.2,
mode: str = "wsp",
override_p1_p2: Optional[Tuple[List[float], List[float]]] = None,
seed: int = 42,
) -> Dict[str, Any]:
if override_p1_p2 is not None:
regime = "override"
p1_scales, p2_scales = override_p1_p2
else:
regime, p1_scales, p2_scales = classify_regime(messages, tools, self.preset, mode=mode)
rendered = self.tmpl.render(
messages=prepare_messages_for_jinja(messages),
tools=tools,
reasoning_effort=reasoning_effort,
) + "<|message_model|><|content_thinking|>"
p_ids = [int(t) for t in self.tok.encode(rendered, add_special_tokens=False).ids]
# When scales are active in WSP mode, cap Phase-1 cleanly to preserve token headroom for Phase 2!
any_wsp_active = any(abs(s) > 1e-6 for s in p1_scales) or any(abs(s) > 1e-6 for s in p2_scales)
if any_wsp_active:
reserve_p2 = 160 if max_tokens <= 512 else 256
max_p1 = max(64, max_tokens - reserve_p2)
else:
max_p1 = max_tokens
t0 = time.perf_counter()
self.push_scales(p1_scales)
p1_toks, hit_end_msg, hit_eos, p1_srv_tps = self._stream_phase1(p_ids, max_p1=max_p1, temp=temperature, seed=seed)
p2_toks: List[int] = []
hit_p2_len = False
p2_srv_tps: Optional[float] = None
if not hit_eos:
# Close thinking gracefully with TOK_END_MSG + TOK_MSG_MODEL if model didn't emit TOK_END_MSG
p1_for_p2 = p1_toks if hit_end_msg else (p1_toks + [TOK_END_MSG])
rem = max(48, max_tokens - len(p1_toks))
self.push_scales(p2_scales)
p2_toks, hit_p2_len, p2_srv_tps = self._run_phase2(p_ids + p1_for_p2 + [TOK_MSG_MODEL], max_p2=rem, temp=temperature, seed=seed)
infer_ms = (time.perf_counter() - t0) * 1000.0
comp_tok = len(p1_toks) + len(p2_toks)
tps = round(comp_tok / max(infer_ms / 1000.0, 1e-4), 2)
srv_tps_vals = []
if p1_srv_tps:
srv_tps_vals.append((p1_srv_tps, max(len(p1_toks), 1)))
if p2_srv_tps:
srv_tps_vals.append((p2_srv_tps, max(len(p2_toks), 1)))
server_decode_tps = round(
sum(v * w for v, w in srv_tps_vals) / sum(w for _, w in srv_tps_vals), 2
) if srv_tps_vals else tps
think_clean = self.tok.decode([t for t in p1_toks if t != TOK_END_MSG], skip_special_tokens=True).strip()
p2_raw = self.tok.decode(p2_toks, skip_special_tokens=False) if p2_toks else ""
content, parsed_tcs, raw_tcs = parse_phase2_tokens(p2_raw)
if parsed_tcs:
finish_reason = "tool_calls"
elif hit_p2_len or (not hit_end_msg and not p2_toks):
finish_reason = "length"
else:
finish_reason = "stop"
return {
"content": content,
"reasoning": think_clean,
"tool_calls": raw_tcs,
"parsed_tool_calls": parsed_tcs,
"finish_reason": finish_reason,
"comp_tok": comp_tok,
"p1_tok": len(p1_toks),
"p2_tok": len(p2_toks),
"p1_natural_close": hit_end_msg,
"infer_ms": round(infer_ms, 1),
"tps": tps,
"server_decode_tps": server_decode_tps,
"p2_server_tps": round(p2_srv_tps, 2) if p2_srv_tps else None,
"regime": regime,
"p1_scales": p1_scales,
"p2_scales": p2_scales,
}
|