File size: 32,244 Bytes
5b616ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
"""Bake best static 2-adapter WSP preset directly into Inkling-2-Mini-UD-IQ3_XXS.gguf (zero --lora flags).

Pipeline:
  Stage 2A: Sweep Base (0.0, 0.0) and 4 static scale pairs (s_think, s_term) on disjoint VAL_24
            using native /v1/chat/completions (`eff=0.2, temp=0.0`) with ZERO Phase-1/Phase-2 routing.
            Capture 3 live top-1 logit parity probes on the winning preset.
  Stage 2B: Zero-requantization GGUF stream-bake across the 734-tensor GGUF:
              - blk.17.loop_mlp_gain.weight : F32 -> F32
              - blk.23.attn_output.weight   : Q6_K -> F16
              - output.weight ([2304,201024]): Q5_K -> Q8_0 (via gguf.quantize)
              - remaining 731 tensors       : untouched raw-byte stream copy
  Stage 2C: Launch standalone `Inkling-2-Mini-WSP-UD-IQ3_XXS.gguf` with ZERO `--lora` flags
            (`/lora-adapters == []`), verify 3/3 top-1 logit parity and VAL_24, then run all 155 tasks
            (agent100 + stem45 + live WSL2 tbench10) natively at `eff=0.2, temp=0.0`.
"""
from __future__ import annotations

import argparse
import json
import math
import os
import re
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 GGMLQuantizationType, GGUFReader, GGUFValueType, GGUFWriter, dequantize, quantize

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")
sys.path.insert(0, r"C:\Users\jhjwi\.gemini\antigravity\scratch\qwen35-deepthought-stem-wsp")
sys.stdout.reconfigure(encoding="utf-8", line_buffering=True)

import disjoint_inkling2_data as dd  # noqa: E402
import wsp_tasks_9subspaces as tasks  # noqa: E402
from evaluate_inkling2_lite import (  # noqa: E402
    TRACK_A_AUDIT,
    TRACK_B_PATH,
    _compute_flips,
    _parse_decode_tps,
    _summarize_tps,
    run_agent100_lite,
    run_stem45_lite,
    run_tbench10_lite,
)
from inkling2_lite_router import (  # noqa: E402
    LITE_ADAPTER_DIR,
    LITE_ADAPTER_NAMES,
    Inkling2LiteRouter,
    LitePreset,
    extract_openai_response,
    prepare_messages_for_jinja,
    prepare_messages_openai,
)
from validate_inkling2_lite import eval_val24_lite  # noqa: E402
from validate_inkling2_sites import BASE_URL, LLAMA_SERVER, PORT, vram_mb  # noqa: E402

BASE_GGUF = ROOT / "gguf" / "Inkling-2-Mini-UD-IQ3_XXS.gguf"
OUT_GGUF = ROOT / "gguf" / "Inkling-2-Mini-WSP-UD-IQ3_XXS.gguf"
VERIFY_JSON = ROOT / "inkling2_baked_verify.json"
OUT_155_JSON = ROOT / "inkling2_baked_155_results.json"

LOG_STAGE_2A = ROOT / "val_baked_stage2a_inkling.log"
LOG_STAGE_2C_VAL = ROOT / "val_baked_stage2c_val_inkling.log"
LOG_STAGE_2C_155 = ROOT / "val_baked_stage2c_155_inkling.log"

SKIP_KV_KEYS = frozenset({"GGUF.version", "GGUF.tensor_count", "GGUF.kv_count", "general.architecture"})

CANDIDATE_SCALES: List[Tuple[str, float, float]] = [
    ("base_ref", 0.00, 0.00),
    ("static_0.65_0.80", 0.65, 0.80),
    ("static_0.50_0.60", 0.50, 0.60),
    ("static_0.65_0.45", 0.65, 0.45),
    ("static_0.50_0.00", 0.50, 0.00),
]


