File size: 6,832 Bytes
7ba7d54
60b9ffe
fd5bcd3
df23f1a
fd5bcd3
4f990cf
 
 
fd5bcd3
 
 
 
4f990cf
7ba7d54
4f990cf
60b9ffe
 
 
7ba7d54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60b9ffe
4f990cf
7ba7d54
4f990cf
fd5bcd3
7ba7d54
 
 
fd5bcd3
7ba7d54
 
 
 
 
 
 
fd5bcd3
7ba7d54
 
 
fd5bcd3
7ba7d54
60b9ffe
4f990cf
7ba7d54
4f990cf
fd5bcd3
 
7ba7d54
 
 
 
 
fd5bcd3
 
7ba7d54
 
 
60b9ffe
7ba7d54
 
60b9ffe
7ba7d54
 
fd5bcd3
4b2d865
 
fd5bcd3
7ba7d54
fd5bcd3
7ba7d54
 
fd5bcd3
7ba7d54
 
 
 
 
 
 
 
fd5bcd3
60b9ffe
4f990cf
7ba7d54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f990cf
7ba7d54
4f990cf
 
7ba7d54
4f990cf
 
7ba7d54
 
 
 
 
4f990cf
 
7ba7d54
ffe689a
 
 
 
 
4f990cf
ffe689a
 
7ba7d54
ffe689a
 
7ba7d54
60b9ffe
 
ffe689a
7ba7d54
 
 
ffe689a
4f990cf
7ba7d54
 
 
ffe689a
 
4f990cf
ffe689a
 
7ba7d54
4f990cf
 
7ba7d54
4f990cf
4b2d865
 
 
 
 
 
 
 
 
4f990cf
7ba7d54
 
 
 
 
 
 
f3d5724
7ba7d54
ffe689a
7ba7d54
 
 
ffe689a
4f990cf
7ba7d54
4f990cf
ffe689a
7ba7d54
 
 
 
4f990cf
7ba7d54
 
 
4f990cf
7ba7d54
 
 
 
 
4f990cf
7ba7d54
 
 
 
 
ffe689a
4f990cf
 
7ba7d54
 
 
 
4f990cf
7ba7d54
4f990cf
 
7ba7d54
 
 
 
ffe689a
7ba7d54
 
 
 
ffe689a
7ba7d54
 
 
 
 
4f990cf
7ba7d54
 
4f990cf
7ba7d54
 
ffe689a
7ba7d54
 
 
 
 
ffe689a
7ba7d54
 
60b9ffe
 
 
 
 
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
import os, sys, math
from typing import Optional, Dict, Any, List

import numpy as np
from numpy.linalg import norm
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field

from sentence_transformers import SentenceTransformer
from huggingface_hub import hf_hub_download
import joblib

# ============================
# CONFIG
# ============================

HF_TOKEN = os.environ.get("HF_TOKEN", "")

ENCODER_MODEL_ID    = "antonypamo/RRFSAVANTMADE"
META_LOGIT_REPO     = "antonypamo/RRFSavantMetaLogicV2"
META_LOGIT_FILENAME = "logreg_rrf_savant.joblib"

MAX_PROMPT_CHARS = 8000
MAX_ANSWER_CHARS = 12000
MAX_DOCS = 50
MAX_DOC_CHARS = 6000

PHI_NODES = [
    "Φ0_seed",
    "Φ1_geometric",
    "Φ2_gauge_dirac",
    "Φ3_log_gravity",
    "Φ4_resonance",
    "Φ5_memory_symbiosis",
    "Φ6_alignment",
    "Φ7_meta_agi",
]

# ============================
# STARTUP: MODELS
# ============================

print("🔄 Loading encoder...", flush=True)
encoder = SentenceTransformer(ENCODER_MODEL_ID)
print("✅ Encoder loaded", flush=True)

print("🔄 Loading meta-logit V2...", flush=True)
meta_logit_path = hf_hub_download(
    repo_id=META_LOGIT_REPO,
    filename=META_LOGIT_FILENAME,
    token=HF_TOKEN or None,
)
meta_logit = joblib.load(meta_logit_path)

EXPECTED_FEATURES = getattr(meta_logit, "n_features_in_", 15)
if EXPECTED_FEATURES != 15:
    raise RuntimeError(f"Meta-logit expects {EXPECTED_FEATURES} features, expected 15.")

print("✅ Meta-logit loaded (15D)", flush=True)

# ============================
# META-STATE FEATURE EXTRACTION
# ============================

def get_embedding(text: str) -> np.ndarray:
    return encoder.encode(
        [text],
        convert_to_numpy=True,
        normalize_embeddings=True,
    )[0]


