File size: 4,878 Bytes
9292ff9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Minimal standalone inference for Omen-REM-0.6B + Instant-CLS safetensors checkpoints."""

from __future__ import annotations

import json, math, sys
from pathlib import Path
import torch, torch.nn.functional as F
import peft.import_utils as _pi
_pi.is_torchao_available = lambda: False
try:
    import peft.tuners.lora.torchao as _pt; _pt.is_torchao_available = lambda: False
except Exception:
    pass
from peft import PeftModel
from safetensors import safe_open
from safetensors.torch import load_file
from transformers import AutoModel, AutoTokenizer

CKPT_DIR = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parent
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
DTYPE = torch.float16 if DEVICE.type == "cuda" else torch.float32

# 5-line safetensors checkpoint loading (PEFT LoRA + Omen Heads + Instant-CLS Fast-Matrix)
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
base = AutoModel.from_pretrained("Qwen/Qwen3-0.6B", dtype=DTYPE).to(DEVICE)
backbone = PeftModel.from_pretrained(base, str(CKPT_DIR)).eval()
heads = {k: v.float().to(DEVICE) for k, v in load_file(str(CKPT_DIR / "omen_heads.safetensors")).items()}
hipp = {k: v.float().to(DEVICE) for k, v in load_file(str(CKPT_DIR / "instant_cls_fast.safetensors")).items()}
with safe_open(str(CKPT_DIR / "omen_heads.safetensors"), framework="pt") as sf:
    FILE_PATHS: list[str] = json.loads(sf.metadata().get("file_catalog_paths", "[]"))

_lin = lambda x, p: F.linear(x, heads[f"{p}.weight"], heads[f"{p}.bias"])
_ln = lambda x, p: F.layer_norm(x, (x.shape[-1],), heads[f"{p}.weight"], heads[f"{p}.bias"])


@torch.no_grad()
def predict_ghost_locus(lines: list[str], use_instant_cls: bool = True) -> dict[str, object]:
    ids = [tokenizer.bos_token_id] if tokenizer.bos_token_id is not None else []
    spans: list[tuple[int, int]] = []
    for ln in lines:
        st = len(ids)
        ids.extend(tokenizer.encode(ln + "\n", add_special_tokens=False) or [tokenizer.eos_token_id])
        spans.append((st, len(ids)))
    mid_buf: list[torch.Tensor] = []
    hook = base.layers[base.config.num_hidden_layers // 2 - 1].register_forward_hook(
        lambda _m, _i, o: mid_buf.append(o[0] if isinstance(o, tuple) else o)
    )
    try:
        inp = torch.tensor([ids], dtype=torch.long, device=DEVICE)
        hf = backbone(input_ids=inp, attention_mask=torch.ones_like(inp), use_cache=False).last_hidden_state[0].float()
        hm = mid_buf[-1][0].float()
    finally:
        hook.remove()
    u = F.gelu(_ln(_lin(torch.stack([torch.cat([hm[s:e].mean(0), hf[s:e].mean(0)]) for s, e in spans]), "line_proj.0"), "line_proj.1"))
    z_glob = F.gelu(_ln(_lin(torch.cat([hm[-1], hf[-1]]), "global_proj.0"), "global_proj.1"))
    sal_w = F.softmax(_lin(F.gelu(_lin(u, "salience_net.0")), "salience_net.2").squeeze(-1), dim=0)
    z_diff = _ln((sal_w.unsqueeze(-1) * u).sum(0) + z_glob, "sub_norm")
    loc_out = _lin(F.gelu(_lin(torch.cat([u, z_diff.unsqueeze(0).expand_as(u)], dim=-1), "locus_line_net.0")), "locus_line_net.2")
    loc_ptr = torch.cat([loc_out[:, 0], _lin(F.gelu(_lin(z_diff, "locus_null_net.0")), "locus_null_net.2")])
    q_ghost = F.normalize(_lin(F.gelu(_lin(z_diff, "ghost_q_proj.0")), "ghost_q_proj.2"), dim=-1)
    sims = q_ghost @ heads["file_keys"].T
    g_logits = sims * heads["log_scale"].exp().clamp(1.0, 40.0)
    top2, loc_p = torch.topk(sims, k=2).values, F.softmax(loc_ptr, dim=0)
    a_in = torch.cat([z_diff, torch.stack([top2[0], top2[0] - top2[1], loc_p[:-1].max(), loc_p[-1]])])
    a_logit = _lin(F.gelu(_lin(a_in, "alarm_head.0")), "alarm_head.2").squeeze(-1)
    if use_instant_cls:
        plus = [hf[s:e] for i, (s, e) in enumerate(spans) if lines[i].startswith("+") and not lines[i].startswith("+++") and e > s]
        va, vp = hf.mean(0) - hipp["mu_all"], (torch.cat(plus).mean(0) if plus else hf.mean(0)) - hipp["mu_plus"]
        h_vec = torch.cat([F.normalize(va, dim=0, eps=1e-6), F.normalize(vp, dim=0, eps=1e-6)]) / math.sqrt(2.0)
        g_logits = g_logits + h_vec @ hipp["W_hipp_ghost"].T
        a_logit = a_logit + (h_vec @ hipp["W_hipp_alarm"].T).squeeze(-1)
    top3 = torch.topk(g_logits, k=3).indices.tolist()
    return {"alarm_prob": round(float(torch.sigmoid(a_logit)), 4), "guilty_line": int(loc_ptr.argmax()), "top3_ghost_files": [FILE_PATHS[i] if i < len(FILE_PATHS) else str(i) for i in top3]}


if __name__ == "__main__":
    sample_diff = ["PR: chore: clean up node.ts internals (#4812)", "diff --git a/src/router/reg-exp-router/node.ts b/src/router/reg-exp-router/node.ts", "@@ -39,6 +39,8 @@ export class RegExpNode {", "   children: Map<string, RegExpNode>", "   addSegment(seg: string, child: Node) {", "+  const lookup = {} as Dict<RouteNode>", "+  lookup[part] = nextNode", "   return child"]
    print(json.dumps(predict_ghost_locus(sample_diff), indent=2))