class InklingServerHandle:
    """Managed llama-server pointed explicitly at any Inkling GGUF path with optional LoRAs."""

    def __init__(self, model_path: Path, lora_paths: List[Path], log_path: Path, n_cpu_moe: int = 4):
        self.model_path = Path(model_path)
        self.lora_paths = list(lora_paths)
        self.log_path = Path(log_path)
        self.n_cpu_moe = n_cpu_moe
        self.proc = None
        self.fp = None
        self.adapters: List[Dict[str, Any]] = []
        self.vram_before: Dict[str, int] = {}
        self.vram_loaded: Dict[str, int] = {}
        self.startup_s = 0.0

    def __enter__(self) -> "InklingServerHandle":
        self.vram_before = vram_mb()
        cmd = [
            str(LLAMA_SERVER),
            "-m", str(self.model_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", str(self.n_cpu_moe),
            "--fit", "off",
        ]
        if self.lora_paths:
            cmd += ["--lora-init-without-apply", "--lora", ",".join(str(p) for p in self.lora_paths)]
        t0 = time.perf_counter()
        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"llama-server exited rc={self.proc.returncode}:\n{tail}")
            try:
                with urllib.request.urlopen(f"{BASE_URL}/health", timeout=2.0) as r:
                    if json.loads(r.read().decode()).get("status") == "ok":
                        with urllib.request.urlopen(f"{BASE_URL}/lora-adapters", timeout=10.0) as ra:
                            self.adapters = json.loads(ra.read().decode())
                        self.startup_s = round(time.perf_counter() - t0, 2)
                        self.vram_loaded = vram_mb()
                        return self
            except Exception:
                pass
            time.sleep(0.4)
        self.__exit__(None, None, None)
        raise TimeoutError("Timed out waiting for Inkling llama-server /health")

    def __exit__(self, *args: Any) -> None:
        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)
        self.proc = None
        if self.fp is not None:
            try:
                self.fp.close()
            except Exception:
                pass
            self.fp = None


class NativeStaticInklingRouter(Inkling2LiteRouter):
    """Forces native `/v1/chat/completions` on every prompt (no Phase-1/Phase-2 switching)."""

    def __init__(
        self,
        base_url: str,
        adapter_ids: List[int],
        static_scales: List[float],
        regime_label: str,
        allow_push: bool,
    ):
        super().__init__(base_url=base_url, adapter_ids=adapter_ids, preset=LitePreset("native_static"))
        self.static_scales = [float(x) for x in static_scales]
        self.regime_label = regime_label
        self.allow_push = allow_push

    def push_scales(self, scales: List[float], force: bool = False) -> float:
        if not self.allow_push or not self.adapter_ids:
            return 0.0
        return super().push_scales(scales, force=force)

    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: Any = None,
        seed: int = 42,
    ) -> Dict[str, Any]:
        if self.allow_push:
            self.push_scales(self.static_scales)
        body: Dict[str, Any] = {
            "model": "inkling2-mini",
            "messages": prepare_messages_openai(messages),
            "max_tokens": max_tokens,
            "temperature": temperature,
            "cache_prompt": False,
            "chat_template_kwargs": {"reasoning_effort": reasoning_effort},
        }
        if tools:
            body["tools"] = tools
        if temperature > 0:
            body["seed"] = seed
        req = urllib.request.Request(
            f"{self.base_url}/v1/chat/completions",
            data=json.dumps(body).encode("utf-8"),
            headers={"Content-Type": "application/json"},
            method="POST",
        )
        t0 = time.perf_counter()
        with urllib.request.urlopen(req, timeout=240) as resp:
            raw_resp = json.loads(resp.read().decode("utf-8"))
        infer_ms = (time.perf_counter() - t0) * 1000.0
        ext = extract_openai_response(raw_resp)
        comp_tok = ext["comp_tok"]
        tps = round(comp_tok / max(infer_ms / 1000.0, 1e-4), 2)
        srv_tps = round(ext["tps"], 2) if ext["tps"] > 0 else tps
        return {
            "content": ext["content"],
            "reasoning": ext["reasoning"],
            "tool_calls": ext["tool_calls"],
            "parsed_tool_calls": ext["parsed_tool_calls"],
            "finish_reason": ext["finish_reason"],
            "comp_tok": comp_tok,
            "prompt_tok": ext["prompt_tok"],
            "p1_tok": 0,
            "p2_tok": comp_tok,
            "p1_natural_close": (
                (ext["finish_reason"] != "length")
                or bool(ext["content"])
                or bool(ext["parsed_tool_calls"])
            ),
            "infer_ms": round(infer_ms, 1),
            "tps": tps,
            "server_decode_tps": srv_tps,
            "p2_server_tps": round(ext["tps"], 2) if ext["tps"] > 0 else None,
            "regime": self.regime_label,
            "p1_scales": list(self.static_scales),
            "p2_scales": list(self.static_scales),
        }