def spectral_features(emb: np.ndarray) -> Dict[str, float]:
    fft = np.fft.rfft(emb)
    power = np.abs(fft) ** 2

    total = power.sum() + 1e-12
    dominant_idx = int(np.argmax(power))

    phi = float(np.clip(total / (total + 1.0), 0.0, 1.0))
    omega = float(np.clip(dominant_idx / len(power), 0.0, 1.0))

    S_RRF = float(1.0 - np.std(power) / (np.mean(power) + 1e-12))
    S_RRF = float(np.clip(S_RRF, 0.0, 1.0))

    coherence = float(0.5 * (1.0 - np.std(power) / (np.mean(power) + 1e-12)) + 0.5 * C_RRF)

    hamiltonian_energy = float(np.dot(emb, emb))
    dominant_frequency = float(dominant_idx)

    return {
        "phi": phi,
        "omega": omega,
        "coherence": coherence,
        "S_RRF": S_RRF,
        "C_RRF": C_RRF,
        "hamiltonian_energy": hamiltonian_energy,
        "dominant_frequency": dominant_frequency,
    }


def closest_phi_node(feats: Dict[str, float]) -> int:
    # Deterministic ontology mapping
    if feats["coherence"] > 0.85 and feats["phi"] > 0.6:
        return 4  # Φ4_resonance
    if feats["hamiltonian_energy"] > 50:
        return 2  # Φ2_gauge_dirac
    if feats["omega"] < 0.2:
        return 0  # Φ0_seed
    if feats["coherence"] < 0.4:
        return 5  # Φ5_memory_symbiosis
    if feats["phi"] < 0.3:
        return 6  # Φ6_alignment
    return 7  # Φ7_meta_agi


def rrf_state_to_vector(prompt: str, answer: str) -> np.ndarray:
    emb = get_embedding(prompt + "\n" + answer)
    feats = spectral_features(emb)

    phi_idx = closest_phi_node(feats)
    phi_one_hot = [1.0 if i == phi_idx else 0.0 for i in range(8)]

    vector = [
        feats["phi"],
        feats["omega"],
        feats["coherence"],
        feats["S_RRF"],
        feats["C_RRF"],
        feats["hamiltonian_energy"],
        feats["dominant_frequency"],
        *phi_one_hot,
    ]

    return np.array(vector, dtype=float), feats, PHI_NODES[phi_idx]

# ============================
# FASTAPI
# ============================

app = FastAPI(
    title="Savant RRF Φ12.0 API",
    version="2.0.0",
    description="Meta-state RRF quality evaluation + rerank",
)

# ============================
# SCHEMAS
# ============================

class EvaluateRequest(BaseModel):
    prompt: str
    answer: str


class EvaluateResponse(BaseModel):
    p_good: float
    scores: Dict[str, float]
    features: Dict[str, float]
    phi_node: str


class RerankRequest(BaseModel):
    query: str
    documents: List[str]
    alpha: float = 0.2


class RerankDocument(BaseModel):
    id: int
    score: float
    rank: int


class RerankResponse(BaseModel):
    model_id: str
    results: List[RerankDocument]

# ============================
# MANIFEST / HEALTH
# ============================
@app.get("/")
def root():
    return {
        "status": "ok",
        "model": "RRFSavantMetaLogicV2",
        "version": "Φ12.0",
        "docs": "/docs",
        "endpoints": ["/manifest", "/health", "/evaluate", "/quality", "/v1/rerank"],
    }

@app.get("/manifest")
def manifest():
    return {
        "model": "RRFSavantMetaLogicV2",
        "version": "Φ12.0",
        "encoder": ENCODER_MODEL_ID,
        "features": 15,
        "phi_nodes": PHI_NODES,
    }

@app.get("/health")
def health():
    return {"status": "ok"}

# ============================
# /EVALUATE
# ============================

@app.post("/evaluate", response_model=EvaluateResponse)
def evaluate(req: EvaluateRequest):
    if len(req.prompt) > MAX_PROMPT_CHARS or len(req.answer) > MAX_ANSWER_CHARS:
        raise HTTPException(413, "Payload too large")

    x, feats, phi_node = rrf_state_to_vector(req.prompt, req.answer)
    proba = meta_logit.predict_proba(x.reshape(1, -1))[0]
    p_good = float(proba[1])

    scores = {
        "SRRF": p_good,
        "CRRF": p_good * feats["coherence"],
        "E_phi": 0.5 * (p_good + feats["phi"]),
    }

    return EvaluateResponse(
        p_good=p_good,
        scores=scores,
        features=feats,
        phi_node=phi_node,
    )


@app.post("/quality", response_model=EvaluateResponse)
def quality_alias(req: EvaluateRequest):
    return evaluate(req)

# ============================
# /v1/rerank (BATCHED)
# ============================

@app.post("/v1/rerank", response_model=RerankResponse)
def rerank(req: RerankRequest):
    if len(req.documents) > MAX_DOCS:
        raise HTTPException(413, "Too many documents")

    texts = [req.query] + req.documents
    for d in req.documents:
        if len(d) > MAX_DOC_CHARS:
            raise HTTPException(413, "Document too large")

    embs = encoder.encode(
        texts,
        convert_to_numpy=True,
        normalize_embeddings=True,
    )

    q_emb = embs[0]
    d_embs = embs[1:]

    scores = d_embs @ q_emb
    ranked_idx = np.argsort(-scores)

    results = [
        RerankDocument(
            id=int(i),
            score=float(scores[i]),
            rank=r + 1,
        )
        for r, i in enumerate(ranked_idx)
    ]

    return RerankResponse(
        model_id=ENCODER_MODEL_ID,
        results=results,
    )