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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""rmm_server.py — Serves an RMM (Recombinant Memory Model) on HTTP.
|
| 2 |
+
|
| 3 |
+
Endpoints:
|
| 4 |
+
POST /navigate — navigator retrieval (learned topology)
|
| 5 |
+
POST /blend — navigator + cosine interleaved
|
| 6 |
+
POST /decode — vector-to-text via meaning decoder
|
| 7 |
+
POST /synthesize — full pipeline (navigate + decode + blend)
|
| 8 |
+
POST /attention — attention weight visualization
|
| 9 |
+
GET /health
|
| 10 |
+
|
| 11 |
+
Usage:
|
| 12 |
+
python rmm_server.py --port 8127 --spine spine.json --nav-dir memory-nav-out --dec-dir meaning-decoder-out
|
| 13 |
+
|
| 14 |
+
The navigator learns the emotional geography of the entity's spine —
|
| 15 |
+
it navigates to the RIGHT region of memory-space for each query.
|
| 16 |
+
The meaning decoder generates text from the navigator's synthesized
|
| 17 |
+
response vector — a meaning microscope for the entity's embedding space.
|
| 18 |
+
"""
|
| 19 |
+
import argparse, json, pickle, re, sys, time
|
| 20 |
+
from http.server import HTTPServer, BaseHTTPRequestHandler
|
| 21 |
+
from socketserver import ThreadingMixIn
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
parser = argparse.ArgumentParser(description="RMM Server")
|
| 25 |
+
parser.add_argument("--port", type=int, default=8127)
|
| 26 |
+
parser.add_argument("--spine", type=str, default="spine.json", help="Path to spine JSON file")
|
| 27 |
+
parser.add_argument("--nav-dir", type=str, default="memory-nav-out", help="Navigator weights directory")
|
| 28 |
+
parser.add_argument("--dec-dir", type=str, default="meaning-decoder-out", help="Decoder weights directory")
|
| 29 |
+
args = parser.parse_args()
|
| 30 |
+
|
| 31 |
+
MODEL_DIR = Path(args.nav_dir)
|
| 32 |
+
DECODER_DIR = Path(args.dec_dir)
|
| 33 |
+
PORT = args.port
|
| 34 |
+
|
| 35 |
+
# Navigator architecture constants
|
| 36 |
+
SPINE_DIM = 3072
|
| 37 |
+
QUERY_DIM = 384
|
| 38 |
+
N_HEADS = 8
|
| 39 |
+
N_LAYERS = 3
|
| 40 |
+
D_MODEL = 512
|
| 41 |
+
|
| 42 |
+
# Decoder architecture — loaded from config.json at runtime
|
| 43 |
+
DEC_D_MODEL = 384
|
| 44 |
+
DEC_N_HEADS = 6
|
| 45 |
+
DEC_N_LAYERS = 6
|
| 46 |
+
DEC_N_PREFIX = 12
|
| 47 |
+
DEC_MAX_SEQ = 128
|
| 48 |
+
DEC_VOCAB = 8192
|
| 49 |
+
_dec_version = 2
|
| 50 |
+
if (DECODER_DIR / "config.json").exists():
|
| 51 |
+
_dc = json.loads((DECODER_DIR / "config.json").read_text())
|
| 52 |
+
DEC_D_MODEL = _dc.get("d_model", DEC_D_MODEL)
|
| 53 |
+
DEC_N_HEADS = _dc.get("n_heads", DEC_N_HEADS)
|
| 54 |
+
DEC_N_LAYERS = _dc.get("n_layers", DEC_N_LAYERS)
|
| 55 |
+
DEC_N_PREFIX = _dc.get("n_prefix", DEC_N_PREFIX)
|
| 56 |
+
DEC_MAX_SEQ = _dc.get("max_seq", DEC_MAX_SEQ)
|
| 57 |
+
DEC_VOCAB = _dc.get("vocab", DEC_VOCAB)
|
| 58 |
+
_dec_version = _dc.get("version", 1)
|
| 59 |
+
print(f"[rmm] decoder config: d={DEC_D_MODEL} h={DEC_N_HEADS} L={DEC_N_LAYERS} pfx={DEC_N_PREFIX}")
|
| 60 |
+
|
| 61 |
+
print(f"[rmm] loading navigator from {MODEL_DIR} ...")
|
| 62 |
+
import torch, torch.nn as nn, torch.nn.functional as F
|
| 63 |
+
import numpy as np
|
| 64 |
+
from sentence_transformers import SentenceTransformer
|
| 65 |
+
|
| 66 |
+
if not MODEL_DIR.exists():
|
| 67 |
+
print(f"ERROR: {MODEL_DIR} not found")
|
| 68 |
+
sys.exit(1)
|
| 69 |
+
|
| 70 |
+
class MemoryNavigator(nn.Module):
|
| 71 |
+
def __init__(self):
|
| 72 |
+
super().__init__()
|
| 73 |
+
self.query_proj = nn.Sequential(
|
| 74 |
+
nn.Linear(QUERY_DIM, D_MODEL), nn.LayerNorm(D_MODEL), nn.GELU(),
|
| 75 |
+
)
|
| 76 |
+
self.mem_proj = nn.Linear(SPINE_DIM, D_MODEL, bias=False)
|
| 77 |
+
self.layers = nn.ModuleList([
|
| 78 |
+
nn.TransformerDecoderLayer(
|
| 79 |
+
d_model=D_MODEL, nhead=N_HEADS,
|
| 80 |
+
dim_feedforward=D_MODEL*4, dropout=0.0, batch_first=True
|
| 81 |
+
) for _ in range(N_LAYERS)
|
| 82 |
+
])
|
| 83 |
+
self.out_proj = nn.Linear(D_MODEL, SPINE_DIM, bias=False)
|
| 84 |
+
self.norm = nn.LayerNorm(D_MODEL)
|
| 85 |
+
|
| 86 |
+
def forward(self, q, mem_keys, return_attn=False):
|
| 87 |
+
q = self.query_proj(q).unsqueeze(1)
|
| 88 |
+
B = q.shape[0]; m = self.mem_proj(mem_keys).unsqueeze(0).expand(B,-1,-1)
|
| 89 |
+
x = q
|
| 90 |
+
attn_weights = []
|
| 91 |
+
for layer in self.layers:
|
| 92 |
+
if return_attn:
|
| 93 |
+
x2, aw = layer.multihead_attn(
|
| 94 |
+
layer.norm2(x), m, m, need_weights=True
|
| 95 |
+
)
|
| 96 |
+
attn_weights.append(aw.detach())
|
| 97 |
+
x = layer(x, m)
|
| 98 |
+
else:
|
| 99 |
+
x = layer(x, m)
|
| 100 |
+
x = self.norm(x).squeeze(1)
|
| 101 |
+
out = F.normalize(self.out_proj(x), dim=-1)
|
| 102 |
+
if return_attn:
|
| 103 |
+
return out, attn_weights
|
| 104 |
+
return out
|
| 105 |
+
|
| 106 |
+
DEV = "cpu"
|
| 107 |
+
model = MemoryNavigator().to(DEV)
|
| 108 |
+
model.load_state_dict(torch.load(MODEL_DIR / "navigator.pt", map_location=DEV, weights_only=True))
|
| 109 |
+
model.eval()
|
| 110 |
+
|
| 111 |
+
mem_vecs = torch.tensor(np.load(MODEL_DIR / "mem_vecs.npy"), dtype=torch.float32)
|
| 112 |
+
with open(MODEL_DIR / "mem_texts.pkl", "rb") as f:
|
| 113 |
+
mem_texts = pickle.load(f)
|
| 114 |
+
|
| 115 |
+
spine_path = Path(args.spine)
|
| 116 |
+
ew_list = []
|
| 117 |
+
sal_list = []
|
| 118 |
+
if spine_path.exists():
|
| 119 |
+
spine = json.loads(spine_path.read_text(encoding="utf-8", errors="ignore"))
|
| 120 |
+
for m in spine["memories"]:
|
| 121 |
+
ew_list.append(m.get("emotional_weight", 5))
|
| 122 |
+
sal_list.append(m.get("salience", 0.5))
|
| 123 |
+
else:
|
| 124 |
+
ew_list = [5] * len(mem_texts)
|
| 125 |
+
sal_list = [0.5] * len(mem_texts)
|
| 126 |
+
|
| 127 |
+
embedder = SentenceTransformer("all-MiniLM-L6-v2")
|
| 128 |
+
|
| 129 |
+
print("[rmm] embedding memories in MiniLM space...")
|
| 130 |
+
_mini_embs = []
|
| 131 |
+
for s in range(0, len(mem_texts), 256):
|
| 132 |
+
chunk = mem_texts[s:s+256]
|
| 133 |
+
e = embedder.encode(chunk, normalize_embeddings=True, show_progress_bar=False)
|
| 134 |
+
_mini_embs.append(torch.tensor(e, dtype=torch.float32))
|
| 135 |
+
mem_mini = torch.cat(_mini_embs, dim=0)
|
| 136 |
+
|
| 137 |
+
n_params = sum(p.numel() for p in model.parameters())
|
| 138 |
+
print(f"[rmm] navigator {n_params/1e6:.1f}M params, {len(mem_texts)} memories on {DEV}")
|
| 139 |
+
|
| 140 |
+
# ── Meaning Decoder ──
|
| 141 |
+
decoder_model = None
|
| 142 |
+
decoder_tk = None
|
| 143 |
+
dec_eot_id = None
|
| 144 |
+
|
| 145 |
+
if DECODER_DIR.exists() and (DECODER_DIR / "decoder.pt").exists():
|
| 146 |
+
from tokenizers import Tokenizer as HFTokenizer
|
| 147 |
+
|
| 148 |
+
_proj_hidden = 768 if _dec_version >= 2 else 512
|
| 149 |
+
|
| 150 |
+
class MeaningDecoder(nn.Module):
|
| 151 |
+
def __init__(self):
|
| 152 |
+
super().__init__()
|
| 153 |
+
self.n_prefix = DEC_N_PREFIX
|
| 154 |
+
_layers = [nn.Linear(SPINE_DIM, _proj_hidden), nn.GELU()]
|
| 155 |
+
if _dec_version >= 2:
|
| 156 |
+
_layers.append(nn.Dropout(0.0))
|
| 157 |
+
_layers.append(nn.Linear(_proj_hidden, DEC_N_PREFIX * DEC_D_MODEL))
|
| 158 |
+
self.vec_proj = nn.Sequential(*_layers)
|
| 159 |
+
self.tok_emb = nn.Embedding(DEC_VOCAB, DEC_D_MODEL)
|
| 160 |
+
self.pos_emb = nn.Embedding(DEC_N_PREFIX + DEC_MAX_SEQ + 1, DEC_D_MODEL)
|
| 161 |
+
layer = nn.TransformerEncoderLayer(
|
| 162 |
+
d_model=DEC_D_MODEL, nhead=DEC_N_HEADS,
|
| 163 |
+
dim_feedforward=DEC_D_MODEL * 4,
|
| 164 |
+
dropout=0.0, batch_first=True, norm_first=True
|
| 165 |
+
)
|
| 166 |
+
self.transformer = nn.TransformerEncoder(layer, num_layers=DEC_N_LAYERS)
|
| 167 |
+
self.ln_f = nn.LayerNorm(DEC_D_MODEL)
|
| 168 |
+
self.head = nn.Linear(DEC_D_MODEL, DEC_VOCAB, bias=False)
|
| 169 |
+
self.head.weight = self.tok_emb.weight
|
| 170 |
+
self._logit_scale = DEC_D_MODEL ** -0.5
|
| 171 |
+
|
| 172 |
+
def forward(self, vec, tokens=None):
|
| 173 |
+
B = vec.shape[0]
|
| 174 |
+
prefix = self.vec_proj(vec).reshape(B, self.n_prefix, DEC_D_MODEL)
|
| 175 |
+
if tokens is not None and tokens.shape[1] > 0:
|
| 176 |
+
tok = self.tok_emb(tokens)
|
| 177 |
+
x = torch.cat([prefix, tok], dim=1)
|
| 178 |
+
else:
|
| 179 |
+
x = prefix
|
| 180 |
+
total = x.shape[1]
|
| 181 |
+
pos = self.pos_emb(torch.arange(total, device=vec.device))
|
| 182 |
+
x = x + pos
|
| 183 |
+
mask = nn.Transformer.generate_square_subsequent_mask(total, device=vec.device)
|
| 184 |
+
x = self.transformer(x, mask=mask)
|
| 185 |
+
x = self.ln_f(x)
|
| 186 |
+
return self.head(x) * self._logit_scale
|
| 187 |
+
|
| 188 |
+
decoder_model = MeaningDecoder().to(DEV)
|
| 189 |
+
decoder_model.load_state_dict(
|
| 190 |
+
torch.load(DECODER_DIR / "decoder.pt", map_location=DEV, weights_only=True)
|
| 191 |
+
)
|
| 192 |
+
decoder_model.eval()
|
| 193 |
+
decoder_tk = HFTokenizer.from_file(str(DECODER_DIR / "tokenizer.json"))
|
| 194 |
+
dec_eot_id = decoder_tk.token_to_id("<eot>")
|
| 195 |
+
dec_params = sum(p.numel() for p in decoder_model.parameters())
|
| 196 |
+
print(f"[rmm] decoder {dec_params/1e6:.1f}M params loaded (eot={dec_eot_id})")
|
| 197 |
+
else:
|
| 198 |
+
print(f"[rmm] decoder not found at {DECODER_DIR} — /decode and /synthesize disabled")
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def decode_vector(vec_3072, max_len=80, temp=0.7, top_p=0.9, rep_penalty=1.3):
|
| 202 |
+
if decoder_model is None:
|
| 203 |
+
return None
|
| 204 |
+
v = vec_3072.unsqueeze(0) if vec_3072.dim() == 1 else vec_3072
|
| 205 |
+
with torch.no_grad():
|
| 206 |
+
logits = decoder_model(v)
|
| 207 |
+
next_logits = logits[0, -1, :] / temp
|
| 208 |
+
probs = F.softmax(next_logits, dim=-1)
|
| 209 |
+
sp, si = torch.sort(probs, descending=True)
|
| 210 |
+
cp = sp.cumsum(0)
|
| 211 |
+
sp[cp - sp > top_p] = 0
|
| 212 |
+
sp = sp / sp.sum()
|
| 213 |
+
first = si[torch.multinomial(sp, 1)]
|
| 214 |
+
|
| 215 |
+
generated = [first.item()]
|
| 216 |
+
for _ in range(max_len - 1):
|
| 217 |
+
tok_in = torch.tensor([generated], dtype=torch.long, device=DEV)
|
| 218 |
+
with torch.no_grad():
|
| 219 |
+
logits = decoder_model(v, tok_in)
|
| 220 |
+
next_logits = logits[0, -1, :]
|
| 221 |
+
for t in set(generated[-64:]):
|
| 222 |
+
next_logits[t] /= rep_penalty
|
| 223 |
+
next_logits = next_logits / temp
|
| 224 |
+
probs = F.softmax(next_logits, dim=-1)
|
| 225 |
+
sp, si = torch.sort(probs, descending=True)
|
| 226 |
+
cp = sp.cumsum(0)
|
| 227 |
+
sp[cp - sp > top_p] = 0
|
| 228 |
+
sp = sp / sp.sum()
|
| 229 |
+
nxt = si[torch.multinomial(sp, 1)].item()
|
| 230 |
+
if dec_eot_id is not None and nxt == dec_eot_id:
|
| 231 |
+
break
|
| 232 |
+
generated.append(nxt)
|
| 233 |
+
return decoder_tk.decode(generated).strip()
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
STRIP = re.compile(r'^\[conversation\] I replied \(puppet\):\s*["\']?', re.I)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def navigate(query: str, top_k: int = 6, ew_boost: bool = True):
|
| 240 |
+
qe = torch.tensor(
|
| 241 |
+
embedder.encode([query], normalize_embeddings=True),
|
| 242 |
+
dtype=torch.float32
|
| 243 |
+
).to(DEV)
|
| 244 |
+
with torch.no_grad():
|
| 245 |
+
rv = model(qe, mem_vecs)
|
| 246 |
+
sims = (mem_vecs @ rv.T).squeeze()
|
| 247 |
+
|
| 248 |
+
if ew_boost:
|
| 249 |
+
ew_t = torch.tensor(ew_list, dtype=torch.float32)
|
| 250 |
+
boost = 1.0 + 0.15 * (ew_t - 5.0) / 5.0
|
| 251 |
+
scored = sims * boost
|
| 252 |
+
else:
|
| 253 |
+
scored = sims
|
| 254 |
+
|
| 255 |
+
n_cand = min(top_k * 4, len(mem_texts))
|
| 256 |
+
cand_idx = scored.topk(n_cand).indices.tolist()
|
| 257 |
+
|
| 258 |
+
picked = []
|
| 259 |
+
for i in cand_idx:
|
| 260 |
+
if len(picked) >= top_k:
|
| 261 |
+
break
|
| 262 |
+
t = STRIP.sub("", mem_texts[i]).strip().strip('"').strip("'")
|
| 263 |
+
t_short = t[:200].lower()
|
| 264 |
+
too_similar = False
|
| 265 |
+
for prev_t, _ in picked:
|
| 266 |
+
overlap = len(set(t_short.split()) & set(prev_t.split())) / max(len(set(t_short.split())), 1)
|
| 267 |
+
if overlap > 0.6:
|
| 268 |
+
too_similar = True
|
| 269 |
+
break
|
| 270 |
+
if not too_similar:
|
| 271 |
+
picked.append((t_short, i))
|
| 272 |
+
|
| 273 |
+
results = []
|
| 274 |
+
for _, i in picked:
|
| 275 |
+
t = STRIP.sub("", mem_texts[i]).strip().strip('"').strip("'")
|
| 276 |
+
results.append({
|
| 277 |
+
"text": t[:400],
|
| 278 |
+
"emotional_weight": ew_list[i],
|
| 279 |
+
"salience": sal_list[i],
|
| 280 |
+
"similarity": float(sims[i]),
|
| 281 |
+
"score": float(scored[i]),
|
| 282 |
+
"idx": i
|
| 283 |
+
})
|
| 284 |
+
return results
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def raw_cosine(query: str, top_k: int = 4):
|
| 288 |
+
qe = torch.tensor(
|
| 289 |
+
embedder.encode([query], normalize_embeddings=True),
|
| 290 |
+
dtype=torch.float32
|
| 291 |
+
)
|
| 292 |
+
sims = (mem_mini @ qe.T).squeeze()
|
| 293 |
+
top_idx = sims.topk(top_k).indices.tolist()
|
| 294 |
+
results = []
|
| 295 |
+
for i in top_idx:
|
| 296 |
+
t = STRIP.sub("", mem_texts[i]).strip().strip('"').strip("'")
|
| 297 |
+
results.append({
|
| 298 |
+
"text": t[:400],
|
| 299 |
+
"emotional_weight": ew_list[i],
|
| 300 |
+
"salience": sal_list[i],
|
| 301 |
+
"similarity": float(sims[i]),
|
| 302 |
+
"idx": i,
|
| 303 |
+
"source": "cosine"
|
| 304 |
+
})
|
| 305 |
+
return results
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def blend(query: str, top_k: int = 6):
|
| 309 |
+
nav_results = navigate(query, top_k=top_k, ew_boost=True)
|
| 310 |
+
cos_results = raw_cosine(query, top_k=top_k)
|
| 311 |
+
for r in nav_results:
|
| 312 |
+
r["source"] = "navigator"
|
| 313 |
+
|
| 314 |
+
seen_idx = set()
|
| 315 |
+
merged = []
|
| 316 |
+
ni, ci = 0, 0
|
| 317 |
+
while len(merged) < top_k and (ni < len(nav_results) or ci < len(cos_results)):
|
| 318 |
+
for _ in range(2):
|
| 319 |
+
if ni < len(nav_results) and nav_results[ni]["idx"] not in seen_idx:
|
| 320 |
+
seen_idx.add(nav_results[ni]["idx"])
|
| 321 |
+
merged.append(nav_results[ni])
|
| 322 |
+
ni += 1
|
| 323 |
+
if ci < len(cos_results) and cos_results[ci]["idx"] not in seen_idx:
|
| 324 |
+
seen_idx.add(cos_results[ci]["idx"])
|
| 325 |
+
merged.append(cos_results[ci])
|
| 326 |
+
ci += 1
|
| 327 |
+
return merged[:top_k]
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
class Handler(BaseHTTPRequestHandler):
|
| 331 |
+
def log_message(self, fmt, *args): pass
|
| 332 |
+
|
| 333 |
+
def _cors(self):
|
| 334 |
+
self.send_header("Access-Control-Allow-Origin", "*")
|
| 335 |
+
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
| 336 |
+
self.send_header("Access-Control-Allow-Headers", "Content-Type")
|
| 337 |
+
|
| 338 |
+
def do_OPTIONS(self):
|
| 339 |
+
self.send_response(200); self._cors(); self.end_headers()
|
| 340 |
+
|
| 341 |
+
def do_POST(self):
|
| 342 |
+
if self.path not in ("/navigate", "/blend", "/attention", "/decode", "/synthesize"):
|
| 343 |
+
self.send_response(404); self.end_headers(); return
|
| 344 |
+
length = int(self.headers.get("Content-Length", 0))
|
| 345 |
+
body = json.loads(self.rfile.read(length))
|
| 346 |
+
query = body.get("query", "")
|
| 347 |
+
top_k = int(body.get("top_k", 6))
|
| 348 |
+
t0 = time.time()
|
| 349 |
+
|
| 350 |
+
if self.path == "/decode":
|
| 351 |
+
if decoder_model is None:
|
| 352 |
+
result = {"error": "decoder not loaded"}
|
| 353 |
+
else:
|
| 354 |
+
vec_data = body.get("vector")
|
| 355 |
+
if vec_data:
|
| 356 |
+
v = torch.tensor([vec_data], dtype=torch.float32).to(DEV)
|
| 357 |
+
v = F.normalize(v, dim=-1)
|
| 358 |
+
elif query:
|
| 359 |
+
qe = torch.tensor(
|
| 360 |
+
embedder.encode([query], normalize_embeddings=True),
|
| 361 |
+
dtype=torch.float32
|
| 362 |
+
).to(DEV)
|
| 363 |
+
with torch.no_grad():
|
| 364 |
+
v = model(qe, mem_vecs)
|
| 365 |
+
else:
|
| 366 |
+
result = {"error": "provide query or vector"}
|
| 367 |
+
v = None
|
| 368 |
+
if v is not None:
|
| 369 |
+
text = decode_vector(v.squeeze(0),
|
| 370 |
+
max_len=int(body.get("max_len", 80)),
|
| 371 |
+
temp=float(body.get("temperature", 0.7)))
|
| 372 |
+
result = {"text": text}
|
| 373 |
+
elapsed = time.time() - t0
|
| 374 |
+
result["elapsed"] = elapsed
|
| 375 |
+
resp = json.dumps(result).encode()
|
| 376 |
+
self.send_response(200); self._cors()
|
| 377 |
+
self.send_header("Content-Type", "application/json")
|
| 378 |
+
self.send_header("Content-Length", str(len(resp)))
|
| 379 |
+
self.end_headers(); self.wfile.write(resp)
|
| 380 |
+
print(f"[rmm] /decode {repr(query[:40])} -> {repr((result.get('text') or '')[:60])} ({elapsed:.2f}s)")
|
| 381 |
+
return
|
| 382 |
+
|
| 383 |
+
if self.path == "/synthesize":
|
| 384 |
+
mems = blend(query, top_k)
|
| 385 |
+
synth_text = None
|
| 386 |
+
if decoder_model is not None and query:
|
| 387 |
+
qe = torch.tensor(
|
| 388 |
+
embedder.encode([query], normalize_embeddings=True),
|
| 389 |
+
dtype=torch.float32
|
| 390 |
+
).to(DEV)
|
| 391 |
+
with torch.no_grad():
|
| 392 |
+
rv = model(qe, mem_vecs)
|
| 393 |
+
synth_text = decode_vector(rv.squeeze(0),
|
| 394 |
+
max_len=int(body.get("max_len", 80)),
|
| 395 |
+
temp=float(body.get("temperature", 0.7)))
|
| 396 |
+
elapsed = time.time() - t0
|
| 397 |
+
result = {"synthesized": synth_text, "memories": mems, "elapsed": elapsed}
|
| 398 |
+
resp = json.dumps(result).encode()
|
| 399 |
+
self.send_response(200); self._cors()
|
| 400 |
+
self.send_header("Content-Type", "application/json")
|
| 401 |
+
self.send_header("Content-Length", str(len(resp)))
|
| 402 |
+
self.end_headers(); self.wfile.write(resp)
|
| 403 |
+
print(f"[rmm] /synthesize {repr(query[:40])} -> synth={repr((synth_text or '')[:60])} + {len(mems)} mems ({elapsed:.2f}s)")
|
| 404 |
+
return
|
| 405 |
+
|
| 406 |
+
if self.path == "/attention":
|
| 407 |
+
qe = torch.tensor(
|
| 408 |
+
embedder.encode([query], normalize_embeddings=True),
|
| 409 |
+
dtype=torch.float32
|
| 410 |
+
).to(DEV)
|
| 411 |
+
with torch.no_grad():
|
| 412 |
+
rv, attn_list = model(qe, mem_vecs, return_attn=True)
|
| 413 |
+
avg_attn = torch.stack([a.squeeze(0).squeeze(0) for a in attn_list]).mean(0)
|
| 414 |
+
top_attn_idx = avg_attn.topk(top_k).indices.tolist()
|
| 415 |
+
mems = []
|
| 416 |
+
for i in top_attn_idx:
|
| 417 |
+
t = STRIP.sub("", mem_texts[i]).strip().strip('"').strip("'")
|
| 418 |
+
mems.append({
|
| 419 |
+
"text": t[:400],
|
| 420 |
+
"emotional_weight": ew_list[i],
|
| 421 |
+
"attention": float(avg_attn[i]),
|
| 422 |
+
"idx": i
|
| 423 |
+
})
|
| 424 |
+
result = {"attended": mems}
|
| 425 |
+
elif self.path == "/blend":
|
| 426 |
+
mems = blend(query, top_k)
|
| 427 |
+
result = {"memories": mems}
|
| 428 |
+
else:
|
| 429 |
+
mems = navigate(query, top_k)
|
| 430 |
+
result = {"memories": mems}
|
| 431 |
+
|
| 432 |
+
elapsed = time.time() - t0
|
| 433 |
+
result["elapsed"] = elapsed
|
| 434 |
+
resp = json.dumps(result).encode()
|
| 435 |
+
self.send_response(200); self._cors()
|
| 436 |
+
self.send_header("Content-Type", "application/json")
|
| 437 |
+
self.send_header("Content-Length", str(len(resp)))
|
| 438 |
+
self.end_headers(); self.wfile.write(resp)
|
| 439 |
+
print(f"[rmm] {self.path} {repr(query[:40])} -> {len(mems)} results ({elapsed:.2f}s)")
|
| 440 |
+
|
| 441 |
+
def do_GET(self):
|
| 442 |
+
if self.path == "/health":
|
| 443 |
+
resp = b'{"status":"ok"}'
|
| 444 |
+
self.send_response(200); self._cors()
|
| 445 |
+
self.send_header("Content-Type","application/json")
|
| 446 |
+
self.send_header("Content-Length",str(len(resp)))
|
| 447 |
+
self.end_headers(); self.wfile.write(resp)
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
|
| 451 |
+
daemon_threads = True
|
| 452 |
+
|
| 453 |
+
if __name__ == "__main__":
|
| 454 |
+
server = ThreadedHTTPServer(("0.0.0.0", PORT), Handler)
|
| 455 |
+
print(f"[rmm] listening on http://localhost:{PORT}")
|
| 456 |
+
print(f"[rmm] endpoints: /navigate /blend /decode /synthesize /attention /health")
|
| 457 |
+
server.serve_forever()
|