File size: 8,134 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
"""Step 1B: 128-Expert Spectral Discovery across Inkling-2-Mini blocks 18..23."""
from __future__ import annotations

import gc
import json
from pathlib import Path
from typing import Dict, List

import numpy as np
import torch
from gguf import GGUFReader, dequantize
from tokenizers import Tokenizer

ROOT = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\inkling2-mini-wsp")
GGUF_PATH = ROOT / "gguf" / "Inkling-2-Mini-UD-IQ3_XXS.gguf"
OUT_PATH = ROOT / "expert_spectral_map.json"


def unit_np(v: np.ndarray, axis: int = -1) -> np.ndarray:
    return v / (np.linalg.norm(v, axis=axis, keepdims=True) + 1e-8)


def main():
    tok = Tokenizer.from_file(str(ROOT / "tokenizer.json"))
    tc = json.loads((ROOT / "tokenizer_config.json").read_text(encoding="utf-8"))
    added_rev = {
        v["content"]: int(k)
        for k, v in tc.get("added_tokens_decoder", {}).items()
        if isinstance(v, dict) and "content" in v
    }

    def tid_exact(s: str) -> int:
        if s in added_rev:
            return added_rev[s]
        tid = tok.token_to_id(s)
        if tid is not None:
            return int(tid)
        ids = tok.encode(s, add_special_tokens=False).ids
        return int(ids[0])

    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:
            enc = tok.encode(w, add_special_tokens=False).ids
            if enc:
                out.append(int(enc[0]))
        return list(dict.fromkeys(out))

    reader = GGUFReader(str(GGUF_PATH), "r")
    tmap = {t.name: t for t in reader.tensors}

    # Dequantize output.weight once -> shape (201024, 2304), use unpadded vocab [:200058]
    print("Dequantizing output.weight & output_norm.weight...", flush=True)
    out_t = tmap["output.weight"]
    W_out = np.asarray(dequantize(out_t.data, out_t.tensor_type), dtype=np.float32)[:200058]
    w_norm = np.array(tmap["output_norm.weight"].data, dtype=np.float32).reshape(-1)
    mean_u = W_out.mean(axis=0)

    def concept_dir(pos_ids: List[int], neg_ids: List[int] = ()) -> np.ndarray:
        p = unit_np((W_out[pos_ids] - mean_u).mean(axis=0) * w_norm)
        if neg_ids:
            n = unit_np((W_out[neg_ids] - mean_u).mean(axis=0) * w_norm)
            return unit_np(p - 0.5 * n)
        return p

    concepts: Dict[str, np.ndarray] = {
        "u_end_think": concept_dir([tid_exact("<|end_message|>")]),
        "u_ruminate": concept_dir(
            tids_word("Wait") + tids_word("Actually") + tids_word("Hmm") + tids_word("However") + tids_word("Alternatively")
        ),
        "u_exec": concept_dir(tids_word("exec"), tids_word("write") + tids_word("read")),
        "u_write": concept_dir(tids_word("write"), tids_word("exec")),
        "u_read": concept_dir(tids_word("read"), tids_word("exec")),
        "u_web": concept_dir(tids_word("web"), tids_word("exec")),
        "u_escal": concept_dir(tids_word("escal") + [tid_exact("escalate_handoff") if tid_exact("escalate_handoff") else tids_word("escal")[0]], tids_word("exec")),
        "u_code": concept_dir(tids_word("def") + tids_word("return") + tids_word("python")),
        "u_stem": concept_dir([tid_exact("boxed")] + tids_word("Answer")),
    }
    concept_names = list(concepts.keys())
    C_mat = np.stack([concepts[k] for k in concept_names], axis=0)  # (K, 2304)

    del W_out
    gc.collect()

    layer_results = {}
    concept_global: Dict[str, List[dict]] = {k: [] for k in concept_names}

    print("Scanning blk.18..23 experts one layer at a time...", flush=True)
    for l in range(18, 24):
        W_r = np.array(tmap[f"blk.{l}.ffn_gate_inp.weight"].data, dtype=np.float32).reshape(128, 2304)
        fp = np.array(tmap[f"blk.{l}.ffn_post_conv.weight"].data, dtype=np.float32).reshape(2304, 4)
        # Current-token ffn_post_conv multiplier from inkling2.cpp: (cur + w_tap3 * cur) / sqrt(n_conv + 1) = (1 + w_tap3) / sqrt(5)
        eff_scale = ((1.0 + fp[:, 3]) / np.sqrt(5.0)).astype(np.float32)

        exp_t = tmap[f"blk.{l}.ffn_down_exps.weight"]
        W_exp = np.asarray(dequantize(exp_t.data, exp_t.tensor_type), dtype=np.float32)  # (128, 2304, 1152)
        # Effective hidden contribution scaled by ffn_post_conv and output_norm weighting
        # Use torch GPU if available for fast batch matmul!
        dev = "cuda" if torch.cuda.is_available() else "cpu"
        eff_t = torch.from_numpy((eff_scale * w_norm)[:, None]).to(dev)  # (2304, 1)
        C_t = torch.from_numpy(C_mat).to(dev)  # (K, 2304)
        W_r_t = torch.from_numpy(W_r).to(dev)  # (128, 2304)
        router_align = (W_r_t @ C_t.T).cpu().numpy()  # (128, K)

        max_pos = np.zeros((128, len(concept_names)), dtype=np.float32)
        max_neg = np.zeros((128, len(concept_names)), dtype=np.float32)
        top16_signed = np.zeros((128, len(concept_names)), dtype=np.float32)

        for e in range(128):
            We = torch.from_numpy(W_exp[e]).to(dev) * eff_t  # (2304, 1152)
            We_unit = We / (torch.norm(We, dim=0, keepdim=True) + 1e-8)
            dots = (C_t @ We_unit).cpu().numpy()  # (K, 1152)
            max_pos[e] = dots.max(axis=1)
            max_neg[e] = dots.min(axis=1)
            # Top-16 signed energy difference (mean of top-16 positive minus mean of top-16 negative)
            s_sorted = np.sort(dots, axis=1)
            top16_signed[e] = s_sorted[:, -16:].mean(axis=1) - (-s_sorted[:, :16].mean(axis=1))

        del W_exp, eff_t, C_t, W_r_t
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
        gc.collect()

        layer_summary = {}
        for ci, cname in enumerate(concept_names):
            # Rank by top16_signed + 0.5 * max_pos
            score_pos = top16_signed[:, ci] + 0.5 * max_pos[:, ci]
            order = np.argsort(-score_pos)
            top_pos_idx = order[:10].tolist()
            top_neg_idx = order[-10:][::-1].tolist()
            layer_summary[cname] = {
                "top_pos": [
                    {
                        "expert": int(e),
                        "top16_signed": round(float(top16_signed[e, ci]), 4),
                        "max_pos": round(float(max_pos[e, ci]), 4),
                        "router_cos": round(float(router_align[e, ci]), 4),
                    }
                    for e in top_pos_idx
                ],
                "top_neg": [
                    {
                        "expert": int(e),
                        "top16_signed": round(float(top16_signed[e, ci]), 4),
                        "min_neg": round(float(max_neg[e, ci]), 4),
                        "router_cos": round(float(router_align[e, ci]), 4),
                    }
                    for e in top_neg_idx
                ],
            }
            for e in order[:4]:
                concept_global[cname].append({
                    "layer": l,
                    "expert": int(e),
                    "score": round(float(score_pos[e]), 4),
                    "top16_signed": round(float(top16_signed[e, ci]), 4),
                    "max_pos": round(float(max_pos[e, ci]), 4),
                    "router_cos": round(float(router_align[e, ci]), 4),
                })

        layer_results[str(l)] = layer_summary
        print(
            f"  blk.{l}: u_end_think top_e={layer_summary['u_end_think']['top_pos'][0]} | "
            f"u_ruminate top_e={layer_summary['u_ruminate']['top_pos'][0]} | "
            f"u_exec top_e={layer_summary['u_exec']['top_pos'][0]}",
            flush=True,
        )

    for cname in concept_names:
        concept_global[cname] = sorted(concept_global[cname], key=lambda x: -x["score"])[:12]

    out = {
        "model": "Inkling-2-Mini-UD-IQ3_XXS",
        "layers_scanned": list(range(18, 24)),
        "concepts": concept_names,
        "global_top_experts": concept_global,
        "by_layer": layer_results,
    }
    OUT_PATH.write_text(json.dumps(out, indent=2), encoding="utf-8")
    print(f"Saved 128-Expert Spectral Map -> {OUT_PATH}", flush=True)


if __name__ == "__main__":
    main()