Spaces:
Sleeping
Sleeping
Quijotic theme
Browse files
app.py
CHANGED
|
@@ -1,8 +1,7 @@
|
|
| 1 |
"""
|
| 2 |
Fractional Memory for Language Models β Interactive Demo
|
| 3 |
=========================================================
|
| 4 |
-
Hugging Face Spaces app.
|
| 5 |
-
Custom queries are embedded via the HF Inference API (free, no GPU needed).
|
| 6 |
|
| 7 |
Quijotic Research LLC β 2026
|
| 8 |
"""
|
|
@@ -13,12 +12,12 @@ import os
|
|
| 13 |
import requests
|
| 14 |
from scipy.special import gamma as gamma_fn
|
| 15 |
from dataclasses import dataclass
|
| 16 |
-
from typing import List,
|
| 17 |
import re
|
| 18 |
|
| 19 |
|
| 20 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 21 |
-
# Mittag-Leffler Kernel
|
| 22 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 23 |
|
| 24 |
class MittagLeffler:
|
|
@@ -53,7 +52,7 @@ class MittagLeffler:
|
|
| 53 |
|
| 54 |
|
| 55 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 56 |
-
# Memory Store
|
| 57 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 58 |
|
| 59 |
@dataclass
|
|
@@ -64,9 +63,6 @@ class MemEntry:
|
|
| 64 |
embedding: np.ndarray
|
| 65 |
timestamp: float
|
| 66 |
|
| 67 |
-
def __repr__(self):
|
| 68 |
-
return f"MemEntry({self.category}: {self.value}, mo={self.timestamp})"
|
| 69 |
-
|
| 70 |
|
| 71 |
class MemoryStore:
|
| 72 |
TEMPORAL_KEYWORDS = {
|
|
@@ -85,9 +81,6 @@ class MemoryStore:
|
|
| 85 |
self.alpha = alpha
|
| 86 |
self.lam = lam
|
| 87 |
self.entries: List[MemEntry] = []
|
| 88 |
-
self._emb_matrix = None
|
| 89 |
-
self._emb_normed = None
|
| 90 |
-
self._timestamps = None
|
| 91 |
self._dirty = True
|
| 92 |
|
| 93 |
def add(self, entry: MemEntry):
|
|
@@ -134,12 +127,11 @@ class MemoryStore:
|
|
| 134 |
for i in reranked]
|
| 135 |
else:
|
| 136 |
idx = np.argsort(sims)[::-1][:top_k]
|
| 137 |
-
return [(self.entries[i], float(sims[i]), 1.0, "static")
|
| 138 |
-
for i in idx]
|
| 139 |
|
| 140 |
|
| 141 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 142 |
-
# HF Inference API
|
| 143 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 144 |
|
| 145 |
HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
|
@@ -147,17 +139,14 @@ EMBED_MODEL = "nomic-ai/nomic-embed-text-v1.5"
|
|
| 147 |
EMBED_API = f"https://router.huggingface.co/hf-inference/pipeline/feature-extraction/{EMBED_MODEL}"
|
| 148 |
|
| 149 |
|
| 150 |
-
def embed_text_hf(text
|
| 151 |
-
"""Embed a single text via HF Inference API."""
|
| 152 |
if not HF_TOKEN:
|
| 153 |
return None
|
| 154 |
try:
|
| 155 |
resp = requests.post(
|
| 156 |
EMBED_API,
|
| 157 |
headers={"Authorization": f"Bearer {HF_TOKEN}"},
|
| 158 |
-
json={"inputs": text},
|
| 159 |
-
timeout=30,
|
| 160 |
-
)
|
| 161 |
resp.raise_for_status()
|
| 162 |
data = resp.json()
|
| 163 |
if isinstance(data, list) and len(data) > 0:
|
|
@@ -169,55 +158,44 @@ def embed_text_hf(text: str) -> Optional[np.ndarray]:
|
|
| 169 |
|
| 170 |
|
| 171 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 172 |
-
# Load
|
| 173 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 174 |
|
| 175 |
def load_baked():
|
| 176 |
-
"""Load pre-computed embeddings and build the memory store."""
|
| 177 |
data = np.load("embeddings.npz", allow_pickle=True)
|
| 178 |
-
|
| 179 |
store = MemoryStore(alpha=0.6, lam=0.05)
|
| 180 |
-
fact_embs = data["fact_embeddings"]
|
| 181 |
-
fact_texts = data["fact_texts"]
|
| 182 |
-
fact_values = data["fact_values"]
|
| 183 |
-
fact_cats = data["fact_categories"]
|
| 184 |
-
fact_months = data["fact_months"]
|
| 185 |
|
| 186 |
-
for i in range(len(fact_texts)):
|
| 187 |
store.add(MemEntry(
|
| 188 |
-
text=str(fact_texts[i]),
|
| 189 |
-
value=str(fact_values[i]),
|
| 190 |
-
category=str(
|
| 191 |
-
embedding=
|
| 192 |
-
timestamp=float(fact_months[i]),
|
| 193 |
))
|
| 194 |
|
| 195 |
-
# Pre-baked question embeddings
|
| 196 |
-
q_embs = data["q_embeddings"]
|
| 197 |
-
q_texts = [str(x) for x in data["q_texts"]]
|
| 198 |
-
q_cats = [str(x) for x in data["q_categories"]]
|
| 199 |
-
q_types = [str(x) for x in data["q_types"]]
|
| 200 |
-
q_correct = [str(x) for x in data["q_correct"]]
|
| 201 |
-
|
| 202 |
q_lookup = {}
|
|
|
|
| 203 |
for i, qt in enumerate(q_texts):
|
| 204 |
-
q_lookup[qt] =
|
| 205 |
|
| 206 |
-
|
|
|
|
| 207 |
|
|
|
|
| 208 |
|
| 209 |
-
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 210 |
-
# Gradio App
|
| 211 |
-
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 212 |
|
| 213 |
print("Loading embeddings...")
|
| 214 |
-
STORE, Q_LOOKUP,
|
| 215 |
QUERY_TIME = 25.0
|
| 216 |
-
print(f"Loaded {len(STORE.entries)} facts
|
|
|
|
| 217 |
|
|
|
|
|
|
|
|
|
|
| 218 |
|
| 219 |
-
def get_embedding(question
|
| 220 |
-
"""Get embedding: check pre-baked first, then HF API."""
|
| 221 |
if question in Q_LOOKUP:
|
| 222 |
return Q_LOOKUP[question]
|
| 223 |
return embed_text_hf(question)
|
|
@@ -225,81 +203,114 @@ def get_embedding(question: str) -> Optional[np.ndarray]:
|
|
| 225 |
|
| 226 |
def query_memory(question):
|
| 227 |
if not question.strip():
|
| 228 |
-
return "", "", ""
|
| 229 |
|
| 230 |
qe = get_embedding(question)
|
| 231 |
if qe is None:
|
| 232 |
-
return ("
|
| 233 |
-
"
|
| 234 |
-
"", "", "")
|
| 235 |
|
| 236 |
is_temporal = STORE.is_temporal(question)
|
| 237 |
-
route_info = (f"**Route:** {'temporal β ML kernel rerank' if is_temporal else 'static β cosine'} \n"
|
| 238 |
-
f"**Temporal query:** {'Yes' if is_temporal else 'No'}")
|
| 239 |
-
|
| 240 |
-
# RAG
|
| 241 |
rag = STORE.query_cosine(qe, top_k=3)
|
| 242 |
-
# Hybrid
|
| 243 |
hyb = STORE.query_hybrid(qe, QUERY_TIME, question, shortlist=10, top_k=3)
|
| 244 |
|
| 245 |
-
rag_val = rag[0][1] if rag else ""
|
| 246 |
-
hyb_val = hyb[0][1] if hyb else ""
|
| 247 |
rag_answer = rag[0][0].value
|
| 248 |
hyb_answer = hyb[0][0].value
|
|
|
|
| 249 |
|
|
|
|
| 250 |
if rag_answer == hyb_answer:
|
| 251 |
-
verdict = f"
|
| 252 |
else:
|
| 253 |
-
verdict = f"
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
for i, (e, c, t) in enumerate(rag[:3]):
|
| 269 |
-
rag_md +=
|
| 270 |
|
| 271 |
-
hyb_md = "
|
| 272 |
for i, (e, c, t, r) in enumerate(hyb[:3]):
|
| 273 |
-
hyb_md +=
|
| 274 |
-
|
| 275 |
-
return verdict, route_info, rag_md, hyb_md
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
# ββ Check for correct answer ββββββββββββββββββββββββββββββββββββ
|
| 279 |
-
|
| 280 |
-
def get_ground_truth(question):
|
| 281 |
-
"""Look up ground truth if this is a pre-baked question."""
|
| 282 |
-
for i, qt in enumerate(Q_TEXTS):
|
| 283 |
-
if qt == question:
|
| 284 |
-
return Q_CORRECT[i], Q_TYPES[i], Q_CATS[i]
|
| 285 |
-
return None, None, None
|
| 286 |
-
|
| 287 |
|
| 288 |
-
|
| 289 |
-
verdict, route_info, rag_md, hyb_md = query_memory(question)
|
| 290 |
|
| 291 |
-
# Add ground truth if available
|
| 292 |
-
correct, qtype, qcat = get_ground_truth(question)
|
| 293 |
-
if correct:
|
| 294 |
-
gt = f"\n\n**Ground truth:** {correct} ({qtype}, {qcat})"
|
| 295 |
-
verdict += gt
|
| 296 |
-
|
| 297 |
-
return verdict, route_info, rag_md, hyb_md
|
| 298 |
|
|
|
|
|
|
|
|
|
|
| 299 |
|
| 300 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
|
| 302 |
-
|
| 303 |
"What is Alex's current salary?",
|
| 304 |
"Where does Alex live now?",
|
| 305 |
"What is Alex's current job title?",
|
|
@@ -312,6 +323,9 @@ EXAMPLES = [
|
|
| 312 |
"What is Alex's favorite restaurant now?",
|
| 313 |
"What is Alex reading now?",
|
| 314 |
"How does Alex get to work now?",
|
|
|
|
|
|
|
|
|
|
| 315 |
"Did Alex ever win a hackathon?",
|
| 316 |
"Does Alex have a dog?",
|
| 317 |
"Where did Alex go to school?",
|
|
@@ -323,140 +337,128 @@ EXAMPLES = [
|
|
| 323 |
]
|
| 324 |
|
| 325 |
|
| 326 |
-
#
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
) as app:
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
"
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
"
|
| 342 |
-
|
| 343 |
-
"
|
| 344 |
-
|
| 345 |
-
|
|
|
|
|
|
|
|
|
|
| 346 |
|
| 347 |
with gr.Tabs():
|
| 348 |
-
with gr.Tab("
|
|
|
|
|
|
|
| 349 |
with gr.Row():
|
| 350 |
-
question_input = gr.Textbox(
|
| 351 |
-
|
| 352 |
-
placeholder="What is Alex's current salary?",
|
| 353 |
-
scale=4)
|
| 354 |
query_btn = gr.Button("Ask", variant="primary", scale=1)
|
| 355 |
|
| 356 |
-
gr.
|
| 357 |
-
examples=[[q] for q in EXAMPLES],
|
| 358 |
-
inputs=[question_input],
|
| 359 |
-
label="Example questions (click to try)")
|
| 360 |
-
|
| 361 |
-
verdict_box = gr.Markdown()
|
| 362 |
-
route_box = gr.Markdown()
|
| 363 |
-
|
| 364 |
with gr.Row():
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
gr.Markdown("""
|
| 379 |
-
##
|
| 380 |
-
|
| 381 |
-
You chat with an AI assistant over weeks. Your salary changes, you move cities,
|
| 382 |
-
you switch jobs. You ask: **"What's my current salary?"**
|
| 383 |
-
|
| 384 |
-
Vanilla RAG returns the answer with the highest embedding similarity β which might
|
| 385 |
-
be your salary from 18 months ago, because the phrasing happened to match better.
|
| 386 |
|
| 387 |
-
|
|
|
|
|
|
|
| 388 |
|
| 389 |
-
**Layer
|
| 390 |
-
|
| 391 |
|
| 392 |
-
**Layer
|
| 393 |
-
|
| 394 |
|
| 395 |
-
|
| 396 |
-
`cosine Γ E_Ξ±(-λ·Ξt^Ξ±)`. The Mittag-Leffler kernel breaks the cosine tie
|
| 397 |
-
by favoring recent facts.
|
| 398 |
|
| 399 |
## The Kernel
|
| 400 |
|
| 401 |
-
`E_Ξ±(
|
| 402 |
-
|
| 403 |
-
|
| 404 |
|
| 405 |
-
|
| 406 |
|
| 407 |
-
|
| 408 |
|
| 409 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 410 |
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
| Method | Temporal Queries | Static Queries | Overall |
|
| 414 |
-
|--------|:---:|:---:|:---:|
|
| 415 |
-
| Vanilla RAG (cosine) | 19.3% | 83.3% | 41.4% |
|
| 416 |
-
| **Hybrid Fractional** | **66.7%** | **83.3%** | **72.4%** |
|
| 417 |
-
| Ξ | **+47.4 pp** | **0.0 pp** | **+31.0 pp** |
|
| 418 |
|
| 419 |
-
|
| 420 |
-
|
|
|
|
| 421 |
|
| 422 |
-
|
| 423 |
|
| 424 |
-
-
|
| 425 |
-
- [GitHub](https://github.com/QuijoticResearch/fractional-memory)
|
| 426 |
-
- [Paper I: Operator Derivative (Zenodo)](https://doi.org/10.5281/zenodo.18624822)
|
| 427 |
-
- [Paper II: Banach/LΓ©vy Extension (Zenodo)](https://doi.org/10.5281/zenodo.18625711)
|
| 428 |
-
- [Paper III: Volterra-LΓ©vy Finance (Zenodo)](https://doi.org/10.5281/zenodo.19211991)
|
| 429 |
-
""")
|
| 430 |
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
|
| 435 |
-
|
|
|
|
|
|
|
| 436 |
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
| Phone | **3/3** | 3 | iPhone 14 β iPhone 15 β Samsung S25 |
|
| 441 |
-
| Reading | **3/3** | 3 | Kahneman β Christian β Fontes |
|
| 442 |
-
| Team size | **3/3** | 5 | 4 β 8 β 3 β 12 β 6 |
|
| 443 |
-
| Salary | **4/5** | 10 | $85k β $240k over 23 months |
|
| 444 |
-
| Job title | **4/5** | 7 | Junior DS β Staff ML Engineer |
|
| 445 |
-
| Company | **3/4** | 3 | DataCorp β TechVentures β NeuralScale |
|
| 446 |
|
| 447 |
-
|
|
|
|
| 448 |
|
| 449 |
-
**
|
| 450 |
-
is 0% (the query "Where does Alex live?" matches "Alex lives in Boston" but
|
| 451 |
-
not "Alex relocated to Denver for the new job"). With normalization,
|
| 452 |
-
all location facts embed as "Alex lives in X" and the kernel picks the latest.
|
| 453 |
|
| 454 |
-
|
| 455 |
-
the temporal kernel entirely β no penalty for being an old fact.
|
| 456 |
|
| 457 |
-
*
|
| 458 |
-
fractional and exponential kernels tie. At extreme timescales (Paper IV E13:
|
| 459 |
-
16,384 tokens, frozen parameters), exponential collapses and fractional holds.
|
| 460 |
""")
|
| 461 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 462 |
app.launch()
|
|
|
|
| 1 |
"""
|
| 2 |
Fractional Memory for Language Models β Interactive Demo
|
| 3 |
=========================================================
|
| 4 |
+
Hugging Face Spaces app. Quijotic Research theme.
|
|
|
|
| 5 |
|
| 6 |
Quijotic Research LLC β 2026
|
| 7 |
"""
|
|
|
|
| 12 |
import requests
|
| 13 |
from scipy.special import gamma as gamma_fn
|
| 14 |
from dataclasses import dataclass
|
| 15 |
+
from typing import List, Optional
|
| 16 |
import re
|
| 17 |
|
| 18 |
|
| 19 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 20 |
+
# Mittag-Leffler Kernel
|
| 21 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 22 |
|
| 23 |
class MittagLeffler:
|
|
|
|
| 52 |
|
| 53 |
|
| 54 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 55 |
+
# Memory Store
|
| 56 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 57 |
|
| 58 |
@dataclass
|
|
|
|
| 63 |
embedding: np.ndarray
|
| 64 |
timestamp: float
|
| 65 |
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
class MemoryStore:
|
| 68 |
TEMPORAL_KEYWORDS = {
|
|
|
|
| 81 |
self.alpha = alpha
|
| 82 |
self.lam = lam
|
| 83 |
self.entries: List[MemEntry] = []
|
|
|
|
|
|
|
|
|
|
| 84 |
self._dirty = True
|
| 85 |
|
| 86 |
def add(self, entry: MemEntry):
|
|
|
|
| 127 |
for i in reranked]
|
| 128 |
else:
|
| 129 |
idx = np.argsort(sims)[::-1][:top_k]
|
| 130 |
+
return [(self.entries[i], float(sims[i]), 1.0, "static") for i in idx]
|
|
|
|
| 131 |
|
| 132 |
|
| 133 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 134 |
+
# HF Inference API
|
| 135 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 136 |
|
| 137 |
HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
|
|
|
| 139 |
EMBED_API = f"https://router.huggingface.co/hf-inference/pipeline/feature-extraction/{EMBED_MODEL}"
|
| 140 |
|
| 141 |
|
| 142 |
+
def embed_text_hf(text):
|
|
|
|
| 143 |
if not HF_TOKEN:
|
| 144 |
return None
|
| 145 |
try:
|
| 146 |
resp = requests.post(
|
| 147 |
EMBED_API,
|
| 148 |
headers={"Authorization": f"Bearer {HF_TOKEN}"},
|
| 149 |
+
json={"inputs": text}, timeout=30)
|
|
|
|
|
|
|
| 150 |
resp.raise_for_status()
|
| 151 |
data = resp.json()
|
| 152 |
if isinstance(data, list) and len(data) > 0:
|
|
|
|
| 158 |
|
| 159 |
|
| 160 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 161 |
+
# Load Data
|
| 162 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 163 |
|
| 164 |
def load_baked():
|
|
|
|
| 165 |
data = np.load("embeddings.npz", allow_pickle=True)
|
|
|
|
| 166 |
store = MemoryStore(alpha=0.6, lam=0.05)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
+
for i in range(len(data["fact_texts"])):
|
| 169 |
store.add(MemEntry(
|
| 170 |
+
text=str(data["fact_texts"][i]),
|
| 171 |
+
value=str(data["fact_values"][i]),
|
| 172 |
+
category=str(data["fact_categories"][i]),
|
| 173 |
+
embedding=data["fact_embeddings"][i],
|
| 174 |
+
timestamp=float(data["fact_months"][i]),
|
| 175 |
))
|
| 176 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
q_lookup = {}
|
| 178 |
+
q_texts = [str(x) for x in data["q_texts"]]
|
| 179 |
for i, qt in enumerate(q_texts):
|
| 180 |
+
q_lookup[qt] = data["q_embeddings"][i]
|
| 181 |
|
| 182 |
+
q_correct = {str(data["q_texts"][i]): str(data["q_correct"][i])
|
| 183 |
+
for i in range(len(q_texts))}
|
| 184 |
|
| 185 |
+
return store, q_lookup, q_correct
|
| 186 |
|
|
|
|
|
|
|
|
|
|
| 187 |
|
| 188 |
print("Loading embeddings...")
|
| 189 |
+
STORE, Q_LOOKUP, Q_CORRECT = load_baked()
|
| 190 |
QUERY_TIME = 25.0
|
| 191 |
+
print(f"Loaded {len(STORE.entries)} facts.")
|
| 192 |
+
|
| 193 |
|
| 194 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 195 |
+
# Query Logic
|
| 196 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 197 |
|
| 198 |
+
def get_embedding(question):
|
|
|
|
| 199 |
if question in Q_LOOKUP:
|
| 200 |
return Q_LOOKUP[question]
|
| 201 |
return embed_text_hf(question)
|
|
|
|
| 203 |
|
| 204 |
def query_memory(question):
|
| 205 |
if not question.strip():
|
| 206 |
+
return "", "", ""
|
| 207 |
|
| 208 |
qe = get_embedding(question)
|
| 209 |
if qe is None:
|
| 210 |
+
return ("Could not embed this query. Try one of the examples below, "
|
| 211 |
+
"or set HF_TOKEN in Space secrets for custom queries."), "", ""
|
|
|
|
| 212 |
|
| 213 |
is_temporal = STORE.is_temporal(question)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
rag = STORE.query_cosine(qe, top_k=3)
|
|
|
|
| 215 |
hyb = STORE.query_hybrid(qe, QUERY_TIME, question, shortlist=10, top_k=3)
|
| 216 |
|
|
|
|
|
|
|
| 217 |
rag_answer = rag[0][0].value
|
| 218 |
hyb_answer = hyb[0][0].value
|
| 219 |
+
ground_truth = Q_CORRECT.get(question, None)
|
| 220 |
|
| 221 |
+
# Verdict
|
| 222 |
if rag_answer == hyb_answer:
|
| 223 |
+
verdict = f"Both return **{hyb_answer}**"
|
| 224 |
else:
|
| 225 |
+
verdict = f"RAG: **{rag_answer}** β Fractional: **{hyb_answer}**"
|
| 226 |
+
|
| 227 |
+
if ground_truth:
|
| 228 |
+
rag_ok = "correct" if rag_answer == ground_truth else "wrong"
|
| 229 |
+
hyb_ok = "correct" if hyb_answer == ground_truth else "wrong"
|
| 230 |
+
verdict += f"\n\nGround truth: **{ground_truth}** Β· RAG {rag_ok} Β· Fractional {hyb_ok}"
|
| 231 |
+
|
| 232 |
+
route = "temporal β cosine shortlist β ML kernel rerank" if is_temporal else "static β cosine only"
|
| 233 |
+
verdict += f"\n\nRoute: `{route}`"
|
| 234 |
+
|
| 235 |
+
# Format
|
| 236 |
+
def fmt_rag(e, cos, rank):
|
| 237 |
+
check = ""
|
| 238 |
+
if ground_truth:
|
| 239 |
+
check = " β" if e.value == ground_truth else " β"
|
| 240 |
+
return (f"**{rank}.** **{e.value}**{check} \n"
|
| 241 |
+
f"month {int(e.timestamp)} Β· `cos = {cos:.3f}` \n"
|
| 242 |
+
f"*{e.text}*\n\n")
|
| 243 |
+
|
| 244 |
+
def fmt_hyb(e, cos, tw, route, rank):
|
| 245 |
+
check = ""
|
| 246 |
+
if ground_truth:
|
| 247 |
+
check = " β" if e.value == ground_truth else " β"
|
| 248 |
+
ml_str = f" Γ ML = {tw:.3f}" if route == "temporal" else ""
|
| 249 |
+
return (f"**{rank}.** **{e.value}**{check} \n"
|
| 250 |
+
f"month {int(e.timestamp)} Β· `cos = {cos:.3f}{ml_str}` \n"
|
| 251 |
+
f"*{e.text}*\n\n")
|
| 252 |
+
|
| 253 |
+
rag_md = ""
|
| 254 |
for i, (e, c, t) in enumerate(rag[:3]):
|
| 255 |
+
rag_md += fmt_rag(e, c, i+1)
|
| 256 |
|
| 257 |
+
hyb_md = ""
|
| 258 |
for i, (e, c, t, r) in enumerate(hyb[:3]):
|
| 259 |
+
hyb_md += fmt_hyb(e, c, t, r, i+1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
|
| 261 |
+
return verdict, rag_md, hyb_md
|
|
|
|
| 262 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
|
| 264 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 265 |
+
# CSS
|
| 266 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 267 |
|
| 268 |
+
CSS = """
|
| 269 |
+
@import url('https://fonts.googleapis.com/css2?family=EB+Garamond:ital,wght@0,400;0,600;1,400&family=JetBrains+Mono:wght@400;500&display=swap');
|
| 270 |
+
|
| 271 |
+
.gradio-container {
|
| 272 |
+
max-width: 960px !important;
|
| 273 |
+
font-family: 'EB Garamond', Georgia, serif !important;
|
| 274 |
+
background: #fafaf8 !important;
|
| 275 |
+
color: #1a1a1a !important;
|
| 276 |
+
}
|
| 277 |
+
h1, h2, h3, h4 {
|
| 278 |
+
font-family: 'EB Garamond', Georgia, serif !important;
|
| 279 |
+
font-weight: 600 !important;
|
| 280 |
+
}
|
| 281 |
+
code {
|
| 282 |
+
font-family: 'JetBrains Mono', monospace !important;
|
| 283 |
+
font-size: 0.85em;
|
| 284 |
+
background: #f0f0ea;
|
| 285 |
+
padding: 1px 5px;
|
| 286 |
+
border-radius: 3px;
|
| 287 |
+
}
|
| 288 |
+
.verdict-box {
|
| 289 |
+
border-left: 3px solid #1a1a1a;
|
| 290 |
+
padding: 12px 16px;
|
| 291 |
+
margin: 8px 0;
|
| 292 |
+
background: #f5f5f0;
|
| 293 |
+
}
|
| 294 |
+
.result-col {
|
| 295 |
+
border: 1px solid #ddd;
|
| 296 |
+
border-radius: 4px;
|
| 297 |
+
padding: 16px;
|
| 298 |
+
background: #fff;
|
| 299 |
+
}
|
| 300 |
+
button.primary {
|
| 301 |
+
background: #1a1a1a !important;
|
| 302 |
+
color: #fafafa !important;
|
| 303 |
+
font-family: 'EB Garamond', Georgia, serif !important;
|
| 304 |
+
font-size: 1.05em !important;
|
| 305 |
+
}
|
| 306 |
+
button.primary:hover { background: #333 !important; }
|
| 307 |
+
.tab-nav button {
|
| 308 |
+
font-family: 'EB Garamond', Georgia, serif !important;
|
| 309 |
+
font-size: 1.05em !important;
|
| 310 |
+
}
|
| 311 |
+
"""
|
| 312 |
|
| 313 |
+
TEMPORAL_EXAMPLES = [
|
| 314 |
"What is Alex's current salary?",
|
| 315 |
"Where does Alex live now?",
|
| 316 |
"What is Alex's current job title?",
|
|
|
|
| 323 |
"What is Alex's favorite restaurant now?",
|
| 324 |
"What is Alex reading now?",
|
| 325 |
"How does Alex get to work now?",
|
| 326 |
+
]
|
| 327 |
+
|
| 328 |
+
STATIC_EXAMPLES = [
|
| 329 |
"Did Alex ever win a hackathon?",
|
| 330 |
"Does Alex have a dog?",
|
| 331 |
"Where did Alex go to school?",
|
|
|
|
| 337 |
]
|
| 338 |
|
| 339 |
|
| 340 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 341 |
+
# App
|
| 342 |
+
# ββββββββββββββββββοΏ½οΏ½οΏ½ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 343 |
+
|
| 344 |
+
with gr.Blocks(title="Fractional Memory β Quijotic Research",
|
| 345 |
+
css=CSS, theme=gr.themes.Base()) as app:
|
| 346 |
+
|
| 347 |
+
gr.HTML("""
|
| 348 |
+
<div style="text-align:center; padding:24px 0 0;">
|
| 349 |
+
<h1 style="font-family:'EB Garamond',Georgia,serif; font-size:2.2em;
|
| 350 |
+
font-weight:600; margin:0; color:#1a1a1a;">
|
| 351 |
+
Fractional Memory for Language Models</h1>
|
| 352 |
+
<div style="font-family:'JetBrains Mono',monospace; font-size:1.4em;
|
| 353 |
+
padding:12px 0; letter-spacing:0.05em; color:#1a1a1a;">
|
| 354 |
+
(Id β πΌ) = Ξ΄ Ξ D</div>
|
| 355 |
+
<div style="font-style:italic; color:#555; margin-bottom:4px;">
|
| 356 |
+
Retrieval that knows what changed.</div>
|
| 357 |
+
<div style="font-size:0.9em; color:#888; margin-bottom:16px;">
|
| 358 |
+
Paper V Β· Quijotic Research LLC Β·
|
| 359 |
+
<a href="https://quijotic.com" style="color:#666;">quijotic.com</a> Β·
|
| 360 |
+
<a href="https://github.com/QuijoticResearch" style="color:#666;">GitHub</a></div>
|
| 361 |
+
<hr style="border:none; border-top:1px solid #ccc; margin:0 0 16px;">
|
| 362 |
+
</div>""")
|
| 363 |
|
| 364 |
with gr.Tabs():
|
| 365 |
+
with gr.Tab("Query"):
|
| 366 |
+
gr.Markdown("Ask about Alex's life across 24 months β 121 facts, "
|
| 367 |
+
"16 evolving categories.")
|
| 368 |
with gr.Row():
|
| 369 |
+
question_input = gr.Textbox(label="Question",
|
| 370 |
+
placeholder="What is Alex's current salary?", scale=4)
|
|
|
|
|
|
|
| 371 |
query_btn = gr.Button("Ask", variant="primary", scale=1)
|
| 372 |
|
| 373 |
+
verdict_box = gr.Markdown(elem_classes=["verdict-box"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 374 |
with gr.Row():
|
| 375 |
+
with gr.Column(elem_classes=["result-col"]):
|
| 376 |
+
gr.Markdown("#### Vanilla RAG")
|
| 377 |
+
rag_output = gr.Markdown()
|
| 378 |
+
with gr.Column(elem_classes=["result-col"]):
|
| 379 |
+
gr.Markdown("#### Fractional Memory")
|
| 380 |
+
frac_output = gr.Markdown()
|
| 381 |
+
|
| 382 |
+
gr.Markdown("---\n**Temporal queries** β facts change, the kernel resolves recency:")
|
| 383 |
+
gr.Examples(examples=[[q] for q in TEMPORAL_EXAMPLES],
|
| 384 |
+
inputs=[question_input], label="")
|
| 385 |
+
gr.Markdown("**Static queries** β routing preserves cosine accuracy:")
|
| 386 |
+
gr.Examples(examples=[[q] for q in STATIC_EXAMPLES],
|
| 387 |
+
inputs=[question_input], label="")
|
| 388 |
+
|
| 389 |
+
query_btn.click(fn=query_memory, inputs=[question_input],
|
| 390 |
+
outputs=[verdict_box, rag_output, frac_output])
|
| 391 |
+
question_input.submit(fn=query_memory, inputs=[question_input],
|
| 392 |
+
outputs=[verdict_box, rag_output, frac_output])
|
| 393 |
+
|
| 394 |
+
with gr.Tab("Architecture"):
|
| 395 |
gr.Markdown("""
|
| 396 |
+
## Normalize β Route β Rerank
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 397 |
|
| 398 |
+
**Layer 1: Normalize.** Facts are embedded using query-aligned templates.
|
| 399 |
+
All salary facts embed as *"Alex's salary is $X per year."* This creates
|
| 400 |
+
temporal ambiguity β the regime where the kernel provides its advantage.
|
| 401 |
|
| 402 |
+
**Layer 2: Route.** Temporal queries β kernel rerank. Static queries β pure cosine.
|
| 403 |
+
Precision over recall: no false positives on static queries.
|
| 404 |
|
| 405 |
+
**Layer 3: Rerank.** Top-10 by cosine, then rerank by `cos Γ E_Ξ±(βλ·Ξt^Ξ±)`.
|
| 406 |
+
The kernel is a tiebreaker, not a global signal.
|
| 407 |
|
| 408 |
+
---
|
|
|
|
|
|
|
| 409 |
|
| 410 |
## The Kernel
|
| 411 |
|
| 412 |
+
`E_Ξ±(βx)` is the Mittag-Leffler function β the resolvent of the fractional SPDE.
|
| 413 |
+
Power-law decay: old facts get low weight but never zero. The store-and-query
|
| 414 |
+
mechanism is the **exact** mild solution for discrete inputs (Paper IV, Thm 8.9).
|
| 415 |
|
| 416 |
+
---
|
| 417 |
|
| 418 |
+
## E15 Results
|
| 419 |
|
| 420 |
+
| | Temporal | Static | Overall |
|
| 421 |
+
|---|:---:|:---:|:---:|
|
| 422 |
+
| Vanilla RAG | 19.3% | 83.3% | 41.4% |
|
| 423 |
+
| Hybrid Fractional | **66.7%** | **83.3%** | **72.4%** |
|
| 424 |
+
| Ξ | +47.4 pp | 0.0 pp | +31.0 pp |
|
| 425 |
|
| 426 |
+
The architecture is the contribution. The kernel is the insurance policy.
|
| 427 |
+
""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 428 |
|
| 429 |
+
with gr.Tab("Papers"):
|
| 430 |
+
gr.Markdown("""
|
| 431 |
+
## The Operator Derivative Program
|
| 432 |
|
| 433 |
+
*D = Ξ΄\** β defined by duality with the stochastic integral.
|
| 434 |
|
| 435 |
+
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 436 |
|
| 437 |
+
**I.** The Operator Derivative in Continuous Stochastic Calculus
|
| 438 |
+
Β· [Zenodo](https://doi.org/10.5281/zenodo.18624822)
|
| 439 |
+
Β· [Lean 4](https://github.com/QuijoticResearch/operator-derivative-lean)
|
| 440 |
|
| 441 |
+
**II.** Operator Factorization Beyond Hilbert Spaces
|
| 442 |
+
Β· [Zenodo](https://doi.org/10.5281/zenodo.18625711)
|
| 443 |
+
Β· [Lean 4](https://github.com/QuijoticResearch/banach-levy-lean)
|
| 444 |
|
| 445 |
+
**III.** The Boundary of Hedgeability
|
| 446 |
+
Β· [Zenodo](https://doi.org/10.5281/zenodo.19211991)
|
| 447 |
+
Β· [Lean 4](https://github.com/QuijoticResearch/volterra-levy)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 448 |
|
| 449 |
+
**IV.** Fractional Memory for Attention-Based Systems
|
| 450 |
+
Β· Zenodo forthcoming
|
| 451 |
|
| 452 |
+
**V.** Persistent Memory for Language Models β *this demo*
|
|
|
|
|
|
|
|
|
|
| 453 |
|
| 454 |
+
---
|
|
|
|
| 455 |
|
| 456 |
+
*Quijotic Research LLC Β· Ramiro Fontes Β· New York*
|
|
|
|
|
|
|
| 457 |
""")
|
| 458 |
|
| 459 |
+
gr.HTML("""<hr style="border:none;border-top:1px solid #ccc;margin:24px 0 8px;">
|
| 460 |
+
<div style="text-align:center;font-size:0.85em;color:#999;padding-bottom:16px;">
|
| 461 |
+
Β© 2026 Quijotic Research LLC Β·
|
| 462 |
+
<a href="https://quijotic.com" style="color:#999;">quijotic.com</a></div>""")
|
| 463 |
+
|
| 464 |
app.launch()
|