Release Omen-REM-0.6B + Instant-CLS safetensors weights & omen_cli.py (DOI: 10.5281/zenodo.24607074)
9292ff9 verified Download inference_example.py from DevMortimer/Omen-REM-0.6B: direct link, hf CLI and curl.
- Browser
- Download file 4.88 kB
-
https://huggingface.co/DevMortimer/Omen-REM-0.6B/resolve/main/inference_example.py
- Command line
-
hf download hf://DevMortimer/Omen-REM-0.6B/inference_example.py
-
curl -L -o inference_example.py https://huggingface.co/DevMortimer/Omen-REM-0.6B/resolve/main/inference_example.py
4.88 kB
| #!/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"]) | |
| 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)) | |