#!/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())