Upload phase_s_scale.py with huggingface_hub
Browse files- phase_s_scale.py +133 -0
phase_s_scale.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Phase S — Scaling: large synthetic corpora + hippocampal consolidation gate
|
| 3 |
+
+ accuracy-at-scale harness.
|
| 4 |
+
|
| 5 |
+
• make_scaled_corpus(n) : n fact entries (EN + AR + hard distractors)
|
| 6 |
+
• make_eval_pairs(...) : held-out paraphrase queries (unseen views/wordings)
|
| 7 |
+
• ConsolidationGate : duplicate/near-duplicate detection before write
|
| 8 |
+
(prevents memory pollution — real hippocampus
|
| 9 |
+
consolidates before permanent storage)
|
| 10 |
+
"""
|
| 11 |
+
import random
|
| 12 |
+
import re
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
from phase_c_augment import augment
|
| 17 |
+
|
| 18 |
+
TOPICS_EN = ["geography", "history", "science", "music", "sports", "cooking",
|
| 19 |
+
"astronomy", "biology", "physics", "cities", "rivers", "mountains",
|
| 20 |
+
"oceans", "planets", "animals", "plants", "languages", "economies"]
|
| 21 |
+
TOPICS_AR = ["جغرافيا", "تاريخ", "علوم", "موسيقى", "رياضة", "طبخ",
|
| 22 |
+
"فلك", "أحياء", "فيزياء", "مدن", "أنهار", "جبال",
|
| 23 |
+
"محيطات", "كواكب", "حيوانات", "نباتات", "لغات", "اقتصاد"]
|
| 24 |
+
|
| 25 |
+
# novel-wording templates (NEVER stored — used only for evaluation)
|
| 26 |
+
TEMPLATES_NOVEL = [
|
| 27 |
+
("Tell me about fact {i} of {t}", "fact {i} about {t}"),
|
| 28 |
+
("I want to know fact {i} regarding {t}", "fact {i} about {t}"),
|
| 29 |
+
("Could you remind me of fact {i} in {t}?", "fact {i} about {t}"),
|
| 30 |
+
("اعرض لي الحقيقة {i} بخصوص {t}", "الحقيقة {i} حول {t}"),
|
| 31 |
+
("ممكن تقول الحقيقة رقم {i} في {t}؟", "القيقة {i} حول {t}"),
|
| 32 |
+
]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def make_scaled_corpus(n, seed=0, hard_ratio=0.3):
|
| 36 |
+
"""n entries: EN facts + AR facts + hard distractors (shared template words,
|
| 37 |
+
different values) — the honest stress for lexical confusion."""
|
| 38 |
+
rng = random.Random(seed)
|
| 39 |
+
out = []
|
| 40 |
+
for i in range(n):
|
| 41 |
+
kind = i % 3
|
| 42 |
+
if kind == 0:
|
| 43 |
+
t = TOPICS_EN[i % len(TOPICS_EN)]
|
| 44 |
+
v = rng.randint(1, 999)
|
| 45 |
+
out.append({"prompt": f"What is fact number {i} about {t}?",
|
| 46 |
+
"response": f"Fact {i}: the {t} value is {v}.",
|
| 47 |
+
"domain": "scale-en"})
|
| 48 |
+
elif kind == 1:
|
| 49 |
+
t = TOPICS_AR[i % len(TOPICS_AR)]
|
| 50 |
+
v = rng.randint(1, 999)
|
| 51 |
+
out.append({"prompt": f"ما هي الحقيقة رقم {i} حول {t}؟",
|
| 52 |
+
"response": f"الحقيقة {i}: قيمة {t} هي {v}.",
|
| 53 |
+
"domain": "scale-ar"})
|
| 54 |
+
else:
|
| 55 |
+
# hard distractor pair: same template vocabulary, unique id slot
|
| 56 |
+
t = TOPICS_EN[(i // 2) % len(TOPICS_EN)]
|
| 57 |
+
v = rng.randint(1, 999)
|
| 58 |
+
out.append({"prompt": f"Give me the fact {i} about the {t} value",
|
| 59 |
+
"response": f"Sure — fact {i} gives {t} = {v}.",
|
| 60 |
+
"domain": "scale-hard"})
|
| 61 |
+
return out
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def make_eval_pairs(corpus, n_q=2000, seed=1):
|
| 65 |
+
"""Held-out queries: (query, target_prompt).
|
| 66 |
+
50% augmented views (unseen noise) + 50% novel wording templates."""
|
| 67 |
+
rng = random.Random(seed)
|
| 68 |
+
nrs = np.random.RandomState(seed)
|
| 69 |
+
idx = rng.sample(range(len(corpus)), min(n_q, len(corpus)))
|
| 70 |
+
pairs = []
|
| 71 |
+
for k, i in enumerate(idx):
|
| 72 |
+
p = corpus[i]["prompt"]
|
| 73 |
+
if k % 2 == 0:
|
| 74 |
+
pairs.append((augment(p, nrs), p))
|
| 75 |
+
else:
|
| 76 |
+
m = re.search(r"(\d+)", p)
|
| 77 |
+
num = m.group(1) if m else str(i)
|
| 78 |
+
m2 = (re.search(r"about (?:the )?(\w+)", p) or
|
| 79 |
+
re.search(r"حول (\w+)", p) or
|
| 80 |
+
re.search(r"the (\w+) value", p))
|
| 81 |
+
topic = m2.group(1) if m2 else "topic"
|
| 82 |
+
tpl_q, _ = TEMPLATES_NOVEL[k % len(TEMPLATES_NOVEL)]
|
| 83 |
+
q = tpl_q.format(i=num, t=topic)
|
| 84 |
+
pairs.append((q, p))
|
| 85 |
+
return pairs
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class ConsolidationGate:
|
| 89 |
+
"""Hippocampal gate with PATTERN SEPARATION (two-factor rule):
|
| 90 |
+
duplicate ⇔ semantic cosine ≥ θ AND slot-signature match
|
| 91 |
+
(slot signature = the set of numbers/values in the prompt).
|
| 92 |
+
|
| 93 |
+
Why: bag-of-ngrams embeddings cannot tell 'fact 42' from 'fact 43'
|
| 94 |
+
(cosine ≈ 0.95+) — the signature factor keeps template siblings
|
| 95 |
+
(genuinely different facts) while merging true paraphrases, exactly
|
| 96 |
+
like hippocampal pattern separation. Signature index => O(1) lookup."""
|
| 97 |
+
|
| 98 |
+
def __init__(self, encoder, threshold=0.7):
|
| 99 |
+
self.enc = encoder
|
| 100 |
+
self.threshold = threshold
|
| 101 |
+
self._index = {}
|
| 102 |
+
self._n = 0
|
| 103 |
+
|
| 104 |
+
@staticmethod
|
| 105 |
+
def slot_sig(text):
|
| 106 |
+
return frozenset(re.findall(r"\d+", text))
|
| 107 |
+
|
| 108 |
+
def _sync(self, memory):
|
| 109 |
+
for j in range(self._n, len(memory.entries)):
|
| 110 |
+
sig = self.slot_sig(memory.entries[j]["prompt"])
|
| 111 |
+
self._index.setdefault(sig, []).append(j)
|
| 112 |
+
self._n = len(memory.entries)
|
| 113 |
+
|
| 114 |
+
def check(self, memory, prompt):
|
| 115 |
+
self._sync(memory)
|
| 116 |
+
sig = self.slot_sig(prompt)
|
| 117 |
+
cands = self._index.get(sig, [])
|
| 118 |
+
if not cands:
|
| 119 |
+
return {"is_new": True, "score": 0.0, "nearest": None}
|
| 120 |
+
e = self.enc.encode(prompt)
|
| 121 |
+
M = np.stack([memory.codes[j] for j in cands])
|
| 122 |
+
scores = M @ e
|
| 123 |
+
k = int(np.argmax(scores))
|
| 124 |
+
s = float(scores[k])
|
| 125 |
+
return {"is_new": bool(s < self.threshold), "score": s,
|
| 126 |
+
"nearest": memory.entries[cands[k]]["prompt"] if s >= self.threshold else None}
|
| 127 |
+
|
| 128 |
+
def ingest(self, memory, entry):
|
| 129 |
+
"""Write only if the gate accepts; returns the gate decision."""
|
| 130 |
+
d = self.check(memory, entry["prompt"])
|
| 131 |
+
if d["is_new"]:
|
| 132 |
+
memory.write(entry)
|
| 133 |
+
return d
|