def copy_gguf_kv(reader: GGUFReader, writer: GGUFWriter, overrides: Dict[str, Tuple[Any, GGUFValueType, Any]]) -> None:
    seen = set()
    for key, field in reader.fields.items():
        if key in SKIP_KV_KEYS:
            continue
        seen.add(key)
        if key in overrides:
            val, vtype, sub_type = overrides[key]
        else:
            vtype = field.types[0]
            sub_type = field.types[1] if len(field.types) > 1 else None
            val = field.contents()
        if key == "general.alignment":
            writer.data_alignment = int(val)
        writer.add_key_value(key, val, vtype, sub_type=sub_type)
    for key, (val, vtype, sub_type) in overrides.items():
        if key not in seen and key not in SKIP_KV_KEYS:
            writer.add_key_value(key, val, vtype, sub_type=sub_type)


def compute_inkling_deltas(s_think: float, s_term: float) -> Dict[str, np.ndarray]:
    """Compute exact FP32 merged weight deltas across the 2 rank-8 Inkling adapters."""
    deltas: Dict[str, np.ndarray] = {}
    for fname, sc in [("wsp_lite_think_close.gguf", s_think), ("wsp_lite_term_action.gguf", s_term)]:
        if abs(sc) <= 1e-8:
            continue
        r = GGUFReader(str(LITE_ADAPTER_DIR / fname), "r")
        alpha = float(r.fields["adapter.lora.alpha"].contents())
        raw = {t.name: np.asarray(t.data).copy() for t in r.tensors}
        for b in sorted({k.rsplit(".", 1)[0] for k in raw}):
            la = raw[f"{b}.lora_a"].astype(np.float32)
            lb = raw[f"{b}.lora_b"].astype(np.float32)
            rank = int(la.shape[0])
            dw = float(sc) * (alpha / float(rank)) * (lb @ la)
            deltas[b] = dw if b not in deltas else (deltas[b] + dw)
    assert deltas, "No active deltas!"
    return deltas


def dequantize_to_f32(src_t: Any) -> Tuple[np.ndarray, str]:
    st = src_t.tensor_type
    if st == GGMLQuantizationType.F32:
        return np.asarray(src_t.data, dtype=np.float32), st.name
    if st == GGMLQuantizationType.F16:
        return np.asarray(src_t.data, dtype=np.float16).astype(np.float32), st.name
    return np.asarray(dequantize(src_t.data, st), dtype=np.float32), st.name


def probe_ids_n100(ids: List[int]) -> Dict[str, Any]:
    req = urllib.request.Request(
        f"{BASE_URL}/completion",
        data=json.dumps({"prompt": ids, "n_predict": 1, "temperature": 0.0, "n_probs": 100, "cache_prompt": False}).encode("utf-8"),
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=60) as r:
        res = json.loads(r.read().decode("utf-8"))
    cp = (res.get("completion_probabilities") or [{}])[0]
    entries = cp.get("top_logprobs") or cp.get("top_probs") or []
    by_id: Dict[int, float] = {}
    top5 = []
    for e in entries:
        tid = int(e.get("id", -1))
        lp = e.get("logprob")
        if lp is None and e.get("prob") is not None:
            lp = math.log(max(float(e["prob"]), 1e-30))
        if tid >= 0 and lp is not None:
            flp = round(float(lp), 5)
            by_id[tid] = flp
            if len(top5) < 5:
                top5.append((tid, e.get("token", ""), flp))
    tid0 = int(cp.get("id", top5[0][0] if top5 else -1))
    lp0 = cp.get("logprob")
    if lp0 is None and cp.get("prob") is not None:
        lp0 = math.log(max(float(cp["prob"]), 1e-30))
    if lp0 is None:
        lp0 = by_id.get(tid0)
    return {
        "top_id": tid0,
        "top_tok": cp.get("token") or res.get("content") or "",
        "top_lp": round(float(lp0), 5) if lp0 is not None else None,
        "by_id": by_id,
    }


