empty repo for clean single-source upload
Browse files- phase_p2_slot.py +0 -177
phase_p2_slot.py
DELETED
|
@@ -1,177 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
PHASE P2 — Slot-aware encoder training (التدريب المُدرِّك للخرائط/الفتحات).
|
| 3 |
-
Why Phase-P1 retrieval was weak: the encoder never saw SIBLING pairs during
|
| 4 |
-
training ("fact 42 about rivers" vs "fact 43 about rivers"), so number slots
|
| 5 |
-
got no gradient and novel wordings diluted the shared signal.
|
| 6 |
-
|
| 7 |
-
Three mechanisms (all NumPy):
|
| 8 |
-
1. Slot-aware featurizer: numeric tokens get dedicated `N:` features (2x weight)
|
| 9 |
-
so digits are not drowned by shared scaffolding n-grams.
|
| 10 |
-
2. HARD NEGATIVE siblings inside InfoNCE: every anchor carries a guaranteed
|
| 11 |
-
same-template/different-number negative column (pattern separation pressure
|
| 12 |
-
at the ENCODER level, not only at the gate).
|
| 13 |
-
3. Novel-wording positives: 50% of positives are re-renderings under unseen
|
| 14 |
-
templates (TEMPLATES_NOVEL) — trains scaffold invariance directly.
|
| 15 |
-
|
| 16 |
-
Anatomy: dentate gyrus adult neurogenesis = separating similar patterns while
|
| 17 |
-
CA3/completion keeps gist; the sibling negatives ARE the separation pressure.
|
| 18 |
-
"""
|
| 19 |
-
import re
|
| 20 |
-
import random
|
| 21 |
-
import numpy as np
|
| 22 |
-
|
| 23 |
-
from phase_c_encoder import TrainableEncoder, hashed_features
|
| 24 |
-
from phase_c_augment import augment
|
| 25 |
-
from phase_d_bilingual import make_pairs
|
| 26 |
-
from phase_s_scale import TEMPLATES_NOVEL, make_scaled_corpus
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
# ------------------------------------------------------------- featurizer v2
|
| 30 |
-
def hashed_features_slot(text, F=2 ** 15):
|
| 31 |
-
"""hashed_features + dedicated numeric-slot features (`N:<token>` x2)."""
|
| 32 |
-
idx, val = hashed_features(text, F)
|
| 33 |
-
toks = re.findall(r"\d+", text)
|
| 34 |
-
if not toks:
|
| 35 |
-
return idx, val
|
| 36 |
-
acc = {}
|
| 37 |
-
for i, v in zip(idx, val):
|
| 38 |
-
acc[int(i)] = acc.get(int(i), 0.0) + float(v)
|
| 39 |
-
for t in toks:
|
| 40 |
-
for rep in (0, 1): # x2 weight for number slots
|
| 41 |
-
f = f"N:{t}#{rep}"
|
| 42 |
-
h = int(__import__("hashlib").md5(f.encode()).hexdigest()[:8], 16)
|
| 43 |
-
i = h % F
|
| 44 |
-
s = 1.0 if (h >> 16) & 1 else -1.0
|
| 45 |
-
acc[i] = acc.get(i, 0.0) + s
|
| 46 |
-
idx2 = np.array([i for i, v in acc.items() if v != 0], dtype=np.int64)
|
| 47 |
-
val2 = np.array([v for v in acc.values() if v != 0], dtype=np.float32)
|
| 48 |
-
return idx2, val2
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
# ------------------------------------------------------------- slot tools
|
| 52 |
-
def make_sibling(text, rng):
|
| 53 |
-
"""Same prompt, different slot value — the hard negative the encoder never saw."""
|
| 54 |
-
def repl(m):
|
| 55 |
-
n = int(m.group(0))
|
| 56 |
-
return str(n + rng.randint(100, 9000))
|
| 57 |
-
return re.sub(r"\d+", repl, text)
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
def novel_view(text, rng, templates=None):
|
| 61 |
-
"""Re-render the SAME fact under an unseen template (novel-wording positive).
|
| 62 |
-
`templates` lets tests hold out phrasings the trainer never sees."""
|
| 63 |
-
T = templates or TEMPLATES_NOVEL
|
| 64 |
-
m = re.search(r"(\d+)", text)
|
| 65 |
-
if not m:
|
| 66 |
-
return augment(text, rng)
|
| 67 |
-
num = m.group(1)
|
| 68 |
-
m2 = (re.search(r"about (?:the )?(\w+)", text) or
|
| 69 |
-
re.search(r"حول (\w+)", text) or
|
| 70 |
-
re.search(r"the (\w+) value", text))
|
| 71 |
-
if not m2:
|
| 72 |
-
return augment(text, rng)
|
| 73 |
-
topic = m2.group(1)
|
| 74 |
-
tpl_q, _ = T[rng.randint(0, len(T))]
|
| 75 |
-
try:
|
| 76 |
-
return tpl_q.format(i=num, t=topic)
|
| 77 |
-
except Exception:
|
| 78 |
-
return augment(text, rng)
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
# ------------------------------------------------------------- slot-aware InfoNCE
|
| 82 |
-
def train_slot_aware(enc, pool, steps=1200, batch=24, lr=0.03, seed=5, log_every=300,
|
| 83 |
-
templates=None):
|
| 84 |
-
"""InfoNCE with B x (B+1) scores: columns = [in-batch positives | sibling].
|
| 85 |
-
Positive = augment OR novel_view; sibling = make_sibling (hard negative)."""
|
| 86 |
-
rng = np.random.RandomState(seed)
|
| 87 |
-
losses = []
|
| 88 |
-
for step in range(steps):
|
| 89 |
-
picks = rng.randint(0, len(pool), batch)
|
| 90 |
-
bases = [pool[i] for i in picks]
|
| 91 |
-
anchors, posits, sibs = [], [], []
|
| 92 |
-
for t in bases:
|
| 93 |
-
anchors.append(t if rng.rand() < 0.5 else augment(t, rng))
|
| 94 |
-
posits.append(augment(t, rng) if rng.rand() < 0.5 else novel_view(t, rng, templates))
|
| 95 |
-
sibs.append(make_sibling(t, rng))
|
| 96 |
-
|
| 97 |
-
def feats(texts):
|
| 98 |
-
return [enc.feat(t, enc.F) for t in texts]
|
| 99 |
-
|
| 100 |
-
def fwd(feats_):
|
| 101 |
-
Z = np.zeros((batch, enc.d), dtype=np.float32)
|
| 102 |
-
for r, (idx, val) in enumerate(feats_):
|
| 103 |
-
if len(idx):
|
| 104 |
-
Z[r] = val @ enc.W[idx]
|
| 105 |
-
norms = np.linalg.norm(Z, axis=1, keepdims=True)
|
| 106 |
-
return Z / np.maximum(norms, 1e-8), norms
|
| 107 |
-
|
| 108 |
-
fa, fp, fs = feats(anchors), feats(posits), feats(sibs)
|
| 109 |
-
Ea, na = fwd(fa)
|
| 110 |
-
Ep, npp = fwd(fp)
|
| 111 |
-
Es, ns = fwd(fs)
|
| 112 |
-
|
| 113 |
-
S_pos = (Ea @ Ep.T) / enc.tau # BxB
|
| 114 |
-
S_sib = np.sum(Ea * Es, axis=1, keepdims=True) / enc.tau # Bx1
|
| 115 |
-
S = np.concatenate([S_pos, S_sib], axis=1) # Bx(B+1)
|
| 116 |
-
S -= S.max(axis=1, keepdims=True)
|
| 117 |
-
P = np.exp(S)
|
| 118 |
-
P /= P.sum(axis=1, keepdims=True)
|
| 119 |
-
tgt = P[np.arange(batch), np.arange(batch)]
|
| 120 |
-
loss = -float(np.mean(np.log(np.maximum(tgt, 1e-12))))
|
| 121 |
-
losses.append(loss)
|
| 122 |
-
|
| 123 |
-
dS = P.copy()
|
| 124 |
-
dS[np.arange(batch), np.arange(batch)] -= 1.0
|
| 125 |
-
dS /= batch
|
| 126 |
-
dS_pos, dS_sib = dS[:, :batch], dS[:, batch:] # BxB, Bx1
|
| 127 |
-
dEa = (dS_pos @ Ep + dS_sib * Es) / enc.tau
|
| 128 |
-
dEp = (dS_pos.T @ Ea) / enc.tau
|
| 129 |
-
dEs = (dS_sib * Ea) / enc.tau
|
| 130 |
-
|
| 131 |
-
def bwd(feats_, E, norms, dE):
|
| 132 |
-
dots = np.sum(E * dE, axis=1, keepdims=True)
|
| 133 |
-
dZ = (dE - E * dots) / np.maximum(norms, 1e-8)
|
| 134 |
-
for r, (idx, val) in enumerate(feats_):
|
| 135 |
-
if len(idx):
|
| 136 |
-
enc.W[idx] -= lr * np.outer(val.astype(np.float32), dZ[r]).astype(np.float32)
|
| 137 |
-
|
| 138 |
-
bwd(fa, Ea, na, dEa)
|
| 139 |
-
bwd(fp, Ep, npp, dEp)
|
| 140 |
-
bwd(fs, Es, ns, dEs)
|
| 141 |
-
if log_every and (step + 1) % log_every == 0:
|
| 142 |
-
lr *= 0.9
|
| 143 |
-
return {"loss_first": float(np.mean(losses[:50])),
|
| 144 |
-
"loss_last": float(np.mean(losses[-50:])), "steps": steps}
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
# ------------------------------------------------------------- full curriculum
|
| 148 |
-
def load_slot(path):
|
| 149 |
-
"""Load a P2 artifact WITH its slot-aware featurizer (W was trained on it)."""
|
| 150 |
-
z = np.load(path)
|
| 151 |
-
enc = TrainableEncoder(F=int(z["F"]), d=int(z["d"]), tau=float(z["tau"]),
|
| 152 |
-
W=z["W"], features_fn=hashed_features_slot)
|
| 153 |
-
return enc
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
def build_p2_encoder(kb, out_path="phase_p2_W.npz", quick=False, templates=None):
|
| 157 |
-
"""Phase-D recipe on the KB (preserve what works) + stage-2 slot-aware
|
| 158 |
-
training on a sibling-rich pool. Returns the trained encoder."""
|
| 159 |
-
prompts = [e["prompt"] for e in kb]
|
| 160 |
-
pairs = make_pairs(kb)
|
| 161 |
-
s1, s2, s3, s4 = (300, 300, 150, 300) if quick else (1500, 1500, 600, 1200)
|
| 162 |
-
|
| 163 |
-
mono = TrainableEncoder(F=2 ** 15, d=128, tau=0.1, seed=0,
|
| 164 |
-
features_fn=hashed_features_slot)
|
| 165 |
-
mono.train(prompts, augment, steps=s1, batch=32, lr=0.05, seed=1)
|
| 166 |
-
bi = TrainableEncoder(F=2 ** 15, d=128, tau=0.1, seed=0, W=mono.W.copy(),
|
| 167 |
-
features_fn=hashed_features_slot)
|
| 168 |
-
bi.train_pairs(pairs, augment, steps=s2, batch=32, lr=0.05, seed=2)
|
| 169 |
-
bi.train(prompts, augment, steps=s3, batch=32, lr=0.03, seed=3)
|
| 170 |
-
|
| 171 |
-
# stage 2: sibling-rich pool (KB + scaled corpus) with hard negatives
|
| 172 |
-
pool = prompts + [e["prompt"] for e in make_scaled_corpus(3000, seed=0)]
|
| 173 |
-
stat = train_slot_aware(bi, pool, steps=s4, batch=24, lr=0.03, seed=5,
|
| 174 |
-
templates=templates)
|
| 175 |
-
if out_path:
|
| 176 |
-
bi.save(out_path)
|
| 177 |
-
return bi, stat
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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