""" Fractional Memory for Language Models — Interactive Demo ========================================================= Companion to "Temporal Memory for Language Models". Hugging Face Spaces app. Vanilla RAG retrieves the most semantically similar facts. Temporal memory keeps competing facts about the same attribute and reranks them by query intent (current vs historical). Fractional / Mittag-Leffler is one temporal selector; EWMA and a generic power-law are also exposed for direct comparison. Quijotic Research LLC — 2026 """ import gradio as gr import numpy as np import os import requests from scipy.special import gamma as gamma_fn from dataclasses import dataclass from typing import List, Optional import re # ═══════════════════════════════════════════════════════════════════ # Mittag-Leffler Kernel # ═══════════════════════════════════════════════════════════════════ class MittagLeffler: def __init__(self, alpha, n_table=20000, x_max=200.0, x_switch=3.0, n_series=200): assert 0 < alpha < 1 self.alpha = alpha xs = np.linspace(0, x_max, n_table) ys = np.empty(n_table) for i, x in enumerate(xs): if x <= x_switch: result = 0.0 for k in range(n_series): g = gamma_fn(alpha * k + 1) if abs(g) < 1e-300: break term = ((-x) ** k) / g result += term if k > 20 and abs(term) < 1e-15 * max(abs(result), 1e-30): break ys[i] = result else: g = gamma_fn(1 - alpha) ys[i] = 1.0 / (x * g) if abs(g) > 1e-300 and x > 1e-300 else 0.0 ys = np.maximum(ys, 0.0) for i in range(1, len(ys)): ys[i] = min(ys[i], ys[i-1]) self._xs, self._ys = xs, ys def __call__(self, x): return np.interp(np.abs(np.asarray(x, dtype=np.float64)), self._xs, self._ys) # ═══════════════════════════════════════════════════════════════════ # Memory Store # ═══════════════════════════════════════════════════════════════════ @dataclass class MemEntry: text: str value: str category: str embedding: np.ndarray timestamp: float class MemoryStore: TEMPORAL_KEYWORDS = { "current", "currently", "now", "present", "presently", "latest", "recent", "recently", "today", } TEMPORAL_PHRASES = [ "these days", "at the moment", "right now", "as of now", "how big is", "how many people are on", "how much does alex pay", "how much does alex earn", "what is alex working on", "what is alex building", ] def __init__(self, alpha=0.6, lam=0.05): self.ml = MittagLeffler(alpha) self.alpha = alpha self.lam = lam self.entries: List[MemEntry] = [] self._dirty = True def add(self, entry: MemEntry): self.entries.append(entry) self._dirty = True def _rebuild(self): if self._dirty and self.entries: self._emb_matrix = np.stack([e.embedding for e in self.entries]) norms = np.linalg.norm(self._emb_matrix, axis=1, keepdims=True) self._emb_normed = self._emb_matrix / np.maximum(norms, 1e-10) self._timestamps = np.array([e.timestamp for e in self.entries]) self._dirty = False def _cosine(self, qe): self._rebuild() q = qe / max(np.linalg.norm(qe), 1e-10) return self._emb_normed @ q def is_temporal(self, text): q = text.lower() for kw in self.TEMPORAL_KEYWORDS: if re.search(r'\b' + re.escape(kw) + r'\b', q): return True for phrase in self.TEMPORAL_PHRASES: if phrase in q: return True return False def query_cosine(self, qe, top_k=5): sims = self._cosine(qe) idx = np.argsort(sims)[::-1][:top_k] return [(self.entries[i], float(sims[i]), 1.0) for i in idx] def query_hybrid(self, qe, query_time, query_text, selector, shortlist=10, top_k=5): sims = self._cosine(qe) if self.is_temporal(query_text): dt = np.maximum(query_time - self._timestamps, 0.01) temporal = selector(dt) sl_idx = np.argsort(sims)[::-1][:shortlist] scores = sims[sl_idx] * temporal[sl_idx] reranked = sl_idx[np.argsort(scores)[::-1][:top_k]] return [(self.entries[i], float(sims[i]), float(temporal[i]), "temporal") for i in reranked] else: idx = np.argsort(sims)[::-1][:top_k] return [(self.entries[i], float(sims[i]), 1.0, "static") for i in idx] # ═══════════════════════════════════════════════════════════════════ # HF Inference API # ═══════════════════════════════════════════════════════════════════ HF_TOKEN = os.environ.get("HF_TOKEN", "") EMBED_MODEL = "nomic-ai/nomic-embed-text-v1.5" EMBED_API = f"https://router.huggingface.co/hf-inference/pipeline/feature-extraction/{EMBED_MODEL}" def embed_text_hf(text): if not HF_TOKEN: return None try: resp = requests.post( EMBED_API, headers={"Authorization": f"Bearer {HF_TOKEN}"}, json={"inputs": text}, timeout=30) resp.raise_for_status() data = resp.json() if isinstance(data, list) and len(data) > 0: vec = data[0] if isinstance(data[0], list) else data return np.array(vec, dtype=np.float32) except Exception as e: print(f"HF embed error: {e}") return None # ═══════════════════════════════════════════════════════════════════ # Load Data # ═══════════════════════════════════════════════════════════════════ def load_baked(): data = np.load("embeddings.npz", allow_pickle=True) store = MemoryStore(alpha=0.6, lam=0.05) for i in range(len(data["fact_texts"])): store.add(MemEntry( text=str(data["fact_texts"][i]), value=str(data["fact_values"][i]), category=str(data["fact_categories"][i]), embedding=data["fact_embeddings"][i], timestamp=float(data["fact_months"][i]), )) q_lookup = {} q_texts = [str(x) for x in data["q_texts"]] for i, qt in enumerate(q_texts): q_lookup[qt] = data["q_embeddings"][i] q_correct = {str(data["q_texts"][i]): str(data["q_correct"][i]) for i in range(len(q_texts))} return store, q_lookup, q_correct print("Loading embeddings...") STORE, Q_LOOKUP, Q_CORRECT = load_baked() QUERY_TIME = 25.0 print(f"Loaded {len(STORE.entries)} facts.") # ═══════════════════════════════════════════════════════════════════ # Temporal Selectors # Each maps Δt (months) → a non-increasing temporal weight. # These are reranking kernels applied to the cosine shortlist. # ═══════════════════════════════════════════════════════════════════ SELECTORS = { "Fractional / Mittag-Leffler": lambda dt: STORE.ml(0.05 * np.maximum(dt, 0.01) ** 0.6), "EWMA": lambda dt: np.exp(-0.03 * np.maximum(dt, 0.0)), "Power-law": lambda dt: (1.0 + 0.05 * np.maximum(dt, 0.0)) ** -0.6, } SELECTOR_NAMES = list(SELECTORS.keys()) DEFAULT_SELECTOR = "Fractional / Mittag-Leffler" # ═══════════════════════════════════════════════════════════════════ # Query Logic # ═══════════════════════════════════════════════════════════════════ def get_embedding(question): if question in Q_LOOKUP: return Q_LOOKUP[question] return embed_text_hf(question) def query_memory(question, selector_name=DEFAULT_SELECTOR): if not question.strip(): return "", "", "" qe = get_embedding(question) if qe is None: return ("Could not embed this query. Try one of the examples below, " "or set HF_TOKEN in Space secrets for custom queries."), "", "" selector = SELECTORS.get(selector_name, SELECTORS[DEFAULT_SELECTOR]) short_name = selector_name.split(" / ")[0] is_temporal = STORE.is_temporal(question) rag = STORE.query_cosine(qe, top_k=3) hyb = STORE.query_hybrid(qe, QUERY_TIME, question, selector, shortlist=10, top_k=3) rag_answer = rag[0][0].value hyb_answer = hyb[0][0].value ground_truth = Q_CORRECT.get(question, None) if rag_answer == hyb_answer: verdict = f"Both return **{hyb_answer}**" else: verdict = f"RAG: **{rag_answer}** → {short_name}: **{hyb_answer}**" if ground_truth: rag_ok = "correct" if rag_answer == ground_truth else "wrong" hyb_ok = "correct" if hyb_answer == ground_truth else "wrong" verdict += (f"\n\nGround truth: **{ground_truth}** · " f"RAG {rag_ok} · {short_name} {hyb_ok}") if is_temporal: route = f"temporal → cosine shortlist → {short_name} rerank" else: route = "static → cosine only (no temporal rerank)" verdict += f"\n\nRoute: `{route}`" def fmt_rag(e, cos, rank): check = "" if ground_truth: check = " ✓" if e.value == ground_truth else " ✗" return (f"**{rank}.** **{e.value}**{check} \n" f"month {int(e.timestamp)} · `cos = {cos:.3f}` \n" f"*{e.text}*\n\n") def fmt_hyb(e, cos, tw, route, rank): check = "" if ground_truth: check = " ✓" if e.value == ground_truth else " ✗" kernel_str = f" × w = {tw:.3f}" if route == "temporal" else "" return (f"**{rank}.** **{e.value}**{check} \n" f"month {int(e.timestamp)} · `cos = {cos:.3f}{kernel_str}` \n" f"*{e.text}*\n\n") rag_md = "" for i, (e, c, t) in enumerate(rag[:3]): rag_md += fmt_rag(e, c, i+1) hyb_md = "" for i, (e, c, t, r) in enumerate(hyb[:3]): hyb_md += fmt_hyb(e, c, t, r, i+1) return verdict, rag_md, hyb_md # ═══════════════════════════════════════════════════════════════════ # CSS # ═══════════════════════════════════════════════════════════════════ CSS = """ @import url('https://fonts.googleapis.com/css2?family=EB+Garamond:ital,wght@0,400;0,500;0,600;1,400&family=JetBrains+Mono:wght@400;500&display=swap'); /* Force light color scheme even when the user's OS is in dark mode. Gradio's Base theme reacts to prefers-color-scheme and toggles a .dark class, which would otherwise leave us with black text on dark gray. */ :root, html, body { color-scheme: light only !important; } .gradio-container { max-width: 960px !important; font-family: 'EB Garamond', Georgia, serif !important; background: #fafaf8 !important; color: #1a1a1a !important; line-height: 1.55; /* Override Gradio theme tokens so prose doesn't default to a faint gray and inputs/blocks don't sit on a dark surface */ --body-text-color: #1a1a1a !important; --body-text-color-subdued: #444 !important; --block-info-text-color: #444 !important; --block-label-text-color: #1a1a1a !important; --block-title-text-color: #1a1a1a !important; --block-background-fill: #fafaf8 !important; --block-label-background-fill: #fafaf8 !important; --input-background-fill: #ffffff !important; --background-fill-primary: #fafaf8 !important; --background-fill-secondary: #ffffff !important; } /* Form inputs: white surface, sane line-height, 16px to avoid iOS zoom and avoid Safari clipping the placeholder mid-letter */ .gradio-container input[type="text"], .gradio-container input[type="search"], .gradio-container textarea { background: #ffffff !important; color: #1a1a1a !important; font-family: 'EB Garamond', Georgia, serif !important; font-size: 16px !important; font-weight: 400 !important; line-height: 1.4 !important; } .gradio-container ::placeholder { color: #888 !important; opacity: 1 !important; font-style: italic; } .gradio-container p, .gradio-container li, .gradio-container span, .gradio-container .prose, .gradio-container .prose p, .gradio-container .prose li, .gradio-container .prose strong, .gradio-container .markdown, .gradio-container .markdown p, .gradio-container .markdown li { color: #1a1a1a !important; } h1, h2, h3, h4 { font-family: 'EB Garamond', Georgia, serif !important; font-weight: 600 !important; line-height: 1.25; color: #1a1a1a !important; } code, pre { font-family: 'JetBrains Mono', monospace !important; background: #f0f0ea; border-radius: 3px; white-space: pre-wrap; word-break: break-word; overflow-wrap: anywhere; } code { font-size: 0.9em; padding: 1px 5px; } .verdict-box { border-left: 3px solid #1a1a1a; padding: 12px 16px; margin: 8px 0; background: #f5f5f0; } .result-col { border: 1px solid #ddd; border-radius: 4px; padding: 16px; background: #fff; } button.primary { background: #1a1a1a !important; color: #fafafa !important; font-family: 'EB Garamond', Georgia, serif !important; font-size: 1.05em !important; } button.primary:hover { background: #333 !important; } .tab-nav button { font-family: 'EB Garamond', Georgia, serif !important; font-size: 1.05em !important; } /* ── Mobile readability ── */ @media (max-width: 700px) { .gradio-container { font-size: 17px !important; padding: 0 12px !important; line-height: 1.6 !important; } .gradio-container p, .gradio-container li, .gradio-container .prose, .gradio-container .prose p, .gradio-container .prose li, .gradio-container .markdown, .gradio-container .markdown p, .gradio-container .markdown li { font-size: 17px !important; line-height: 1.6 !important; font-weight: 500 !important; color: #1a1a1a !important; } .gradio-container h1 { font-size: 1.6em !important; } .gradio-container h2 { font-size: 1.3em !important; } .gradio-container h3 { font-size: 1.1em !important; } .result-col { flex: 1 1 100% !important; min-width: 100% !important; padding: 12px !important; } .verdict-box { padding: 10px 12px !important; } code { font-size: 0.95em !important; } table { font-size: 15px !important; } .gradio-container a { color: #333 !important; } /* Stack the Question textbox and Ask button so the placeholder has full width and isn't truncated on iPhone */ .ask-row { flex-direction: column !important; gap: 8px !important; } .ask-row > * { width: 100% !important; min-width: 100% !important; flex: 1 1 100% !important; } .gradio-container input[type="text"], .gradio-container input[type="search"] { width: 100% !important; } } /* ── Dark-mode override: re-pin everything to the light palette ── Gradio applies a .dark class on html/body when the system is in dark mode. Without these rules, our text stays #1a1a1a but Gradio's surfaces flip to near-black, producing low contrast on iOS. */ .dark .gradio-container, .gradio-container.dark, html.dark .gradio-container, body.dark .gradio-container { background: #fafaf8 !important; color: #1a1a1a !important; --body-text-color: #1a1a1a !important; --body-text-color-subdued: #444 !important; --block-info-text-color: #444 !important; --block-label-text-color: #1a1a1a !important; --block-title-text-color: #1a1a1a !important; --block-background-fill: #fafaf8 !important; --block-label-background-fill: #fafaf8 !important; --input-background-fill: #ffffff !important; --background-fill-primary: #fafaf8 !important; --background-fill-secondary: #ffffff !important; --panel-background-fill: #fafaf8 !important; --neutral-50: #fafaf8 !important; --neutral-100: #f5f5f0 !important; --neutral-200: #f0f0ea !important; --neutral-300: #e0e0d8 !important; /* Radio / checkbox pill surfaces. Keep every state on a white background and indicate selection via a dark border + native accent color, so iOS can't darken the surrounding box. */ --checkbox-background-fill: #ffffff !important; --checkbox-background-fill-hover: #ffffff !important; --checkbox-background-fill-selected: #ffffff !important; --checkbox-label-background-fill: #ffffff !important; --checkbox-label-background-fill-hover: #f5f5f0 !important; --checkbox-label-background-fill-selected: #ffffff !important; --checkbox-label-text-color: #1a1a1a !important; --checkbox-label-text-color-selected: #1a1a1a !important; --checkbox-border-color: #ddd !important; --checkbox-border-color-hover: #999 !important; --checkbox-border-color-selected: #1a1a1a !important; /* Secondary buttons (Gradio also uses these for radio chips in some builds) */ --button-secondary-background-fill: #ffffff !important; --button-secondary-background-fill-hover: #f5f5f0 !important; --button-secondary-text-color: #1a1a1a !important; --button-secondary-text-color-hover: #1a1a1a !important; --button-secondary-border-color: #ddd !important; } /* Direct selector fallback for the radio chips (white surface, dark text). Avoid :has() — on iOS it can match a parent label that wraps all options and darken the whole group. */ .dark .gradio-container [data-testid="radio"] label, .dark .gradio-container fieldset label, .dark .gradio-container [class*="radio"] label, .dark .gradio-container [class*="radio"] span { background: #ffffff !important; color: #1a1a1a !important; border-color: #ddd !important; } /* Native input + sibling-span pattern only — cannot accidentally match a wrapping label */ .dark .gradio-container input[type="radio"]:checked + span { color: #1a1a1a !important; font-weight: 600 !important; } .dark .gradio-container input[type="radio"], .dark .gradio-container input[type="checkbox"] { accent-color: #1a1a1a !important; } .dark .gradio-container p, .dark .gradio-container li, .dark .gradio-container span, .dark .gradio-container .prose, .dark .gradio-container .prose p, .dark .gradio-container .prose li, .dark .gradio-container .prose strong, .dark .gradio-container .markdown, .dark .gradio-container .markdown p, .dark .gradio-container .markdown li, .dark .gradio-container h1, .dark .gradio-container h2, .dark .gradio-container h3, .dark .gradio-container h4 { color: #1a1a1a !important; } .dark .verdict-box { background: #f5f5f0 !important; color: #1a1a1a !important; border-left-color: #1a1a1a !important; } .dark .result-col { background: #ffffff !important; color: #1a1a1a !important; border-color: #ddd !important; } .dark code, .dark pre { background: #f0f0ea !important; color: #1a1a1a !important; } .dark .gradio-container input[type="text"], .dark .gradio-container input[type="search"], .dark .gradio-container textarea { background: #ffffff !important; color: #1a1a1a !important; } """ TEMPORAL_EXAMPLES = [ "What is Alex's current salary?", "Where does Alex live now?", "What is Alex's current job title?", "Where does Alex work now?", "Who does Alex report to now?", "What is Alex working on now?", "How big is Alex's current team?", "What phone does Alex use now?", "What exercise does Alex do now?", "What is Alex's favorite restaurant now?", "What is Alex reading now?", "How does Alex get to work now?", ] STATIC_EXAMPLES = [ "Did Alex ever win a hackathon?", "Does Alex have a dog?", "Where did Alex go to school?", "Does Alex play guitar?", "Has Alex given a keynote?", "Is Alex vegetarian?", "What is Alex's favorite band?", "Does Alex have siblings?", ] # ═══════════════════════════════════════════════════════════════════ # App # ═══════════════════════════════════════════════════════════════════ with gr.Blocks(title="Fractional Memory — Quijotic Research") as app: gr.HTML("""