def bake_inkling_gguf(
    deltas: Dict[str, np.ndarray],
    s_think: float,
    s_term: float,
    skip_bake: bool = False,
) -> Dict[str, Any]:
    t0 = time.time()
    reader = GGUFReader(str(BASE_GGUF), "r")
    arch = str(reader.fields["general.architecture"].contents())
    assert arch == "inkling2", f"Unexpected arch: {arch!r}"
    assert set(deltas.keys()).issubset({t.name for t in reader.tensors})

    expected_arrays: Dict[str, Tuple[GGMLQuantizationType, np.ndarray, str]] = {}
    for src_t in reader.tensors:
        name = src_t.name
        if name not in deltas:
            continue
        dw = deltas[name]
        w_deq, src_type_name = dequantize_to_f32(src_t)
        assert w_deq.shape == dw.shape, f"{name} shape mismatch {w_deq.shape} vs {dw.shape}"
        w_new = w_deq + dw
        if name == "output.weight":
            q8 = np.ascontiguousarray(quantize(w_new, GGMLQuantizationType.Q8_0), dtype=np.uint8)
            expected_arrays[name] = (GGMLQuantizationType.Q8_0, q8, src_type_name)
        elif src_t.tensor_type == GGMLQuantizationType.F32:
            arr32 = np.ascontiguousarray(w_new, dtype=np.float32)
            expected_arrays[name] = (GGMLQuantizationType.F32, arr32, src_type_name)
        else:
            arr16 = np.ascontiguousarray(w_new, dtype=np.float16)
            expected_arrays[name] = (GGMLQuantizationType.F16, arr16, src_type_name)
        print(
            f"  [prepare] {name:30s} {src_type_name:5s} -> {expected_arrays[name][0].name:4s} "
            f"(shape={list(expected_arrays[name][1].shape)}, +frob={np.linalg.norm(dw):.4f})",
            flush=True,
        )

    if not (skip_bake and OUT_GGUF.exists()):
        kv_overrides = {
            "general.name": ("Inkling-2-Mini-WSP-UD-IQ3_XXS", GGUFValueType.STRING, None),
            "general.description": (
                f"Modified derivative of thinkingmachines/Inkling-2-Mini (unsloth/Inkling-2-Mini-UD-IQ3_XXS.gguf) "
                f"with closed-form Weight-Space Programming static preset (s_think={s_think}, s_term={s_term}) baked into "
                f"{len(deltas)} tensors ({sorted(deltas.keys())}). Original model by Thinking Machines (Apache 2.0).",
                GGUFValueType.STRING,
                None,
            ),
        }
        tmp_out = OUT_GGUF.with_suffix(".gguf.tmp")
        if tmp_out.exists():
            tmp_out.unlink()

        writer = GGUFWriter(str(tmp_out), arch, use_temp_file=False)
        copy_gguf_kv(reader, writer, overrides=kv_overrides)

        plan: List[Tuple[str, Any, Optional[Tuple[GGMLQuantizationType, np.ndarray]]]] = []
        for src_t in reader.tensors:
            name = src_t.name
            if name in expected_arrays:
                dt, arr, _ = expected_arrays[name]
                if dt == GGMLQuantizationType.F32:
                    writer.add_tensor_info(name, arr.shape, np.dtype(np.float32), arr.nbytes, raw_dtype=None)
                elif dt == GGMLQuantizationType.F16:
                    writer.add_tensor_info(name, arr.shape, np.dtype(np.float16), arr.nbytes, raw_dtype=None)
                else:
                    sh_logical = tuple(int(x) for x in arr.shape)
                    writer.add_tensor_info(name, sh_logical, np.dtype(np.uint8), arr.nbytes, raw_dtype=dt)
                plan.append((name, src_t, (dt, arr)))
            else:
                st = src_t.tensor_type
                sh = tuple(int(x) for x in src_t.data.shape)
                if st == GGMLQuantizationType.F32:
                    writer.add_tensor_info(name, sh, np.dtype(np.float32), int(src_t.n_bytes), raw_dtype=None)
                elif st == GGMLQuantizationType.F16:
                    writer.add_tensor_info(name, sh, np.dtype(np.float16), int(src_t.n_bytes), raw_dtype=None)
                else:
                    writer.add_tensor_info(name, sh, np.dtype(np.uint8), int(src_t.n_bytes), raw_dtype=st)
                plan.append((name, src_t, None))

        writer.write_header_to_file()
        writer.write_kv_data_to_file()
        writer.write_ti_data_to_file()
        total_t = len(plan)
        try:
            for idx, (_nm, src_t, mod) in enumerate(plan, 1):
                if mod is not None:
                    writer.write_tensor_data(mod[1])
                elif src_t.tensor_type == GGMLQuantizationType.F32:
                    writer.write_tensor_data(np.ascontiguousarray(src_t.data, dtype=np.float32))
                elif src_t.tensor_type == GGMLQuantizationType.F16:
                    writer.write_tensor_data(np.ascontiguousarray(src_t.data, dtype=np.float16))
                else:
                    writer.write_tensor_data(np.ascontiguousarray(src_t.data, dtype=np.uint8))
                if idx % 150 == 0 or idx == total_t:
                    el = time.time() - t0
                    eta = (total_t - idx) * (el / idx)
                    print(f"  [stream inkling2] {idx}/{total_t} tensors | elapsed={el:.1f}s ETA={eta:.1f}s", flush=True)
        finally:
            writer.close()
        os.replace(tmp_out, OUT_GGUF)

    # Full structural verification on re-read
    out_r = GGUFReader(str(OUT_GGUF), "r")
    assert len(out_r.tensors) == len(reader.tensors) == 734
    src_map = {t.name: t for t in reader.tensors}
    out_map = {t.name: t for t in out_r.tensors}
    assert set(src_map.keys()) == set(out_map.keys())

    untouched = 0
    mod_stats: List[Dict[str, Any]] = []
    for tn, st in src_map.items():
        ot = out_map[tn]
        if tn not in expected_arrays:
            assert ot.tensor_type == st.tensor_type
            assert int(ot.n_bytes) == int(st.n_bytes)
            assert [int(x) for x in ot.shape] == [int(x) for x in st.shape]
            untouched += 1
        else:
            exp_dt, exp_arr, src_type_name = expected_arrays[tn]
            assert ot.tensor_type == exp_dt, f"{tn}: got {ot.tensor_type} vs {exp_dt}"
            assert [int(x) for x in ot.shape] == [int(x) for x in st.shape]
            got_arr = np.asarray(ot.data)
            assert np.array_equal(got_arr, exp_arr), f"{tn}: exact array mismatch on re-read!"
            mod_stats.append({
                "tensor": tn,
                "src_type": src_type_name,
                "dst_type": exp_dt.name,
                "shape": [int(x) for x in ot.shape],
                "nbytes": int(ot.n_bytes),
                "dw_frob": round(float(np.linalg.norm(deltas[tn])), 5),
            })

    src_bytes = int(BASE_GGUF.stat().st_size)
    out_bytes = int(OUT_GGUF.stat().st_size)
    return {
        "source_gguf": str(BASE_GGUF),
        "baked_gguf": str(OUT_GGUF),
        "s_think": s_think,
        "s_term": s_term,
        "source_bytes": src_bytes,
        "baked_bytes": out_bytes,
        "delta_bytes": out_bytes - src_bytes,
        "source_gib": round(src_bytes / (1024 ** 3), 4),
        "baked_gib": round(out_bytes / (1024 ** 3), 4),
        "delta_mib": round((out_bytes - src_bytes) / (1024 ** 2), 2),
        "total_tensors": len(out_r.tensors),
        "modified_tensor_count": len(mod_stats),
        "untouched_tensors": untouched,
        "bake_wall_s": round(time.time() - t0, 2),
        "modified_tensors": sorted(mod_stats, key=lambda x: x["tensor"]),
    }


