File size: 9,860 Bytes
b92a420
 
 
 
 
 
 
 
 
 
 
 
 
7249e51
b92a420
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d31ea88
 
b92a420
 
 
 
 
 
 
 
d31ea88
 
 
 
 
 
 
 
cbf5d82
d31ea88
 
cbf5d82
 
d31ea88
cbf5d82
d31ea88
 
 
b92a420
aa72d8d
 
d31ea88
 
aa72d8d
 
b92a420
aa72d8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b92a420
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7249e51
b92a420
 
 
 
7249e51
 
 
 
b92a420
 
 
 
 
 
 
 
 
 
 
7249e51
 
b92a420
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Cortex-System-one: Standalone Typed Decision Inference Script
Model: Cortex-System-one (0.574B parameters)
Evaluation: S1MB Official Typed Decisions Champion (44.73%)
"""

import os
import sys
import json
import re
import torch
import torch.nn.functional as F
import time
from pathlib import Path
from typing import List, Tuple, Dict, Any, Optional, Sequence
import tiktoken

from Model import Cortex


def option_label(index: int) -> str:
    n = index + 1
    chars = []
    while n:
        n, rem = divmod(n - 1, 26)
        chars.append(chr(65 + rem))
    return "".join(reversed(chars))


def find_option_spans(token_ids: Sequence[int], enc: Any, options: Sequence[str]) -> List[Tuple[int, int]]:
    """Resolves token spans for each candidate option in the input prompt."""
    try:
        tok_bytes = [enc.decode_single_token_bytes(t) for t in token_ids]
        prompt_bytes = b"".join(tok_bytes)
        byte_to_tok = []
        for tok_idx, b in enumerate(tok_bytes):
            byte_to_tok.extend([tok_idx] * len(b))

        char_cursor = 0
        spans = []
        for opt in options:
            clean_opt = opt.strip()
            opt_bytes = clean_opt.encode("utf-8")
            pos = prompt_bytes.find(opt_bytes, char_cursor)
            if pos < 0:
                unlabeled = re.sub(r"^[A-Za-z0-9\(\)\.\:\-\s]+", "", clean_opt).strip()
                if len(unlabeled) >= 3:
                    pos = prompt_bytes.find(unlabeled.encode("utf-8"), char_cursor)
            if pos >= 0 and (pos + len(opt_bytes)) <= len(byte_to_tok):
                s_tok = byte_to_tok[pos]
                e_tok = byte_to_tok[pos + len(opt_bytes) - 1]
                spans.append((s_tok, e_tok))
                char_cursor = pos + len(opt_bytes)
            else:
                break
        if len(spans) == len(options):
            return spans
    except Exception:
        pass

    last = max(0, len(token_ids) - 1)
    return [(max(0, last - (len(options) - 1 - i)), max(0, last - (len(options) - 1 - i))) for i in range(len(options))]


def load_cortex_model(
    model_name_or_path: Optional[str] = None,
    checkpoint_path: Optional[str] = None,
    calibration_path: Optional[str] = "cortex_system_one_calibration.json",
    device: Optional[torch.device] = None,
    dtype: torch.dtype = torch.float16,
):
    """Loads Cortex-System-one (0.574B) into memory with calibration parameters."""
    if device is None:
        device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    target = checkpoint_path or model_name_or_path or "ckpt_cortex_system_one_champion.pth"
    path_obj = Path(target)
    if path_obj.is_dir():
        ckpt_file = path_obj / "ckpt_cortex_system_one_champion.pth"
        if calibration_path:
            calib_candidate = path_obj / "cortex_system_one_calibration.json"
            if calib_candidate.is_file():
                calibration_path = str(calib_candidate)
    elif "/" in target and not path_obj.exists():
        # Direct Hugging Face Repo ID passed (e.g. 'siddiVinayaka/Cortex-System-One')
        from huggingface_hub import hf_hub_download
        print(f"[*] Downloading Cortex-System-One directly from Hugging Face repo '{target}'...")
        ckpt_file = Path(hf_hub_download(repo_id=target, filename="ckpt_cortex_system_one_champion.pth"))
        if calibration_path:
            calibration_path = hf_hub_download(repo_id=target, filename="cortex_system_one_calibration.json")
    else:
        ckpt_file = path_obj

    if not ckpt_file.is_file():
        try:
            from huggingface_hub import hf_hub_download
            print(f"[*] Checkpoint not found locally. Downloading from Hugging Face...")
            ckpt_file = Path(hf_hub_download(repo_id="siddiVinayaka/Cortex-System-One", filename="ckpt_cortex_system_one_champion.pth"))
        except Exception:
            raise FileNotFoundError(f"Checkpoint not found at: {ckpt_file.resolve()}")

    # Check if the file is just a Git LFS text pointer
    if ckpt_file.stat().st_size < 2048:
        try:
            with open(ckpt_file, "r", encoding="utf-8", errors="ignore") as f:
                header = f.read(100)
            if "version https://git-lfs" in header:
                print(f"[!] Detected Git LFS pointer ({ckpt_file.stat().st_size} bytes) instead of binary weights.")
                try:
                    from huggingface_hub import hf_hub_download
                    print("[*] Automatically resolving and downloading full 2.21 GB weights via huggingface_hub...")
                    downloaded = hf_hub_download(repo_id="siddiVinayaka/Cortex-System-One", filename=ckpt_file.name)
                    ckpt_file = Path(downloaded)
                except Exception as lfs_err:
                    raise RuntimeError(
                        f"The file '{ckpt_file.name}' is only a Git LFS pointer text file.\n"
                        "To pull the actual 2.21 GB weights in Google Colab / Linux, run:\n"
                        "    !cd /content/Cortex-System-One && git lfs pull\n"
                        "Or install huggingface_hub: 'pip install huggingface_hub'"
                    ) from lfs_err
        except Exception as e:
            if "Git LFS pointer" in str(e):
                raise e

    print(f"[*] Loading weights from {ckpt_file.name} ({ckpt_file.stat().st_size / (1024**2):.1f} MB)...")
    ckpt = torch.load(ckpt_file, map_location="cpu", weights_only=False)
    cfg = ckpt.get("base_cfg", ckpt.get("cfg", {}))

    model = Cortex(
        vocab_size=int(cfg.get("vocab_size", 100277)),
        dim=int(cfg.get("dim", 1280)),
        heads=int(cfg.get("heads", 16)),
        kv_heads=int(cfg.get("kv_heads", 4)),
        num_layers=int(cfg.get("num_layers", 20)),
        memory_slots=int(cfg.get("memory_slots", 128)),
        mtp_depths=int(cfg.get("mtp_depths", 1)),
        decision_layers=2,
        use_flash=False,
    )

    raw_sd = ckpt.get("model", ckpt.get("model_state_dict", ckpt))
    clean_sd = {k.replace("_orig_mod.", "").replace("module.", "").replace("backbone.", ""): v for k, v in raw_sd.items()}
    model.load_state_dict(clean_sd, strict=False)
    model.use_system1_head = True
    model = model.to(device=device, dtype=dtype).eval()

    calib = {}
    if calibration_path and Path(calibration_path).is_file():
        with open(calibration_path, "r", encoding="utf-8") as f:
            calib = json.load(f)
        print(f"[OK] Loaded calibration settings from {Path(calibration_path).name}")

    total_params = sum(p.numel() for p in model.parameters())
    print(f"[OK] Cortex-System-one successfully ready ({total_params:,} parameters)")
    return model, calib


def predict_decision(
    model: Cortex,
    prompt: str,
    options: List[str],
    calibration: Optional[Dict[str, Any]] = None,
    device: Optional[torch.device] = None,
) -> Dict[str, Any]:
    """Performs calibrated typed decision inference."""
    if device is None:
        device = next(model.parameters()).device

    enc = tiktoken.get_encoding("cl100k_base")
    tokens = enc.encode(prompt, allowed_special={"<|endoftext|>"})
    spans = find_option_spans(tokens, enc, options)

    inp_tensor = torch.tensor([tokens], device=device, dtype=torch.long)
    pos_tensor = torch.tensor([spans], device=device, dtype=torch.long)

    t0 = time.perf_counter()
    with torch.no_grad():
        logits, _, _, _ = model(inp_tensor, candidate_positions=pos_tensor, last_token_only=True)
        raw_logits = logits[0, 0].clone()

    if device.type == "cuda":
        torch.cuda.synchronize()
    latency_ms = (time.perf_counter() - t0) * 1000.0

    temp = 1.1
    if calibration and "temperatures" in calibration:
        temp = calibration["temperatures"].get(f"choice|{len(options)}", 1.1)

    scaled_logits = raw_logits / temp
    probs = F.softmax(scaled_logits, dim=-1).cpu().tolist()
    pred_idx = int(torch.tensor(probs).argmax().item())

    return {
        "predicted_index": pred_idx,
        "predicted_option": options[pred_idx],
        "confidence": round(probs[pred_idx], 4),
        "latency_ms": round(latency_ms, 2),
        "probabilities": {opt: round(p, 4) for opt, p in zip(options, probs)},
    }


# Backwards-compatible alias for README example
predict_choice = predict_decision



if __name__ == "__main__":
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    print(f"[*] Testing Cortex-System-one inference on {device}...")

    ckpt_file = "ckpt_cortex_system_one_champion.pth" if Path("ckpt_cortex_system_one_champion.pth").is_file() else "../ckpt_cortex_system_one_champion.pth"
    model, calib = load_cortex_model(
        checkpoint_path=ckpt_file,
        calibration_path="cortex_system_one_calibration.json",
        device=device,
    )

    prompt = (
        "Workflow: Security Incidents\n"
        "Task State: {\"alert_type\":\"brute_force\",\"failed_logins\":42,\"source_ip\":\"198.51.100.2\"}\n\n"
        "Task: Determine incident response containment action.\n"
        "Options:\n"
        "(A) Ignore alert as false positive\n"
        "(B) Isolate host and revoke active credentials\n"
        "(C) Send non-urgent notification\n\n"
        "Analyze the state and select the correct option.\nAnswer:"
    )
    options = [
        "Ignore alert as false positive",
        "Isolate host and revoke active credentials",
        "Send non-urgent notification"
    ]

    res = predict_decision(model, prompt, options, calibration=calib, device=device)
    print("\n--- INFERENCE RESULT ---")
    print(f"Predicted Choice : {res['predicted_option']} (Index: {res['predicted_index']})")
    print("Probabilities    :")
    for opt, prob in res['probabilities'].items():
        print(f"  - {opt}: {prob * 100:.2f}%")
    print("------------------------")