Fractional Memory for Language Models

Keep every fact. Score by relevance and by age relative to the query.
Companion to “Temporal Memory for Language Models” · Quijotic Research LLC · quijotic.com · GitHub

""") with gr.Tabs(): with gr.Tab("Query"): gr.Markdown( "Ask about Alex's life across 24 months — 121 facts, " "16 evolving categories. Many attributes (salary, role, team size) " "have several entries that compete for the same query; the " "temporal selector decides which one wins." ) with gr.Row(elem_classes=["ask-row"]): question_input = gr.Textbox(label="Question", placeholder="What is Alex's current salary?", scale=4) query_btn = gr.Button("Ask", variant="primary", scale=1) selector_radio = gr.Radio( choices=SELECTOR_NAMES, value=DEFAULT_SELECTOR, label="Temporal selector", info="Reranking kernel applied to the cosine shortlist on temporal queries.", ) verdict_box = gr.Markdown(elem_classes=["verdict-box"]) with gr.Row(): with gr.Column(elem_classes=["result-col"]): gr.Markdown("#### Vanilla RAG") rag_output = gr.Markdown() with gr.Column(elem_classes=["result-col"]): gr.Markdown("#### Temporal selector") frac_output = gr.Markdown() gr.Markdown( "---\n**Temporal queries** — competing facts about the same attribute; " "the selector picks by query intent:" ) gr.Examples(examples=[[q] for q in TEMPORAL_EXAMPLES], inputs=[question_input], label="") gr.Markdown( "**Static queries** — one true answer; the router skips the rerank " "so cosine accuracy is preserved:" ) gr.Examples(examples=[[q] for q in STATIC_EXAMPLES], inputs=[question_input], label="") gr.Markdown( "---\n*Beyond this demo: the full paper evaluates this using " "synthetic parameter surfaces, dense EWMA, MiniLM retrieval, " "matched-scale calibration, contrastive TempLAMA-style facts, " "and a structured frozen-decoder check.*" ) query_btn.click(fn=query_memory, inputs=[question_input, selector_radio], outputs=[verdict_box, rag_output, frac_output]) question_input.submit(fn=query_memory, inputs=[question_input, selector_radio], outputs=[verdict_box, rag_output, frac_output]) selector_radio.change(fn=query_memory, inputs=[question_input, selector_radio], outputs=[verdict_box, rag_output, frac_output]) with gr.Tab("Architecture"): gr.Markdown(""" ## Normalize → Route → Rerank **Normalize.** Facts are embedded using query-aligned templates so that every salary entry — past or current — embeds as *"Alex's salary is $X per year."* This deliberately collapses cosine: competing facts about the same attribute end up near each other, and the temporal selector has to decide which one wins. **Route.** Temporal queries (*current*, *now*, *latest*, …) take the rerank. Static queries (*did Alex ever …*, *where did Alex go to school*) skip it and fall through to cosine alone. The router exists so we don't pay a recency penalty when there isn't one to pay. **Rerank.** Top-10 by cosine, then rerank by `cos × w(Δt)` where `w` is the chosen temporal selector. --- ## Temporal selectors The demo exposes three. They are different shapes; pick one with the radio on the Query tab. | Selector | Form | Notes | |---|---|---| | **EWMA** | `exp(−λ Δt)` | The deployed baseline (e.g. LangChain's time-weighted retriever). Drops fast; light tail. | | **Power-law** | `(1 + λ Δt)^(−β)` | A simple long-memory option. Robust fallback in the paper's sweeps. | | **Fractional / Mittag-Leffler** | `E_α(−λ Δt^α)` | Power-law tail with a controlled short-time response. One selector among several tested. | Retaining facts is not enough — a memory system also needs an explicit temporal selection policy. The paper compares these (and a few more) head-to-head; no single selector dominates everywhere, but the architecture itself is the larger effect. --- ## On this small demo | | Temporal | Static | Overall | |---|:---:|:---:|:---:| | Vanilla RAG | 19.3% | 83.3% | 41.4% | | Vanilla RAG + temporal rerank | **66.7%** | **83.3%** | **72.4%** | Numbers are for the 24-month synthetic biography in this Space; the architecture contribution dominates the kernel-choice contribution at this size. *The full paper evaluates this beyond the toy demo using synthetic parameter surfaces, dense EWMA, MiniLM retrieval, matched-scale calibration, contrastive TempLAMA-style facts, and a structured frozen-decoder check.* """) with gr.Tab("Papers"): gr.Markdown(""" ## The Operator Derivative Program *D = δ\\** — defined by duality with the stochastic integral. --- **I.** The Operator Derivative in Continuous Stochastic Calculus · [Zenodo](https://doi.org/10.5281/zenodo.18624822) · [Lean 4](https://github.com/QuijoticResearch/operator-derivative-lean) **II.** Operator Factorization Beyond Hilbert Spaces · [Zenodo](https://doi.org/10.5281/zenodo.18625711) · [Lean 4](https://github.com/QuijoticResearch/banach-levy-lean) **III.** The Boundary of Hedgeability · [Zenodo](https://doi.org/10.5281/zenodo.19211991) · [Lean 4](https://github.com/QuijoticResearch/volterra-levy) **IV.** Fractional Memory for Attention-Based Systems · Zenodo forthcoming **Temporal Memory for Language Models** — *companion to this demo* --- *Quijotic Research LLC · Ramiro Fontes · New York* """) gr.HTML("""
© 2026 Quijotic Research LLC · quijotic.com
""") app.launch(css=CSS, theme=gr.themes.Base())