empty repo for clean single-source upload
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177"""PHASE P2 — Slot-aware encoder training (التدريب المُدرِّك للخرائط/الفتحات).Why Phase-P1 retrieval was weak: the encoder never saw SIBLING pairs duringtraining ("fact 42 about rivers" vs "fact 43 about rivers"), so number slotsgot no gradient and novel wordings diluted the shared signal.
Three mechanisms (all NumPy):1. Slot-aware featurizer: numeric tokens get dedicated `N:` features (2x weight) so digits are not drowned by shared scaffolding n-grams.2. HARD NEGATIVE siblings inside InfoNCE: every anchor carries a guaranteed same-template/different-number negative column (pattern separation pressure at the ENCODER level, not only at the gate).3. Novel-wording positives: 50% of positives are re-renderings under unseen templates (TEMPLATES_NOVEL) — trains scaffold invariance directly.
Anatomy: dentate gyrus adult neurogenesis = separating similar patterns whileCA3/completion keeps gist; the sibling negatives ARE the separation pressure."""import reimport randomimport numpy as np
from phase_c_encoder import TrainableEncoder, hashed_featuresfrom phase_c_augment import augmentfrom phase_d_bilingual import make_pairsfrom phase_s_scale import TEMPLATES_NOVEL, make_scaled_corpus
# ------------------------------------------------------------- featurizer v2def hashed_features_slot(text, F=2 ** 15): """hashed_features + dedicated numeric-slot features (`N:<token>` x2).""" idx, val = hashed_features(text, F) toks = re.findall(r"\d+", text) if not toks: return idx, val acc = {} for i, v in zip(idx, val): acc[int(i)] = acc.get(int(i), 0.0) + float(v) for t in toks: for rep in (0, 1): # x2 weight for number slots f = f"N:{t}#{rep}" h = int(__import__("hashlib").md5(f.encode()).hexdigest()[:8], 16) i = h % F s = 1.0 if (h >> 16) & 1 else -1.0 acc[i] = acc.get(i, 0.0) + s idx2 = np.array([i for i, v in acc.items() if v != 0], dtype=np.int64) val2 = np.array([v for v in acc.values() if v != 0], dtype=np.float32) return idx2, val2
# ------------------------------------------------------------- slot toolsdef make_sibling(text, rng): """Same prompt, different slot value — the hard negative the encoder never saw.""" def repl(m): n = int(m.group(0)) return str(n + rng.randint(100, 9000)) return re.sub(r"\d+", repl, text)
def novel_view(text, rng, templates=None): """Re-render the SAME fact under an unseen template (novel-wording positive). `templates` lets tests hold out phrasings the trainer never sees.""" T = templates or TEMPLATES_NOVEL m = re.search(r"(\d+)", text) if not m: return augment(text, rng) num = m.group(1) m2 = (re.search(r"about (?:the )?(\w+)", text) or re.search(r"حول (\w+)", text) or re.search(r"the (\w+) value", text)) if not m2: return augment(text, rng) topic = m2.group(1) tpl_q, _ = T[rng.randint(0, len(T))] try: return tpl_q.format(i=num, t=topic) except Exception: return augment(text, rng)
# ------------------------------------------------------------- slot-aware InfoNCEdef train_slot_aware(enc, pool, steps=1200, batch=24, lr=0.03, seed=5, log_every=300, templates=None): """InfoNCE with B x (B+1) scores: columns = [in-batch positives | sibling]. Positive = augment OR novel_view; sibling = make_sibling (hard negative).""" rng = np.random.RandomState(seed) losses = [] for step in range(steps): picks = rng.randint(0, len(pool), batch) bases = [pool[i] for i in picks] anchors, posits, sibs = [], [], [] for t in bases: anchors.append(t if rng.rand() < 0.5 else augment(t, rng)) posits.append(augment(t, rng) if rng.rand() < 0.5 else novel_view(t, rng, templates)) sibs.append(make_sibling(t, rng))
def feats(texts): return [enc.feat(t, enc.F) for t in texts]
def fwd(feats_): Z = np.zeros((batch, enc.d), dtype=np.float32) for r, (idx, val) in enumerate(feats_): if len(idx): Z[r] = val @ enc.W[idx] norms = np.linalg.norm(Z, axis=1, keepdims=True) return Z / np.maximum(norms, 1e-8), norms
fa, fp, fs = feats(anchors), feats(posits), feats(sibs) Ea, na = fwd(fa) Ep, npp = fwd(fp) Es, ns = fwd(fs)
S_pos = (Ea @ Ep.T) / enc.tau # BxB S_sib = np.sum(Ea * Es, axis=1, keepdims=True) / enc.tau # Bx1 S = np.concatenate([S_pos, S_sib], axis=1) # Bx(B+1) S -= S.max(axis=1, keepdims=True) P = np.exp(S) P /= P.sum(axis=1, keepdims=True) tgt = P[np.arange(batch), np.arange(batch)] loss = -float(np.mean(np.log(np.maximum(tgt, 1e-12)))) losses.append(loss)
dS = P.copy() dS[np.arange(batch), np.arange(batch)] -= 1.0 dS /= batch dS_pos, dS_sib = dS[:, :batch], dS[:, batch:] # BxB, Bx1 dEa = (dS_pos @ Ep + dS_sib * Es) / enc.tau dEp = (dS_pos.T @ Ea) / enc.tau dEs = (dS_sib * Ea) / enc.tau
def bwd(feats_, E, norms, dE): dots = np.sum(E * dE, axis=1, keepdims=True) dZ = (dE - E * dots) / np.maximum(norms, 1e-8) for r, (idx, val) in enumerate(feats_): if len(idx): enc.W[idx] -= lr * np.outer(val.astype(np.float32), dZ[r]).astype(np.float32)
bwd(fa, Ea, na, dEa) bwd(fp, Ep, npp, dEp) bwd(fs, Es, ns, dEs) if log_every and (step + 1) % log_every == 0: lr *= 0.9 return {"loss_first": float(np.mean(losses[:50])), "loss_last": float(np.mean(losses[-50:])), "steps": steps}
# ------------------------------------------------------------- full curriculumdef load_slot(path): """Load a P2 artifact WITH its slot-aware featurizer (W was trained on it).""" z = np.load(path) enc = TrainableEncoder(F=int(z["F"]), d=int(z["d"]), tau=float(z["tau"]), W=z["W"], features_fn=hashed_features_slot) return enc
def build_p2_encoder(kb, out_path="phase_p2_W.npz", quick=False, templates=None): """Phase-D recipe on the KB (preserve what works) + stage-2 slot-aware training on a sibling-rich pool. Returns the trained encoder.""" prompts = [e["prompt"] for e in kb] pairs = make_pairs(kb) s1, s2, s3, s4 = (300, 300, 150, 300) if quick else (1500, 1500, 600, 1200)
mono = TrainableEncoder(F=2 ** 15, d=128, tau=0.1, seed=0, features_fn=hashed_features_slot) mono.train(prompts, augment, steps=s1, batch=32, lr=0.05, seed=1) bi = TrainableEncoder(F=2 ** 15, d=128, tau=0.1, seed=0, W=mono.W.copy(), features_fn=hashed_features_slot) bi.train_pairs(pairs, augment, steps=s2, batch=32, lr=0.05, seed=2) bi.train(prompts, augment, steps=s3, batch=32, lr=0.03, seed=3)
# stage 2: sibling-rich pool (KB + scaled corpus) with hard negatives pool = prompts + [e["prompt"] for e in make_scaled_corpus(3000, seed=0)] stat = train_slot_aware(bi, pool, steps=s4, batch=24, lr=0.03, seed=5, templates=templates) if out_path: bi.save(out_path) return bi, statphase_p2_slot.pyDeleted-177