Text Generation
GGUF
inkling2_loop
weight-space-programming
mechanistic-interpretability
lora
dynamic-lora
llama-cpp
inkling2
Mixture of Experts
looped-transformer
reasoning
tool-calling
agent
terminal-bench
nl2bash
gsm8k
stem
math-500
mmlu-pro
conversational
modelopt
imatrix
Instructions to use jstarks/Inkling-2-Mini-Weight-Space-Programming with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use jstarks/Inkling-2-Mini-Weight-Space-Programming with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf jstarks/Inkling-2-Mini-Weight-Space-Programming:UD-IQ3_XXS # Run inference directly in the terminal: llama cli -hf jstarks/Inkling-2-Mini-Weight-Space-Programming:UD-IQ3_XXS
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf jstarks/Inkling-2-Mini-Weight-Space-Programming:UD-IQ3_XXS # Run inference directly in the terminal: llama cli -hf jstarks/Inkling-2-Mini-Weight-Space-Programming:UD-IQ3_XXS
Build from source code
git clone https://github.com/ggml-org/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-app # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama serve -hf jstarks/Inkling-2-Mini-Weight-Space-Programming:UD-IQ3_XXS # Run inference directly in the terminal: ./build/bin/llama cli -hf jstarks/Inkling-2-Mini-Weight-Space-Programming:UD-IQ3_XXS
Use Docker
docker model run hf.co/jstarks/Inkling-2-Mini-Weight-Space-Programming:UD-IQ3_XXS
- Llama new
- LM Studio
- Jan
- vLLM
How to use jstarks/Inkling-2-Mini-Weight-Space-Programming with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "jstarks/Inkling-2-Mini-Weight-Space-Programming" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "jstarks/Inkling-2-Mini-Weight-Space-Programming", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/jstarks/Inkling-2-Mini-Weight-Space-Programming:UD-IQ3_XXS
- Ollama
How to use jstarks/Inkling-2-Mini-Weight-Space-Programming with Ollama:
ollama run hf.co/jstarks/Inkling-2-Mini-Weight-Space-Programming:UD-IQ3_XXS
- Unsloth Desktop
- Pi
How to use jstarks/Inkling-2-Mini-Weight-Space-Programming with Pi:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf jstarks/Inkling-2-Mini-Weight-Space-Programming:UD-IQ3_XXS
Configure the model in Pi
# Install Pi: npm install -g @earendil-works/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "llama-cpp": { "baseUrl": "http://localhost:9931/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "jstarks/Inkling-2-Mini-Weight-Space-Programming:UD-IQ3_XXS" } ] } } }Run Pi
# Start Pi in your project directory: pi
- Docker Model Runner
How to use jstarks/Inkling-2-Mini-Weight-Space-Programming with Docker Model Runner:
docker model run hf.co/jstarks/Inkling-2-Mini-Weight-Space-Programming:UD-IQ3_XXS
- Lemonade
How to use jstarks/Inkling-2-Mini-Weight-Space-Programming with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull jstarks/Inkling-2-Mini-Weight-Space-Programming:UD-IQ3_XXS
Run and chat with the model
lemonade run user.Inkling-2-Mini-Weight-Space-Programming-UD-IQ3_XXS
List all available models
lemonade list
- Hermes Agent
How to use jstarks/Inkling-2-Mini-Weight-Space-Programming with Hermes Agent:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf jstarks/Inkling-2-Mini-Weight-Space-Programming:UD-IQ3_XXS
Configure Hermes
# Install Hermes: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash hermes setup # Point Hermes at the local server: hermes config set model.provider custom hermes config set model.base_url http://127.0.0.1:9931/v1 hermes config set model.default jstarks/Inkling-2-Mini-Weight-Space-Programming:UD-IQ3_XXS
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use jstarks/Inkling-2-Mini-Weight-Space-Programming with OpenClaw:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf jstarks/Inkling-2-Mini-Weight-Space-Programming:UD-IQ3_XXS
Configure OpenClaw
# Install OpenClaw: npm install -g openclaw@latest # Register the local server and set it as the default model: openclaw onboard --non-interactive --mode local \ --auth-choice custom-api-key \ --custom-base-url http://127.0.0.1:9931/v1 \ --custom-model-id "jstarks/Inkling-2-Mini-Weight-Space-Programming:UD-IQ3_XXS" \ --custom-provider-id llama-cpp \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
File size: 29,733 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 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 | """Step 3: Multi-Site Closed-Form WSP Synthesis for thinkingmachines/Inkling-2-Mini.
Synthesizes:
- 8 modular production subspace GGUF LoRAs in adapters/:
1. wsp_s1_think_close.gguf (output.weight + blk.18..23.ffn_gate_inp + blk.23.attn_output)
2. wsp_s2_loop_damp.gguf (blk.12..17.loop_mlp_{forget,gain,down})
3. wsp_s3_loop_refine.gguf (blk.12..17.loop_mlp_gain + blk.17,23.attn_gate + blk.18..23.ffn_gate_inp)
4. wsp_s4_tool_router.gguf (output.weight + blk.18..23.ffn_gate_inp + blk.23.attn_output)
5. wsp_s5_handoff_gate.gguf (output.weight + blk.23.attn_output)
6. wsp_s6_term_action.gguf (output.weight + blk.18..23.ffn_gate_inp)
7. wsp_s7_stem_settle.gguf (output.weight + blk.18..23.ffn_gate_inp)
8. wsp_s8_post_format.gguf (output.weight)
- 4 single-site ablation GGUF LoRAs for S1+S4 on VAL_24:
ablation_output_head.gguf, ablation_router.gguf, ablation_attn.gguf, ablation_loop.gguf
"""
from __future__ import annotations
import gc
import json
import time
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
import torch
from gguf import GGUFReader, GGUFWriter, dequantize
from tokenizers import Tokenizer
ROOT = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\inkling2-mini-wsp")
GGUF_PATH = ROOT / "gguf" / "Inkling-2-Mini-UD-IQ3_XXS.gguf"
PT_PATH = ROOT / "captured_inkling2_hfinal.pt"
EXP_MAP_PATH = ROOT / "expert_spectral_map.json"
ADAPTER_DIR = ROOT / "adapters"
MANIFEST_PATH = ROOT / "wsp_synthesis_manifest.json"
D_MODEL = 2304
N_VOCAB_UNPADDED = 200058
TOK_CONTENT_TEXT = 200004
TOK_EOS = 200006
TOK_CONTENT_THINK = 200008
TOK_END_MSG = 200010
TOK_TOOL_JSON = 200049
def unit_t(x: torch.Tensor, dim: int = -1) -> torch.Tensor:
return x / (torch.norm(x, dim=dim, keepdim=True) + 1e-8)
def solve_woodbury_dense(
X_t: torch.Tensor,
Y_t: torch.Tensor,
X_n: torch.Tensor,
lam_null: float = 20.0,
lam_i: float = 1e-2,
) -> torch.Tensor:
"""Scale-invariant closed-form Woodbury ridge solver: dW @ X_t^T ≈ Y_t^T with X_n nullspace protection.
X_t: (N_t, D_in), Y_t: (N_t, D_out), X_n: (N_n, D_in) -> returns dW (D_out, D_in) float32 on X_t.device.
"""
assert X_t.shape[0] > 0, "Empty target states"
sx = float(torch.sqrt(X_t.pow(2).sum(dim=1).mean()).clamp(min=1e-6).item())
Xt_s = X_t / sx
Yt_s = Y_t / sx
d_in = X_t.shape[1]
A = (Xt_s.T @ Xt_s) / max(X_t.shape[0], 1)
if X_n.shape[0] > 0:
Xn_s = X_n / sx
A = A + lam_null * ((Xn_s.T @ Xn_s) / X_n.shape[0])
A = A + lam_i * torch.eye(d_in, device=X_t.device, dtype=torch.float32)
B = (Yt_s.T @ Xt_s) / max(X_t.shape[0], 1) # (D_out, D_in)
# Solve dW @ A = B => A^T @ dW^T = B^T
dW = torch.linalg.solve(A.T, B.T).T
return dW
def svd_factorize_lora(dW: torch.Tensor, rank: int) -> Tuple[np.ndarray, np.ndarray, float, torch.Tensor]:
"""Factorize dW (D_out, D_in) into exact GGUF F16 lora_a (rank, D_in) and lora_b (D_out, rank)."""
U, S, Vh = torch.linalg.svd(dW.float(), full_matrices=False)
r_eff = min(rank, int(S.shape[0]))
U_r = U[:, :r_eff]
S_r = S[:r_eff]
Vh_r = Vh[:r_eff, :]
dW_r = U_r @ torch.diag(S_r) @ Vh_r
energy = float((S_r.pow(2).sum() / (S.pow(2).sum() + 1e-12)).item())
sqrt_s = torch.sqrt(torch.clamp(S_r, min=0.0))
lb = (U_r * sqrt_s.unsqueeze(0)).cpu().numpy()
la = (sqrt_s.unsqueeze(1) * Vh_r).cpu().numpy()
if r_eff < rank:
lb = np.concatenate([lb, np.zeros((lb.shape[0], rank - r_eff), dtype=np.float32)], axis=1)
la = np.concatenate([la, np.zeros((rank - r_eff, la.shape[1]), dtype=np.float32)], axis=0)
return la.astype(np.float16), lb.astype(np.float16), energy, dW_r
def solve_sparse_vocab_head(
X_t: torch.Tensor,
target_shifts: List[Dict[int, float]],
X_n: torch.Tensor,
n_vocab_padded: int,
rank: int = 16,
lam_null: float = 25.0,
lam_i: float = 1e-2,
) -> Tuple[np.ndarray, np.ndarray, Dict[str, Any]]:
"""Solve output.weight LoRA strictly on active vocab rows (0.000% perturbation on remaining 200K+ rows)."""
active_ids = sorted({vid for row in target_shifts for vid in row.keys()})
vid_to_col = {vid: i for i, vid in enumerate(active_ids)}
Y_sub = torch.zeros((len(target_shifts), len(active_ids)), device=X_t.device, dtype=torch.float32)
for r_i, row in enumerate(target_shifts):
for vid, val in row.items():
Y_sub[r_i, vid_to_col[vid]] = float(val)
dW_sub = solve_woodbury_dense(X_t, Y_sub, X_n, lam_null=lam_null, lam_i=lam_i) # (|V_act|, 2304)
la, lb_sub, energy, dW_sub_r = svd_factorize_lora(dW_sub, rank=rank)
# Scatter lb_sub (|V_act|, rank) into full (201024, rank) F16 array
lb_full = np.zeros((n_vocab_padded, rank), dtype=np.float16)
lb_full[active_ids, :] = lb_sub
# Compute exact pre-softcap shift metrics
pred_t = (X_t @ dW_sub_r.T) # (N_t, |V_act|)
pos_vals = []
neg_vals = []
for r_i, row in enumerate(target_shifts):
for vid, val in row.items():
c = vid_to_col[vid]
if val > 0:
pos_vals.append(float(pred_t[r_i, c].item()))
elif val < 0:
neg_vals.append(float(pred_t[r_i, c].item()))
t_rms = float(torch.sqrt(pred_t.pow(2).sum(dim=1).mean()).clamp(min=1e-9).item())
if X_n.shape[0] > 0:
pred_n = X_n @ dW_sub_r.T
n_rms = float(torch.sqrt(pred_n.pow(2).sum(dim=1).mean()).item())
null_leak = n_rms / t_rms
else:
null_leak = 0.0
stats = {
"active_vocab_count": len(active_ids),
"svd_energy": round(energy, 5),
"frob_norm": round(float(torch.norm(dW_sub_r).item()), 4),
"mean_pos_dz": round(float(np.mean(pos_vals)) if pos_vals else 0.0, 3),
"mean_neg_dz": round(float(np.mean(neg_vals)) if neg_vals else 0.0, 3),
"null_leak_pct": round(100.0 * null_leak, 3),
}
return la, lb_full, stats
def safe_div_norm(x: torch.Tensor, w_norm: torch.Tensor) -> torch.Tensor:
denom = w_norm.sign() * w_norm.abs().clamp(min=0.15)
denom = torch.where(w_norm == 0, torch.ones_like(w_norm) * 0.15, denom)
return x / denom.unsqueeze(0)
def build_router_pairs(
layers: List[int],
R_t: torch.Tensor,
R_n: torch.Tensor,
exp_map: Dict[str, Any],
pos_concepts: List[str],
neg_concepts: List[str],
W_out_norm: torch.Tensor,
delta_score: float = 0.8,
rank: int = 8,
) -> Tuple[Dict[str, Tuple[np.ndarray, np.ndarray]], Dict[str, Any]]:
"""Synthesize blk.{l}.ffn_gate_inp.weight LoRA pairs upweighting/downweighting spectral specialist experts."""
pairs = {}
scale_ffn = float(np.sqrt(D_MODEL))
Xt_r = unit_t(safe_div_norm(R_t, W_out_norm)) * scale_ffn
Xn_r = unit_t(safe_div_norm(R_n, W_out_norm)) * scale_ffn if R_n.shape[0] > 0 else R_n
# Normalize delta_score carefully: logits before sigmoid are ~[-5, 5], we divide by scale_ffn implicitly inside solve!
n_t = Xt_r.shape[0]
frobs = []
leaks = []
for l in layers:
by_l = exp_map["by_layer"][str(l)]
pos_ids = []
for c in pos_concepts:
pos_ids.extend([x["expert"] for x in by_l[c]["top_pos"][:6]])
neg_ids = []
for c in neg_concepts:
neg_ids.extend([x["expert"] for x in by_l[c]["top_pos"][:6]])
pos_set = set(pos_ids) - set(neg_ids)
neg_set = set(neg_ids) - set(pos_ids)
Y_r = torch.zeros((n_t, 128), device=Xt_r.device, dtype=torch.float32)
for e in pos_set:
Y_r[:, e] = +delta_score
for e in neg_set:
Y_r[:, e] = -delta_score
dW_r = solve_woodbury_dense(Xt_r, Y_r, Xn_r, lam_null=30.0, lam_i=5e-2)
la, lb, _, dW_rr = svd_factorize_lora(dW_r, rank=rank)
pairs[f"blk.{l}.ffn_gate_inp.weight"] = (la, lb)
frobs.append(float(torch.norm(dW_rr).item()))
if Xn_r.shape[0] > 0:
tr = float(torch.sqrt((Xt_r @ dW_rr.T).pow(2).sum(dim=1).mean()).clamp(min=1e-9).item())
nr = float(torch.sqrt((Xn_r @ dW_rr.T).pow(2).sum(dim=1).mean()).item())
leaks.append(100.0 * nr / tr)
return pairs, {"mean_frob": round(float(np.mean(frobs)), 5), "mean_null_pct": round(float(np.mean(leaks)) if leaks else 0.0, 2)}
def build_attn_out_pair(
layer: int,
tmap: Dict[str, Any],
r_steer: torch.Tensor,
R_null: torch.Tensor,
W_out_norm: torch.Tensor,
target_frob: float = 0.25,
rank: int = 8,
) -> Tuple[str, Tuple[np.ndarray, np.ndarray], Dict[str, Any]]:
"""Precondition blk.{l}.attn_output.weight by (1 + attn_post_conv[:,3]) / sqrt(5) + column-aligned rank-r projection."""
Wo = np.asarray(dequantize(tmap[f"blk.{layer}.attn_output.weight"].data, tmap[f"blk.{layer}.attn_output.weight"].tensor_type), dtype=np.float32)
Wo_t = torch.from_numpy(Wo).to(r_steer.device) # (2304, 3072)
ac = np.array(tmap[f"blk.{layer}.attn_post_conv.weight"].data, dtype=np.float32).reshape(2304, 4)
gain_t = torch.from_numpy(((1.0 + ac[:, 3]) / np.sqrt(5.0)).astype(np.float32)).to(r_steer.device) # (2304,)
# Effective output direction in post_conv * output_norm space:
scale_eff = gain_t * W_out_norm
We = Wo_t * scale_eff.unsqueeze(1) # (2304, 3072)
We_unit = We / (torch.norm(We, dim=0, keepdim=True) + 1e-8)
r_u = unit_t(r_steer)
dots = We_unit.T @ r_u # (3072,)
# Select top-32 input channels whose base output aligns cleanly with r_u and minimally with R_null
if R_null.shape[0] > 0:
Rn_u = unit_t(R_null, dim=1)
null_pen = (We_unit.T @ Rn_u.T).abs().mean(dim=1)
scores = dots.abs() - 0.5 * null_pen
else:
scores = dots.abs()
top_cols = torch.topk(scores, k=min(32, Wo_t.shape[1])).indices
v_in = torch.zeros(Wo_t.shape[1], device=r_steer.device, dtype=torch.float32)
v_in[top_cols] = torch.sign(dots[top_cols]) * scores[top_cols].clamp(min=0.0)
v_in = unit_t(v_in)
# Precondition output vector by inverse clamped post_conv * output_norm
rel_g = scale_eff.abs() / (scale_eff.abs().mean() + 1e-8)
inv_g = torch.sign(scale_eff) / rel_g.clamp(min=0.25, max=6.0)
u_out = unit_t(r_u * inv_g)
# Project out top null directions in weighted output space
if R_null.shape[0] > 0:
# Take top-16 SVD directions of R_null in residual space
_, _, Vn = torch.linalg.svd(unit_t(safe_div_norm(R_null, W_out_norm)), full_matrices=False)
Q_n = Vn[:min(16, Vn.shape[0])] # (16, 2304)
u_eff = u_out * gain_t
u_eff = u_eff - Q_n.T @ (Q_n @ u_eff)
u_out = unit_t(u_eff / (gain_t.sign() * gain_t.abs().clamp(min=0.1)))
dW = target_frob * torch.outer(u_out, v_in) # rank-1 padded to rank-8 cleanly
la, lb, _, dW_r = svd_factorize_lora(dW, rank=rank)
return f"blk.{layer}.attn_output.weight", (la, lb), {"frob": round(float(torch.norm(dW_r).item()), 4)}
def build_attn_gate_pair(
layer: int,
tmap: Dict[str, Any],
X_t: torch.Tensor,
X_n: torch.Tensor,
r_steer: torch.Tensor,
W_out_norm: torch.Tensor,
target_shift: float = 0.8,
rank: int = 8,
) -> Tuple[str, Tuple[np.ndarray, np.ndarray], Dict[str, Any]]:
"""Steer blk.{l}.attn_gate.weight ([2304, 3072]) to selectively amplify channels aligned with r_steer."""
Wo = np.asarray(dequantize(tmap[f"blk.{layer}.attn_output.weight"].data, tmap[f"blk.{layer}.attn_output.weight"].tensor_type), dtype=np.float32)
Wo_t = torch.from_numpy(Wo).to(X_t.device)
ac = np.array(tmap[f"blk.{layer}.attn_post_conv.weight"].data, dtype=np.float32).reshape(2304, 4)
gain_t = torch.from_numpy(((1.0 + ac[:, 3]) / np.sqrt(5.0)).astype(np.float32)).to(X_t.device)
We = Wo_t * (gain_t * W_out_norm).unsqueeze(1)
We_unit = We / (torch.norm(We, dim=0, keepdim=True) + 1e-8)
dots = We_unit.T @ unit_t(r_steer) # (3072,)
y_gate = torch.tanh(dots * 8.0) * target_shift # positive on aligned channels, negative on opposite
Y_t = y_gate.unsqueeze(0).expand(X_t.shape[0], -1)
Xt_r = unit_t(safe_div_norm(X_t, W_out_norm)) * float(np.sqrt(D_MODEL))
Xn_r = unit_t(safe_div_norm(X_n, W_out_norm)) * float(np.sqrt(D_MODEL)) if X_n.shape[0] > 0 else X_n
dW = solve_woodbury_dense(Xt_r, Y_t, Xn_r, lam_null=30.0, lam_i=5e-2)
la, lb, _, dW_r = svd_factorize_lora(dW, rank=rank)
return f"blk.{layer}.attn_gate.weight", (la, lb), {"frob": round(float(torch.norm(dW_r).item()), 4)}
def build_loop_ctrl_pairs(
layers: List[int],
tmap: Dict[str, Any],
X_t: torch.Tensor,
X_n: torch.Tensor,
r_gain_dir: Optional[torch.Tensor],
r_forget_dir: Optional[torch.Tensor],
W_out_norm: torch.Tensor,
gain_mag: float = 0.6,
forget_mag: float = 0.6,
rank: int = 8,
) -> Tuple[Dict[str, Tuple[np.ndarray, np.ndarray]], Dict[str, Any]]:
"""Synthesize blk.{12..17}.loop_mlp_{gain,forget} LoRAs via exact loop_mlp_down projection into 64-dim gate basis."""
pairs = {}
scale_rms = float(np.sqrt(D_MODEL))
Xt_r = unit_t(safe_div_norm(X_t, W_out_norm)) * scale_rms
Xn_r = unit_t(safe_div_norm(X_n, W_out_norm)) * scale_rms if X_n.shape[0] > 0 else X_n
frobs = []
for l in layers:
D_full = np.array(tmap[f"blk.{l}.loop_mlp_down.weight"].data, dtype=np.float32).reshape(64, 4608)
D_cur = torch.from_numpy(D_full[:, :D_MODEL]).to(X_t.device) # (64, 2304)
# h_ctrl_cur ≈ unit_rms(Xt_r) @ D_cur^T -> (N, 64)
H64_t = Xt_r @ D_cur.T
H64_n = Xn_r @ D_cur.T if Xn_r.shape[0] > 0 else Xn_r
if r_gain_dir is not None:
yg = (unit_t(r_gain_dir) * gain_mag).unsqueeze(0).expand(H64_t.shape[0], -1)
dW_g = solve_woodbury_dense(H64_t, yg, H64_n, lam_null=25.0, lam_i=5e-2) # (2304, 64)
la, lb, _, dW_gr = svd_factorize_lora(dW_g, rank=rank)
pairs[f"blk.{l}.loop_mlp_gain.weight"] = (la, lb)
frobs.append(float(torch.norm(dW_gr).item()))
if r_forget_dir is not None:
yf = (unit_t(r_forget_dir) * forget_mag).unsqueeze(0).expand(H64_t.shape[0], -1)
dW_f = solve_woodbury_dense(H64_t, yf, H64_n, lam_null=25.0, lam_i=5e-2) # (2304, 64)
la, lb, _, dW_fr = svd_factorize_lora(dW_f, rank=rank)
pairs[f"blk.{l}.loop_mlp_forget.weight"] = (la, lb)
frobs.append(float(torch.norm(dW_fr).item()))
return pairs, {"mean_frob": round(float(np.mean(frobs)) if frobs else 0.0, 4)}
def write_lora_gguf(out_path: Path, arch: str, name: str, rank: int, pairs: Dict[str, Tuple[np.ndarray, np.ndarray]]) -> float:
writer = GGUFWriter(str(out_path), arch)
writer.add_string("general.type", "adapter")
writer.add_string("adapter.type", "lora")
writer.add_string("general.name", name)
writer.add_float32("adapter.lora.alpha", float(rank))
for tname, (la, lb) in sorted(pairs.items()):
writer.add_tensor(f"{tname}.lora_a", la)
writer.add_tensor(f"{tname}.lora_b", lb)
writer.write_header_to_file()
writer.write_kv_data_to_file()
writer.write_tensors_to_file()
writer.close()
return round(out_path.stat().st_size / 1024.0, 2)
def main():
t0 = time.time()
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"]
exp_map = json.loads(EXP_MAP_PATH.read_text(encoding="utf-8"))
tok = Tokenizer.from_file(str(ROOT / "tokenizer.json"))
def tids_word(w: str) -> List[int]:
out = []
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")
t_web = tids_word("web")
t_escal = tids_word("escal") + tids_word("escalate")
t_boxed = [int(tok.token_to_id("boxed"))]
t_ans = tids_word("Answer")
t_brace = [90]
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) -> List[int]:
out = []
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_web = idx_by("phase2_tool_boundary", label="boundary_web")
b_escal = idx_by("phase2_tool_boundary", label="boundary_escal")
b_text = idx_by("phase2_tool_boundary", label="boundary_text_restraint")
pf_box = idx_by("phase2_post_format", kind="boxed_or_answer")
pf_num = idx_by("phase2_post_format", kind="anti_brace_comma")
X_base_null = H[early_think + early_mid_stem + syntax_null]
manifest: Dict[str, Any] = {"arch": arch, "adapters": {}, "ablations": {}}
# 1. wsp_s1_think_close.gguf (V2 uniform rank=8, margin-calibrated for softcap=30)
print("\nSynthesizing V2 (rank=8, margin-calibrated) S1..S8...", flush=True)
R_PROD = 8
X_s1 = H[late_fast]
Y_s1 = [{TOK_END_MSG: +26.0, **{w: -14.0 for w in t_wait}} for _ in range(len(late_fast))]
la1, lb1, st1_head = solve_sparse_vocab_head(X_s1, Y_s1, X_base_null, n_vocab_padded, rank=R_PROD, lam_null=35.0)
p1_router, st1_r = build_router_pairs(list(range(18, 24)), X_s1, X_base_null, exp_map, ["u_end_think"], ["u_ruminate"], W_out_norm, delta_score=0.9, rank=R_PROD)
u_close_steer = u_dir([TOK_END_MSG], neg=t_wait)
k1_a, p1_a, st1_a = build_attn_out_pair(23, tmap, u_close_steer, X_base_null, W_out_norm, target_frob=0.25, rank=R_PROD)
pairs_s1 = {"output.weight": (la1, lb1), **p1_router, k1_a: p1_a}
sz1 = write_lora_gguf(ADAPTER_DIR / "wsp_s1_think_close.gguf", arch, "wsp_s1_think_close", R_PROD, pairs_s1)
manifest["adapters"]["wsp_s1_think_close"] = {"kb": sz1, "rank": R_PROD, "head": st1_head, "router": st1_r, "attn": st1_a}
print(f" S1 think_close ({sz1} KB): {st1_head} | router={st1_r}", flush=True)
# 2. wsp_s2_loop_damp.gguf (blk.12..17.loop_mlp_forget + loop_mlp_gain)
r_rum = u_dir(t_wait, neg=[TOK_END_MSG])
pairs_s2, st2_l = build_loop_ctrl_pairs(list(range(12, 18)), tmap, X_s1, X_base_null, r_gain_dir=-u_close_steer, r_forget_dir=r_rum, W_out_norm=W_out_norm, gain_mag=0.45, forget_mag=0.45, rank=R_PROD)
sz2 = write_lora_gguf(ADAPTER_DIR / "wsp_s2_loop_damp.gguf", arch, "wsp_s2_loop_damp", R_PROD, pairs_s2)
manifest["adapters"]["wsp_s2_loop_damp"] = {"kb": sz2, "rank": R_PROD, "loop": st2_l}
print(f" S2 loop_damp ({sz2} KB): {st2_l}", flush=True)
# 3. wsp_s3_loop_refine.gguf (blk.12..17.loop_mlp_gain + blk.17,23.attn_gate + blk.18..23.ffn_gate_inp STEM)
X_stem = H[early_mid_stem + late_stem]
X_s3_null = H[syntax_null + b_exec + b_write]
u_stem_steer = u_dir(t_boxed + t_ans, neg=t_wait)
p3_loop, st3_l = build_loop_ctrl_pairs(list(range(12, 18)), tmap, X_stem, X_s3_null, r_gain_dir=u_stem_steer, r_forget_dir=None, W_out_norm=W_out_norm, gain_mag=0.40, rank=R_PROD)
k3_g17, p3_g17, st3_g17 = build_attn_gate_pair(17, tmap, X_stem, X_s3_null, u_stem_steer, W_out_norm, target_shift=0.5, rank=R_PROD)
k3_g23, p3_g23, st3_g23 = build_attn_gate_pair(23, tmap, X_stem, X_s3_null, u_stem_steer, W_out_norm, target_shift=0.5, rank=R_PROD)
p3_router, st3_r = build_router_pairs(list(range(18, 24)), X_stem, X_s3_null, exp_map, ["u_stem"], ["u_ruminate"], W_out_norm, delta_score=0.7, rank=R_PROD)
sz3 = write_lora_gguf(ADAPTER_DIR / "wsp_s3_loop_refine.gguf", arch, "wsp_s3_loop_refine", R_PROD, {**p3_loop, k3_g17: p3_g17, k3_g23: p3_g23, **p3_router})
manifest["adapters"]["wsp_s3_loop_refine"] = {"kb": sz3, "rank": R_PROD, "loop": st3_l, "attn_gate17": st3_g17, "attn_gate23": st3_g23, "router": st3_r}
print(f" S3 loop_refine ({sz3} KB): loop={st3_l} | router={st3_r}", flush=True)
# 4. wsp_s4_tool_router.gguf (margin-calibrated for 41-54 base pre-tanh exec dominance)
s4_idxs = b_write + b_read + b_web + b_text
X_s4 = H[s4_idxs]
Y_s4 = (
[{w: +32.0 for w in t_write} | {e: -30.0 for e in t_exec} for _ in b_write]
+ [{r: +26.0 for r in t_read} | {e: -24.0 for e in t_exec} for _ in b_read]
+ [{wb: +26.0 for wb in t_web} | {e: -24.0 for e in t_exec} for _ in b_web]
+ [{TOK_CONTENT_TEXT: +12.0} | {e: -14.0 for e in t_exec} for _ in b_text]
)
X_s4_null = H[b_exec + syntax_null + early_think]
la4, lb4, st4_head = solve_sparse_vocab_head(X_s4, Y_s4, X_s4_null, n_vocab_padded, rank=R_PROD, lam_null=30.0)
p4_router, st4_r = build_router_pairs(list(range(18, 24)), H[b_write + b_read + b_web], X_s4_null, exp_map, ["u_write", "u_read", "u_web"], ["u_exec"], W_out_norm, delta_score=0.9, rank=R_PROD)
u_nowrite_exec = u_dir(t_write + t_read + [TOK_CONTENT_TEXT], neg=t_exec)
k4_a, p4_a, st4_a = build_attn_out_pair(23, tmap, u_nowrite_exec, X_s4_null, W_out_norm, target_frob=0.25, rank=R_PROD)
pairs_s4 = {"output.weight": (la4, lb4), **p4_router, k4_a: p4_a}
sz4 = write_lora_gguf(ADAPTER_DIR / "wsp_s4_tool_router.gguf", arch, "wsp_s4_tool_router", R_PROD, pairs_s4)
manifest["adapters"]["wsp_s4_tool_router"] = {"kb": sz4, "rank": R_PROD, "head": st4_head, "router": st4_r, "attn": st4_a}
print(f" S4 tool_router ({sz4} KB): {st4_head} | router={st4_r}", flush=True)
# 5. wsp_s5_handoff_gate.gguf (stronger on exec-misfiring missing-cred states cs6h_2 / che_0)
X_s5 = H[b_escal]
Y_s5 = []
for i in b_escal:
if meta[i].get("id") in ("cs6h_2", "che_0"):
Y_s5.append({es: +32.0 for es in t_escal} | {e: -30.0 for e in t_exec} | {r: -12.0 for r in t_read})
else:
Y_s5.append({es: +20.0 for es in t_escal} | {e: -18.0 for e in t_exec} | {r: -10.0 for r in t_read})
X_s5_null = H[b_exec + b_read + b_write + syntax_null]
la5, lb5, st5_head = solve_sparse_vocab_head(X_s5, Y_s5, X_s5_null, n_vocab_padded, rank=R_PROD, lam_null=30.0)
u_esc_steer = u_dir(t_escal, neg=t_exec)
k5_a, p5_a, st5_a = build_attn_out_pair(23, tmap, u_esc_steer, X_s5_null, W_out_norm, target_frob=0.25, rank=R_PROD)
pairs_s5 = {"output.weight": (la5, lb5), k5_a: p5_a}
sz5 = write_lora_gguf(ADAPTER_DIR / "wsp_s5_handoff_gate.gguf", arch, "wsp_s5_handoff_gate", R_PROD, pairs_s5)
manifest["adapters"]["wsp_s5_handoff_gate"] = {"kb": sz5, "rank": R_PROD, "head": st5_head, "attn": st5_a}
print(f" S5 handoff_gate({sz5} KB): {st5_head}", flush=True)
# 6. wsp_s6_term_action.gguf (decisive exec tool invocation & error recovery)
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_s6 = H[b_exec_nl_tb]
Y_s6 = [{e: +22.0 for e in t_exec} | {TOK_TOOL_JSON: +16.0, TOK_CONTENT_TEXT: -18.0} for _ in b_exec_nl_tb]
X_s6_null = H[b_text + b_write + b_read + b_escal + syntax_null]
la6, lb6, st6_head = solve_sparse_vocab_head(X_s6, Y_s6, X_s6_null, n_vocab_padded, rank=R_PROD, lam_null=30.0)
p6_router, st6_r = build_router_pairs(list(range(18, 24)), X_s6, X_s6_null, exp_map, ["u_exec"], ["u_ruminate", "u_write"], W_out_norm, delta_score=0.8, rank=R_PROD)
pairs_s6 = {"output.weight": (la6, lb6), **p6_router}
sz6 = write_lora_gguf(ADAPTER_DIR / "wsp_s6_term_action.gguf", arch, "wsp_s6_term_action", R_PROD, pairs_s6)
manifest["adapters"]["wsp_s6_term_action"] = {"kb": sz6, "rank": R_PROD, "head": st6_head, "router": st6_r}
print(f" S6 term_action ({sz6} KB): {st6_head} | router={st6_r}", flush=True)
# 7. wsp_s7_stem_settle.gguf (late STEM settlement protecting early/mid STEM derivations!)
X_s7 = H[late_stem]
Y_s7 = [{TOK_END_MSG: +26.0, **{w: -14.0 for w in t_wait}} for _ in late_stem]
la7, lb7, st7_head = solve_sparse_vocab_head(X_s7, Y_s7, X_base_null, n_vocab_padded, rank=R_PROD, lam_null=40.0)
p7_router, st7_r = build_router_pairs(list(range(18, 24)), X_s7, X_base_null, exp_map, ["u_end_think"], ["u_ruminate"], W_out_norm, delta_score=0.9, rank=R_PROD)
pairs_s7 = {"output.weight": (la7, lb7), **p7_router}
sz7 = write_lora_gguf(ADAPTER_DIR / "wsp_s7_stem_settle.gguf", arch, "wsp_s7_stem_settle", R_PROD, pairs_s7)
manifest["adapters"]["wsp_s7_stem_settle"] = {"kb": sz7, "rank": R_PROD, "head": st7_head, "router": st7_r}
print(f" S7 stem_settle ({sz7} KB): {st7_head} | router={st7_r}", flush=True)
# 8. wsp_s8_post_format.gguf (Phase-2 crisp \boxed{}/Answer: (X) + anti-{,} comma suppression)
X_s8 = H[pf_box + pf_num]
Y_s8 = (
[{b: +14.0 for b in t_boxed} | {a: +10.0 for a in t_ans} | {TOK_CONTENT_THINK: -18.0} for _ in pf_box]
+ [{b: -22.0 for b in t_brace} | {TOK_CONTENT_THINK: -14.0} for _ in pf_num]
)
la8, lb8, st8_head = solve_sparse_vocab_head(X_s8, Y_s8, H[syntax_null + early_think], n_vocab_padded, rank=R_PROD, lam_null=30.0)
sz8 = write_lora_gguf(ADAPTER_DIR / "wsp_s8_post_format.gguf", arch, "wsp_s8_post_format", R_PROD, {"output.weight": (la8, lb8)})
manifest["adapters"]["wsp_s8_post_format"] = {"kb": sz8, "rank": R_PROD, "head": st8_head}
print(f" S8 post_format ({sz8} KB): {st8_head}", flush=True)
# Keep Step 4 ablation_* GGUFs untouched if already built
abl_done = all((ADAPTER_DIR / f"{nm}.gguf").exists() for nm in ("ablation_output_head", "ablation_router", "ablation_attn", "ablation_loop"))
if abl_done:
print("\nKeeping existing Step 4 ablation_* GGUFs untouched.", flush=True)
else:
print("\nSynthesizing 4 single-site ablation GGUFs for S1+S4...", flush=True)
X_comb = torch.cat([X_s1, X_s4], dim=0)
Y_comb = Y_s1 + Y_s4
X_comb_null = H[early_think + early_mid_stem + syntax_null + b_exec]
la_ab, lb_ab, st_ab_h = solve_sparse_vocab_head(X_comb, Y_comb, X_comb_null, n_vocab_padded, rank=16, lam_null=24.0)
sz_ab_h = write_lora_gguf(ADAPTER_DIR / "ablation_output_head.gguf", arch, "ablation_output_head", 16, {"output.weight": (la_ab, lb_ab)})
p_ab_r = {}
for l in range(18, 24):
A_r = np.concatenate([p1_router[f"blk.{l}.ffn_gate_inp.weight"][0], p4_router[f"blk.{l}.ffn_gate_inp.weight"][0]], axis=0)
B_r = np.concatenate([p1_router[f"blk.{l}.ffn_gate_inp.weight"][1], p4_router[f"blk.{l}.ffn_gate_inp.weight"][1]], axis=1)
p_ab_r[f"blk.{l}.ffn_gate_inp.weight"] = (A_r, B_r)
sz_ab_r = write_lora_gguf(ADAPTER_DIR / "ablation_router.gguf", arch, "ablation_router", 16, p_ab_r)
k_a17, p_a17, _ = build_attn_out_pair(17, tmap, u_close_steer, X_base_null, W_out_norm, target_frob=0.22, rank=8)
k_g23, p_g23, _ = build_attn_gate_pair(23, tmap, X_comb, X_comb_null, unit_t(u_close_steer + u_nowrite_exec), W_out_norm, target_shift=0.6, rank=8)
A_23 = np.concatenate([p1_a[0], p4_a[0]], axis=0)
B_23 = np.concatenate([p1_a[1], p4_a[1]], axis=1)
pairs_ab_attn = {
"blk.23.attn_output.weight": (A_23, B_23),
k_a17: (np.pad(p_a17[0], ((0, 8), (0, 0))), np.pad(p_a17[1], ((0, 0), (0, 8)))),
k_g23: (np.pad(p_g23[0], ((0, 8), (0, 0))), np.pad(p_g23[1], ((0, 0), (0, 8)))),
}
sz_ab_a = write_lora_gguf(ADAPTER_DIR / "ablation_attn.gguf", arch, "ablation_attn", 16, pairs_ab_attn)
sz_ab_l = write_lora_gguf(ADAPTER_DIR / "ablation_loop.gguf", arch, "ablation_loop", 8, pairs_s2)
manifest["ablations"] = {
"ablation_output_head": {"kb": sz_ab_h, "stats": st_ab_h},
"ablation_router": {"kb": sz_ab_r},
"ablation_attn": {"kb": sz_ab_a},
"ablation_loop": {"kb": sz_ab_l, "stats": st2_l},
}
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} in {manifest['synthesis_s']}s", flush=True)
if __name__ == "__main__":
main()
|