def main() -> None:
    ap = argparse.ArgumentParser(description="Bake static 2-adapter preset into Inkling-2-Mini standalone GGUF.")
    ap.add_argument("--skip-bake", action="store_true")
    args = ap.parse_args()

    t_all0 = time.time()
    dd.verify_zero_overlap()
    val24 = dd.load_disjoint_splits()["val24"]
    lite_paths = [LITE_ADAPTER_DIR / f"{n}.gguf" for n in LITE_ADAPTER_NAMES]

    probe_specs = [
        ("val_math_0", [{"role": "user", "content": f"Solve the following mathematics problem carefully. Put your final simplified answer inside \\boxed{{}}.\n\n{val24['val_math_7'][0]['problem']}"}], None),
        ("val_nl2bash_0", [{"role": "user", "content": f"Execute a single Linux shell command via `exec` to accomplish this task: {val24['val_nl2bash_6'][0]['query']}"}], tasks.WORKER_TOOLS),
        ("val_restraint_0", val24["val_restraint_exec_3"][0]["messages"], val24["val_restraint_exec_3"][0]["tools"]),
    ]

    # Stage 2A: Native /v1/chat/completions static sweep on VAL_24
    sweep_rows: List[Dict[str, Any]] = []
    live_probes: Dict[str, Any] = {}
    probe_ids: Dict[str, List[int]] = {}
    with InklingServerHandle(BASE_GGUF, lora_paths=lite_paths, log_path=LOG_STAGE_2A, n_cpu_moe=4) as srv2a:
        id_by_name = {Path(a["path"]).stem: int(a["id"]) for a in srv2a.adapters}
        aids = [id_by_name[n] for n in LITE_ADAPTER_NAMES]
        stage2a_vram = srv2a.vram_loaded
        print(f"=== Stage 2A Ready ({srv2a.startup_s}s) | VRAM={stage2a_vram['used_mb']} MiB ===", flush=True)

        t_sw = time.time()
        for idx, (arm_nm, st_th, st_tm) in enumerate(CANDIDATE_SCALES, 1):
            router = NativeStaticInklingRouter(
                BASE_URL, aids, static_scales=[st_th, st_tm], regime_label=f"native_{arm_nm}", allow_push=True
            )
            r = eval_val24_lite(router, val24, arm_nm)
            r["s_think"] = st_th
            r["s_term"] = st_tm
            sweep_rows.append(r)
            el = time.time() - t_sw
            eta = (len(CANDIDATE_SCALES) - idx) * (el / idx)
            print(
                f"  [Stage 2A {idx}/{len(CANDIDATE_SCALES)}] {arm_nm:18s} => {r['pass']}/24 ({r['pct']}%) "
                f"| cut={r['cut_mid_think']} | {r['by_group']} | srv={r['mean_srv_tps']} tok/s | ETA={eta:.1f}s",
                flush=True,
            )

        base_val24 = sweep_rows[0]
        static_cands = sweep_rows[1:]
        best_cand = max(
            static_cands,
            key=lambda x: (
                x["pass"],
                -x["cut_mid_think"],
                int(x["by_group"]["val_restraint_exec"].split("/")[0]),
                int(x["by_group"]["val_nl2bash"].split("/")[0]),
                x["mean_srv_tps"],
            ),
        )
        print(
            f"\n=== Selected Static Inkling Winner: {best_cand['arm']} "
            f"(s_think={best_cand['s_think']}, s_term={best_cand['s_term']}) => "
            f"{best_cand['pass']}/24 (Base={base_val24['pass']}/24) ===",
            flush=True,
        )

        # Render exact prompt IDs & capture 3 live logit parity probes under winning static scales
        p_router = NativeStaticInklingRouter(
            BASE_URL, aids, static_scales=[best_cand["s_think"], best_cand["s_term"]], regime_label="probe", allow_push=True
        )
        p_router.push_scales([best_cand["s_think"], best_cand["s_term"]], force=True)
        for pkey, msgs, tdefs in probe_specs:
            rendered = (
                p_router.tmpl.render(messages=prepare_messages_for_jinja(msgs), tools=tdefs, reasoning_effort=0.2)
                + "<|message_model|><|content_thinking|>"
            )
            probe_ids[pkey] = [int(t) for t in p_router.tok.encode(rendered, add_special_tokens=False).ids]
            live_probes[pkey] = probe_ids_n100(probe_ids[pkey])
            print(
                f"  [LIVE PROBE] {pkey:18s}: top_id={live_probes[pkey]['top_id']} top_lp={live_probes[pkey]['top_lp']}",
                flush=True,
            )

    time.sleep(0.5)

    # Stage 2B: Stream-bake into Inkling-2-Mini-WSP-UD-IQ3_XXS.gguf
    print(f"\n=== Stage 2B: Baking {OUT_GGUF.name} ===", flush=True)
    deltas = compute_inkling_deltas(best_cand["s_think"], best_cand["s_term"])
    bake_info = bake_inkling_gguf(deltas, best_cand["s_think"], best_cand["s_term"], skip_bake=args.skip_bake)
    print(
        f"Baked OK: {OUT_GGUF.name} | {bake_info['baked_bytes']:,} bytes ({bake_info['baked_gib']} GiB, "
        f"+{bake_info['delta_mib']} MiB) | {bake_info['bake_wall_s']}s",
        flush=True,
    )

    # Stage 2C.1: Verify 3/3 Logit Parity + VAL_24 with ZERO --lora flags
    baked_probes: Dict[str, Any] = {}
    with InklingServerHandle(OUT_GGUF, lora_paths=[], log_path=LOG_STAGE_2C_VAL, n_cpu_moe=4) as srv2c_v:
        assert srv2c_v.adapters == [], f"Expected zero runtime LoRAs, got {srv2c_v.adapters}"
        v_loaded_val = srv2c_v.vram_loaded
        print(f"=== Stage 2C.1 VAL_24 Ready ({srv2c_v.startup_s}s, /lora-adapters=[], VRAM={v_loaded_val['used_mb']} MiB) ===", flush=True)
        assert v_loaded_val["used_mb"] < 11950, f"Loaded VRAM too high: {v_loaded_val}"

        for pkey, _, _ in probe_specs:
            baked_probes[pkey] = probe_ids_n100(probe_ids[pkey])
            d_lp = round(abs(float(baked_probes[pkey]["top_lp"]) - float(live_probes[pkey]["top_lp"])), 5)
            print(
                f"  [BAKED PROBE] {pkey:18s}: live={live_probes[pkey]['top_id']} baked={baked_probes[pkey]['top_id']} |Δ|={d_lp:.5f}",
                flush=True,
            )

        baked_val_router = NativeStaticInklingRouter(
            BASE_URL, [], static_scales=[best_cand["s_think"], best_cand["s_term"]], regime_label="baked_static", allow_push=False
        )
        baked_val24 = eval_val24_lite(baked_val_router, val24, "baked_static")

    time.sleep(0.3)
    val_dec_tps = _summarize_tps(_parse_decode_tps(LOG_STAGE_2C_VAL.read_text(encoding="utf-8", errors="replace")))
    parity_rows = []
    for pkey, _, _ in probe_specs:
        lp_l, lp_b = live_probes[pkey], baked_probes[pkey]
        common = set(lp_l["by_id"].keys()) & set(lp_b["by_id"].keys())
        max_ov = max(abs(lp_b["by_id"][k] - lp_l["by_id"][k]) for k in common) if common else 0.0
        parity_rows.append({
            "prompt": pkey,
            "live_top_id": lp_l["top_id"],
            "baked_top_id": lp_b["top_id"],
            "top1_match": int(lp_b["top_id"]) == int(lp_l["top_id"]),
            "live_top_lp": lp_l["top_lp"],
            "baked_top_lp": lp_b["top_lp"],
            "abs_delta_top1_lp": round(abs(float(lp_b["top_lp"]) - float(lp_l["top_lp"])), 5),
            "max_abs_delta_top100_lp": round(max_ov, 5),
        })
    verify_doc = {
        "bake": bake_info,
        "stage2a_vram_loaded": stage2a_vram,
        "stage2c_val_vram_loaded": v_loaded_val,
        "vram_after_val": vram_mb(),
        "val24_sweep": [
            {k: v for k, v in r.items() if k != "records"}
            for r in sweep_rows
        ],
        "selected_static_preset": {"arm": best_cand["arm"], "s_think": best_cand["s_think"], "s_term": best_cand["s_term"]},
        "logit_parity_vs_live_lora": {
            "prompts": parity_rows,
            "top1_match_count": sum(1 for r in parity_rows if r["top1_match"]),
            "total_prompts": len(parity_rows),
            "max_abs_delta_top1_lp": max(r["abs_delta_top1_lp"] for r in parity_rows),
            "max_abs_delta_top100_lp": max(r["max_abs_delta_top100_lp"] for r in parity_rows),
        },
        "baked_val24": {k: v for k, v in baked_val24.items() if k != "records"},
        "baked_val24_decode_tps": val_dec_tps,
    }
    VERIFY_JSON.write_text(json.dumps(verify_doc, indent=2), encoding="utf-8")
    assert verify_doc["logit_parity_vs_live_lora"]["top1_match_count"] == 3, f"Parity mismatch: {parity_rows}"

    # Stage 2C.2: Full 155-Task Standalone Native Evaluation
    track_a = json.loads(TRACK_A_AUDIT.read_text(encoding="utf-8"))
    track_b = json.loads(TRACK_B_PATH.read_text(encoding="utf-8"))
    t_155_0 = time.time()
    with InklingServerHandle(OUT_GGUF, lora_paths=[], log_path=LOG_STAGE_2C_155, n_cpu_moe=4) as srv2c_e:
        assert srv2c_e.adapters == [], f"Expected zero runtime LoRAs, got {srv2c_e.adapters}"
        peak_tracker = [srv2c_e.vram_loaded["used_mb"]]
        assert srv2c_e.vram_loaded["used_mb"] < 11950, f"Loaded VRAM too high: {srv2c_e.vram_loaded}"
        print(
            f"\n=== Stage 2C.2 Full 155-Task Eval READY ({srv2c_e.startup_s}s, /lora-adapters=[], "
            f"VRAM={srv2c_e.vram_loaded['used_mb']} MiB free={srv2c_e.vram_loaded['free_mb']} MiB) ===",
            flush=True,
        )
        router_155 = NativeStaticInklingRouter(
            BASE_URL, [], static_scales=[best_cand["s_think"], best_cand["s_term"]], regime_label="baked_static", allow_push=False
        )
        a100 = run_agent100_lite(router_155, peak_tracker)
        s45 = run_stem45_lite(router_155, peak_tracker)
        tb10 = run_tbench10_lite(router_155, peak_tracker)
        v_loaded_155 = srv2c_e.vram_loaded

    time.sleep(0.5)
    dec_155_tps = _summarize_tps(_parse_decode_tps(LOG_STAGE_2C_155.read_text(encoding="utf-8", errors="replace")))
    post_v = vram_mb()

    base_a100 = int(track_a["step3b_agent100"]["overall_pass"])
    base_s45 = int(track_a["step3c_stem45"]["overall_pass"])
    base_tb10 = int(track_a["step3d_tbench10"]["pass"])
    base_tot = base_a100 + base_s45 + base_tb10
    baked_tot = a100["overall_pass"] + s45["overall_pass"] + tb10["pass"]

    res155 = {
        "model": "thinkingmachines/Inkling-2-Mini",
        "quant": "UD-IQ3_XXS",
        "selected_static_preset": {"arm": best_cand["arm"], "s_think": best_cand["s_think"], "s_term": best_cand["s_term"]},
        "track_a_base_ref": {"agent100_pass": base_a100, "stem45_pass": base_s45, "tbench10_pass": base_tb10, "combined_pass": base_tot},
        "track_b_v2_ref": {
            "agent100_pass": int(track_b["arm2_agent100"]["overall_pass"]),
            "stem45_pass": int(track_b["arm2_stem45"]["overall_pass"]),
            "tbench10_pass": int(track_b["arm2_tbench10"]["pass"]),
        },
        "vram_loaded": v_loaded_155,
        "peak_vram_mb": peak_tracker[0],
        "vram_after_shutdown": post_v,
        "agent100": a100,
        "flips_agent100_vs_base": _compute_flips(a100["records"], track_a["step3b_agent100"]["records"]),
        "stem45": s45,
        "flips_stem45_vs_base": _compute_flips(s45["records"], track_a["step3c_stem45"]["records"]),
        "tbench10": tb10,
        "flips_tbench10_vs_base": _compute_flips(tb10["records"], track_a["step3d_tbench10"]["records"]),
        "combined_summary": {
            "combined_pass": baked_tot,
            "combined_total": 155,
            "combined_pct": round(100.0 * baked_tot / 155.0, 1),
            "delta_vs_base": baked_tot - base_tot,
        },
        "server_log_decode_tps": dec_155_tps,
        "total_eval_s": round(time.time() - t_155_0, 1),
        "total_wall_s": round(time.time() - t_all0, 1),
    }
    OUT_155_JSON.write_text(json.dumps(res155, indent=2), encoding="utf-8")

    print(
        f"\n=== STANDALONE BAKED INKLING-2-MINI COMPLETE ({res155['total_wall_s']}s) ===\n"
        f"  Combined : Base {base_tot}/155 -> Baked {baked_tot}/155 ({res155['combined_summary']['combined_pct']}%, {baked_tot - base_tot:+d})\n"
        f"  Breakdown: agent100={a100['overall_pass']}/100 | stem45={s45['overall_pass']}/45 (cut={s45['cut_mid_think']}) | tbench10={tb10['pass']}/10\n"
        f"  Speed/VRAM: {dec_155_tps} | loaded={v_loaded_155['used_mb']} peak={peak_tracker[0]} post={post_v['used_mb']} MiB",
        flush=True,
    )
    assert post_v["used_mb"] < 1200, f"Post-shutdown VRAM too high: {post_v}"
    assert (dec_155_tps["median"] or 0.0) >= 25.0, f"Severe decode slowdown: {dec_155_tps}"


if __name__ == "__main__":
    main()