File size: 17,772 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 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 | #!/usr/bin/env python3
"""Standalone Git CLI and Python API for Omen-REM-0.6B + Instant-CLS."""
from __future__ import annotations
import argparse
import json
import math
import subprocess
import sys
import time
from pathlib import Path
from typing import Any
import torch
import torch.nn.functional as F
from huggingface_hub import snapshot_download
from peft import PeftModel
from safetensors import safe_open
from safetensors.torch import load_file, save_file
from transformers import AutoModel, AutoTokenizer
DEFAULT_REPO_ID = "DevMortimer/Omen-REM-0.6B"
BASE_MODEL_ID = "Qwen/Qwen3-0.6B"
RIDGE_LAMBDA = 0.08
def _resolve_model_dir(repo_or_dir: str) -> Path:
local = Path(repo_or_dir)
if local.is_dir() and (local / "omen_heads.safetensors").is_file():
return local
return Path(snapshot_download(repo_id=repo_or_dir))
def _run_git(repo: Path, args: list[str]) -> str:
proc = subprocess.run(
["git", "-C", str(repo), *args],
capture_output=True,
text=True,
check=False,
)
if proc.returncode != 0:
raise RuntimeError(proc.stderr.strip() or f"git {' '.join(args)} failed")
return proc.stdout
def _extract_changed_files(diff_text: str) -> list[str]:
files: list[str] = []
for line in diff_text.splitlines():
if line.startswith("+++ b/"):
path = line[6:].strip()
if path and path not in files:
files.append(path)
return files
class OmenMemory:
def __init__(
self,
model_dir: Path,
state_dir: Path | None = None,
device: str | None = None,
) -> None:
self.model_dir = model_dir
self.state_dir = state_dir or Path(".omen")
self.device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
self.dtype = torch.float16 if self.device.type == "cuda" else torch.float32
self.tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_ID)
self.base = AutoModel.from_pretrained(BASE_MODEL_ID, dtype=self.dtype).to(self.device)
self.backbone = PeftModel.from_pretrained(self.base, str(model_dir)).eval()
heads_path = model_dir / "omen_heads.safetensors"
hipp_path = model_dir / "instant_cls_fast.safetensors"
self.heads = {k: v.float().to(self.device) for k, v in load_file(str(heads_path)).items()}
self.hipp = {k: v.float().to(self.device) for k, v in load_file(str(hipp_path)).items()}
with safe_open(str(heads_path), framework="pt") as sf:
meta = sf.metadata() or {}
self.file_paths: list[str] = json.loads(meta.get("file_catalog_paths", "[]"))
dim = int(self.hipp["W_hipp_ghost"].shape[1])
self.c_inv = torch.eye(dim, dtype=torch.float32, device=self.device) / RIDGE_LAMBDA
self.neo_ghost_delta = torch.zeros_like(self.hipp["W_hipp_ghost"])
self.neo_alarm_delta = torch.zeros_like(self.hipp["W_hipp_alarm"])
self.active_anchors = torch.zeros((0, dim), dtype=torch.float32, device=self.device)
self.veto_vecs = torch.zeros((0, dim), dtype=torch.float32, device=self.device)
self.veto_gains = torch.zeros((0,), dtype=torch.float32, device=self.device)
self._load_local_state()
@classmethod
def from_pretrained(
cls,
repo_or_dir: str = DEFAULT_REPO_ID,
state_dir: str | Path | None = None,
device: str | None = None,
) -> "OmenMemory":
model_dir = _resolve_model_dir(repo_or_dir)
sdir = Path(state_dir) if state_dir is not None else None
return cls(model_dir=model_dir, state_dir=sdir, device=device)
def _state_path(self) -> Path:
return self.state_dir / "instant_cls_state.safetensors"
def _load_local_state(self) -> None:
sp = self._state_path()
if not sp.is_file():
return
saved = {k: v.float().to(self.device) for k, v in load_file(str(sp)).items()}
with safe_open(str(sp), framework="pt") as sf:
meta = sf.metadata() or {}
if "file_catalog_paths" in meta:
self.file_paths = json.loads(meta["file_catalog_paths"])
for key in ("W_hipp_ghost", "W_hipp_alarm"):
if key in saved:
self.hipp[key] = saved[key]
if "C_inv" in saved:
self.c_inv = saved["C_inv"]
if "neo_ghost_delta" in saved:
self.neo_ghost_delta = saved["neo_ghost_delta"]
if "neo_alarm_delta" in saved:
self.neo_alarm_delta = saved["neo_alarm_delta"]
if "active_anchors" in saved:
self.active_anchors = saved["active_anchors"]
if "veto_vecs" in saved:
self.veto_vecs = saved["veto_vecs"]
if "veto_gains" in saved:
self.veto_gains = saved["veto_gains"]
def _save_local_state(self) -> None:
self.state_dir.mkdir(parents=True, exist_ok=True)
tensors = {
"W_hipp_ghost": self.hipp["W_hipp_ghost"].detach().cpu().float(),
"W_hipp_alarm": self.hipp["W_hipp_alarm"].detach().cpu().float(),
"C_inv": self.c_inv.detach().cpu().float(),
"neo_ghost_delta": self.neo_ghost_delta.detach().cpu().float(),
"neo_alarm_delta": self.neo_alarm_delta.detach().cpu().float(),
"active_anchors": self.active_anchors.detach().cpu().float(),
"veto_vecs": self.veto_vecs.detach().cpu().float(),
"veto_gains": self.veto_gains.detach().cpu().float(),
}
save_file(
tensors,
str(self._state_path()),
metadata={"file_catalog_paths": json.dumps(self.file_paths)},
)
def _ensure_file_slot(self, path: str) -> int:
if path in self.file_paths:
return self.file_paths.index(path)
self.file_paths.append(path)
dim = int(self.hipp["W_hipp_ghost"].shape[1])
zero_row = torch.zeros((1, dim), dtype=torch.float32, device=self.device)
self.hipp["W_hipp_ghost"] = torch.cat([self.hipp["W_hipp_ghost"], zero_row], dim=0)
self.neo_ghost_delta = torch.cat([self.neo_ghost_delta, zero_row], dim=0)
key_dim = int(self.heads["file_keys"].shape[1])
self.heads["file_keys"] = torch.cat(
[self.heads["file_keys"], torch.zeros((1, key_dim), dtype=torch.float32, device=self.device)],
dim=0,
)
return len(self.file_paths) - 1
def _lin(self, x: torch.Tensor, prefix: str) -> torch.Tensor:
return F.linear(x, self.heads[f"{prefix}.weight"], self.heads[f"{prefix}.bias"])
def _ln(self, x: torch.Tensor, prefix: str) -> torch.Tensor:
return F.layer_norm(x, (x.shape[-1],), self.heads[f"{prefix}.weight"], self.heads[f"{prefix}.bias"])
@torch.no_grad()
def _encode_lines(self, lines: list[str]) -> tuple[torch.Tensor, torch.Tensor, list[tuple[int, int]]]:
ids = [self.tokenizer.bos_token_id] if self.tokenizer.bos_token_id is not None else []
spans: list[tuple[int, int]] = []
for ln in lines:
st = len(ids)
toks = self.tokenizer.encode(ln + "\n", add_special_tokens=False)
ids.extend(toks or [self.tokenizer.eos_token_id])
spans.append((st, len(ids)))
mid_buf: list[torch.Tensor] = []
hook = self.base.layers[self.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=self.device)
hf = self.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()
return hm, hf, spans
def _h_vec(self, lines: list[str], hf: torch.Tensor, spans: list[tuple[int, int]]) -> torch.Tensor:
plus = [hf[s:e] for i, (s, e) in enumerate(spans) if lines[i].startswith("+") and not lines[i].startswith("+++") and e > s]
va = hf.mean(0) - self.hipp["mu_all"]
vp = (torch.cat(plus).mean(0) if plus else hf.mean(0)) - self.hipp["mu_plus"]
return torch.cat([F.normalize(va, dim=0, eps=1e-6), F.normalize(vp, dim=0, eps=1e-6)]) / math.sqrt(2.0)
@torch.no_grad()
def check_diff(
self,
diff_text: str,
top_k: int = 3,
use_instant_cls: bool = True,
) -> dict[str, Any]:
lines = [ln for ln in diff_text.splitlines() if ln.strip()] or ["(empty diff)"]
t0 = time.perf_counter()
hm, hf, spans = self._encode_lines(lines)
u = F.gelu(self._ln(self._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(self._ln(self._lin(torch.cat([hm[-1], hf[-1]]), "global_proj.0"), "global_proj.1"))
sal_w = F.softmax(self._lin(F.gelu(self._lin(u, "salience_net.0")), "salience_net.2").squeeze(-1), dim=0)
z_diff = self._ln((sal_w.unsqueeze(-1) * u).sum(0) + z_glob, "sub_norm")
loc_out = self._lin(F.gelu(self._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], self._lin(F.gelu(self._lin(z_diff, "locus_null_net.0")), "locus_null_net.2")])
q_ghost = F.normalize(self._lin(F.gelu(self._lin(z_diff, "ghost_q_proj.0")), "ghost_q_proj.2"), dim=-1)
sims = q_ghost @ self.heads["file_keys"].T
g_logits = sims * self.heads["log_scale"].exp().clamp(1.0, 40.0)
top2 = torch.topk(sims, k=min(2, sims.numel())).values
gap = top2[0] - (top2[1] if top2.numel() > 1 else 0.0)
loc_p = F.softmax(loc_ptr, dim=0)
a_in = torch.cat([z_diff, torch.stack([top2[0], gap, loc_p[:-1].max(), loc_p[-1]])])
a_logit = self._lin(F.gelu(self._lin(a_in, "alarm_head.0")), "alarm_head.2").squeeze(-1)
if use_instant_cls:
h_vec = self._h_vec(lines, hf, spans)
g_logits = g_logits + h_vec @ (self.hipp["W_hipp_ghost"] + self.neo_ghost_delta).T
a_logit = a_logit + (h_vec @ (self.hipp["W_hipp_alarm"] + self.neo_alarm_delta).T).squeeze(-1)
if self.veto_vecs.shape[0] > 0:
proj = self.veto_vecs @ h_vec
a_logit = a_logit - torch.sum(self.veto_gains * (proj * proj))
k = max(1, min(top_k, g_logits.numel()))
top_idx = torch.topk(g_logits, k=k).indices.tolist()
elapsed_ms = (time.perf_counter() - t0) * 1000.0
return {
"alarm_prob": round(float(torch.sigmoid(a_logit)), 4),
"guilty_line": int(loc_ptr.argmax()),
"top_ghost_files": [self.file_paths[i] if i < len(self.file_paths) else str(i) for i in top_idx],
"latency_ms": round(elapsed_ms, 2),
}
@torch.no_grad()
def learn_diff(self, diff_text: str, target_file: str, retire: bool = False) -> dict[str, Any]:
lines = [ln for ln in diff_text.splitlines() if ln.strip()] or ["(empty diff)"]
_hm, hf, spans = self._encode_lines(lines)
h_vec = self._h_vec(lines, hf, spans)
t0 = time.perf_counter()
if not retire:
target_idx = self._ensure_file_slot(target_file)
v = self.c_inv @ h_vec
inv_alpha = 1.0 / (1.0 + float(torch.dot(h_vec, v)))
self.c_inv = self.c_inv - inv_alpha * torch.outer(v, v)
target_vec = torch.zeros((len(self.file_paths),), dtype=torch.float32, device=self.device)
target_vec[target_idx] = 4.6
err = target_vec - (self.hipp["W_hipp_ghost"] @ h_vec)
self.hipp["W_hipp_ghost"] = self.hipp["W_hipp_ghost"] + inv_alpha * torch.outer(err, v)
err_a = 3.4 - float((self.hipp["W_hipp_alarm"] @ h_vec).squeeze())
self.hipp["W_hipp_alarm"] = self.hipp["W_hipp_alarm"] + inv_alpha * err_a * v.unsqueeze(0)
self.active_anchors = torch.cat([self.active_anchors, h_vec.unsqueeze(0)], dim=0)
mode = "sherman_morrison_write"
else:
r_perp = h_vec.clone()
if self.active_anchors.shape[0] > 0:
q_a, _ = torch.linalg.qr(self.active_anchors.T, mode="reduced")
r_perp = r_perp - q_a @ (q_a.T @ r_perp)
norm = float(torch.linalg.norm(r_perp))
if norm > 1e-6:
u_r = r_perp / norm
proj_g = self.hipp["W_hipp_ghost"] @ u_r
self.hipp["W_hipp_ghost"] = self.hipp["W_hipp_ghost"] - torch.outer(proj_g, u_r)
proj_a = self.hipp["W_hipp_alarm"] @ u_r
self.hipp["W_hipp_alarm"] = self.hipp["W_hipp_alarm"] - torch.outer(proj_a, u_r)
ref_energy = max(0.04, float(torch.dot(u_r, h_vec)) ** 2)
self.veto_vecs = torch.cat([self.veto_vecs, u_r.unsqueeze(0)], dim=0)
self.veto_gains = torch.cat(
[self.veto_gains, torch.tensor([7.4 / ref_energy], dtype=torch.float32, device=self.device)]
)
mode = "qr_orthogonal_erase"
elapsed_ms = (time.perf_counter() - t0) * 1000.0
self._save_local_state()
return {"mode": mode, "target_file": target_file, "update_ms": round(elapsed_ms, 3)}
@torch.no_grad()
def sleep_consolidate(self, repo: Path, days: int = 7) -> dict[str, Any]:
t0 = time.perf_counter()
log_out = _run_git(repo, ["log", f"--since={days} days ago", "--pretty=format:__COMMIT__", "--name-only"])
commits = [blk.splitlines() for blk in log_out.split("__COMMIT__") if blk.strip()]
co_change_commits = sum(1 for files in commits if len([f for f in files if f.strip()]) >= 2)
self.neo_ghost_delta = self.neo_ghost_delta * 0.96 + self.hipp["W_hipp_ghost"]
self.neo_alarm_delta = self.neo_alarm_delta * 0.96 + self.hipp["W_hipp_alarm"]
self.hipp["W_hipp_ghost"].zero_()
self.hipp["W_hipp_alarm"].zero_()
dim = int(self.hipp["W_hipp_ghost"].shape[1])
self.c_inv = torch.eye(dim, dtype=torch.float32, device=self.device) / RIDGE_LAMBDA
self._save_local_state()
elapsed_ms = (time.perf_counter() - t0) * 1000.0
return {
"days": days,
"commits_scanned": len(commits),
"co_change_commits": co_change_commits,
"hipp_norm_after_reset": 0.0,
"elapsed_ms": round(elapsed_ms, 2),
}
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Omen-REM-0.6B local Git memory CLI.")
parser.add_argument("--model", default=DEFAULT_REPO_ID, help="HF repo ID or local export directory.")
parser.add_argument("--repo", default=".", help="Path to target Git repository.")
sub = parser.add_subparsers(dest="cmd", required=True)
p_check = sub.add_parser("check", help="Scan current git diff for untouched files at risk.")
p_check.add_argument("--staged", action="store_true", help="Inspect staged diff only.")
p_check.add_argument("--ref", default=None, help="Diff against a specific git ref.")
p_check.add_argument("--top-k", type=int, default=3, help="Number of untouched files to display.")
p_check.add_argument("--threshold", type=float, default=0.5, help="Alarm probability threshold.")
p_check.add_argument("--json", action="store_true", dest="as_json", help="Emit JSON output.")
p_learn = sub.add_parser("learn", help="Teach or retire a cross-file rule in ~1 ms (Instant-CLS).")
p_learn.add_argument("commit", nargs="?", default="HEAD", help="Git commit to learn from (default: HEAD).")
p_learn.add_argument("--target", default=None, help="Untouched companion file path.")
p_learn.add_argument("--retire", action="store_true", help="Retire an obsolete rule via QR null-space erasure.")
p_sleep = sub.add_parser("sleep", help="Run nightly Bio-REM consolidation and reset fast weights.")
p_sleep.add_argument("--days", type=int, default=7, help="Lookback window in days.")
return parser
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
repo = Path(args.repo).resolve()
omen = OmenMemory.from_pretrained(args.model, state_dir=repo / ".omen")
if args.cmd == "check":
git_args = ["diff"]
if args.staged:
git_args.append("--cached")
if args.ref:
git_args.append(args.ref)
diff_text = _run_git(repo, git_args)
if not diff_text.strip():
print("No diff changes to check.")
return 0
res = omen.check_diff(diff_text, top_k=args.top_k)
if args.as_json:
print(json.dumps(res, indent=2))
else:
status = "ALERT" if res["alarm_prob"] >= args.threshold else "OK"
print(f"[Omen {status}] alarm={res['alarm_prob']:.2f} latency={res['latency_ms']:.1f}ms")
for idx, path in enumerate(res["top_ghost_files"], 1):
print(f" {idx}. {path}")
return 1 if res["alarm_prob"] >= args.threshold else 0
if args.cmd == "learn":
diff_text = _run_git(repo, ["show", "--no-color", args.commit])
changed = _extract_changed_files(diff_text)
target = args.target or (changed[-1] if len(changed) >= 2 else (changed[0] if changed else "unknown"))
res = omen.learn_diff(diff_text, target_file=target, retire=args.retire)
print(json.dumps(res, indent=2))
return 0
if args.cmd == "sleep":
res = omen.sleep_consolidate(repo=repo, days=args.days)
print(json.dumps(res, indent=2))
return 0
return 2
if __name__ == "__main__":
raise SystemExit(main())
|