File size: 17,917 Bytes
2f2df6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
from __future__ import annotations

import math
import torch
import torch.nn as nn
import torch.nn.functional as F


class NestedMemoryLayer(nn.Module):
    """
    Nested Learning memory layer embedded inside ONE unified model (short -> medium -> long):

      - Short-term  : the base LLM's own softmax attention over the current chat context (not here).
      - Medium-term : Loop 1, Titans-style linear associative memory (M, S), written online on
                      every prefill token, gated per token by the neural gate_write. Fades fast.
      - Long-term   : Loop 2, routed slot memory (slot_values) with softmax read. It is NOT written
                      during chat. At the end of a chat, consolidate() replays the most salient
                      tokens of the session (episodic buffer, ranked by gate_write) through M and
                      writes what the neural gate_consol deems important into the matching slots.
                      Forward-only, no backprop, no hard-coded rules. Fades slowly.
      - Skills      : Loop 3, meta-parameters (Wk/Wv/Wq, gates, router, slot_keys, ...) learned
                      only in outer-loop training: HOW to memorize, not WHAT.
    """

    def __init__(
        self,
        d_model: int,
        d_mem: int = 256,
        n_experts: int = 8,
        n_slots: int = 256,
        topk: int = 16,
        k_experts: int = 2,
        max_lr: float = 0.25,
        max_forget: float = 0.05,
        inner_steps: int = 4,
        n_buffer: int = 64,
        poly_dim: int = 0,
        omega_window: int = 1,
        muon: bool = False,
        muon_steps: int = 3,
        shift_key: bool = False,
        res_rel: bool = False,
    ):
        super().__init__()
        self.d_model = d_model
        self.d_mem = d_mem
        self.n_experts = n_experts
        self.n_slots = n_slots
        self.topk = topk
        self.k_experts = k_experts
        self.max_lr = max_lr
        self.max_forget = max_forget
        self.inner_steps = inner_steps
        self.n_buffer = n_buffer
        # --- Atlas options (all off = Titans-style baseline) ---
        self.poly_dim = poly_dim            # polynomial feature map: extra key dims = poly_dim**2
        self.omega_window = max(1, omega_window)  # Omega rule: update from a sliding window of tokens
        self.muon = muon                    # Muon: Newton-Schulz orthogonalised momentum update
        self.muon_steps = muon_steps
        self.d_key = d_mem + poly_dim * poly_dim
        # v3: write pairs (key of token t-1 -> value of token t), so a query at token t recalls what FOLLOWED
        # a similar context when it was told ("...ชื่อ" -> name). Same-token k/v cannot retrieve anything new.
        self.shift_key = shift_key
        # v3: memory injection scaled to the residual stream's own RMS (a fixed 0.15 was drowned by |h|)
        self.res_rel = res_rel

        self.in_norm = nn.RMSNorm(d_model, dtype=torch.float32)
        self.out_norm = nn.RMSNorm(d_model, dtype=torch.float32)

        # --- Loop 1: Medium-term token-level associative memory (M, S) ---
        self.Wk = nn.Linear(d_model, d_mem, bias=False, dtype=torch.float32)
        self.Wv = nn.Linear(d_model, d_mem, bias=False, dtype=torch.float32)
        self.Wq = nn.Linear(d_model, d_mem, bias=False, dtype=torch.float32)
        self.fast_out = nn.Linear(d_mem, d_model, bias=False, dtype=torch.float32)
        if poly_dim > 0:
            self.Wk2 = nn.Linear(d_model, poly_dim, bias=False, dtype=torch.float32)
            self.Wq2 = nn.Linear(d_model, poly_dim, bias=False, dtype=torch.float32)
        self.gate_lr = nn.Linear(d_model, 1, dtype=torch.float32)
        self.gate_mom = nn.Linear(d_model, 1, dtype=torch.float32)
        self.gate_forget = nn.Linear(d_model, 1, dtype=torch.float32)
        self.register_buffer("M", torch.zeros(d_mem, self.d_key, dtype=torch.float32))
        self.register_buffer("S", torch.zeros(d_mem, self.d_key, dtype=torch.float32))

        # --- Loop 2: Long-term routed slot memory (slot_values, expert_strength) ---
        self.router = nn.Linear(d_model, n_experts, bias=False, dtype=torch.float32)
        self.slot_val_proj = nn.Linear(d_model, d_model, bias=False, dtype=torch.float32)
        self.gate_slot_lr = nn.Linear(d_model, 1, dtype=torch.float32)  # kept for checkpoint compat
        self.slot_keys = nn.Parameter(
            torch.randn(n_experts, n_slots, d_model, dtype=torch.float32) * (d_model ** -0.5)
        )
        self.register_buffer(
            "slot_values", torch.zeros(n_experts, n_slots, d_model, dtype=torch.float32)
        )
        self.register_buffer(
            "expert_strength", torch.ones(n_experts, dtype=torch.float32)
        )

        # --- Episodic buffer: salient tokens of the current session, waiting for consolidation ---
        self.register_buffer("ep_x", torch.zeros(n_buffer, d_model, dtype=torch.float32))
        self.register_buffer("ep_s", torch.full((n_buffer,), -1.0, dtype=torch.float32))  # -1 = empty

        # --- Neural gates (pure architecture control) ---
        self.gate_read = nn.Linear(d_model, 1, dtype=torch.float32)
        nn.init.constant_(self.gate_read.bias, -1.5)
        self.gate_write = nn.Linear(d_model, 1, dtype=torch.float32)
        nn.init.constant_(self.gate_write.bias, 0.0)
        self.gate_consol = nn.Linear(d_model, 1, dtype=torch.float32)
        nn.init.constant_(self.gate_consol.bias, 0.0)
        self.res_scale = nn.Parameter(torch.tensor(0.5 if res_rel else 0.15, dtype=torch.float32))

        self.online_update: bool = True
        self.keep_grad_state: bool = False
        # (M, S, V, buf_x, buf_s) carried with autograd during outer-loop training
        self._grad_state: tuple[torch.Tensor, ...] | None = None
        self.last_gate: torch.Tensor | None = None
        self.last_write_gate: torch.Tensor | None = None
        self.last_consol_gate: torch.Tensor | None = None
        self.last_y_fast: torch.Tensor | None = None  # raw medium-memory read (for the training read loss)
        self.last_x_in: torch.Tensor | None = None

    # ------------------------------------------------------------------ feature maps
    def _feat(self, x: torch.Tensor, query: bool) -> torch.Tensor:
        """Key/query features. Atlas polynomial map: [k, vec(k2 k2^T)] (degree-2 kernel) when poly_dim > 0."""
        base = (self.Wq if query else self.Wk)(x)
        if self.poly_dim <= 0:
            return F.normalize(base, dim=-1)
        p = F.normalize((self.Wq2 if query else self.Wk2)(x), dim=-1)
        outer = (p.unsqueeze(-1) * p.unsqueeze(-2)).flatten(-2)
        return F.normalize(torch.cat([F.normalize(base, dim=-1), outer], dim=-1), dim=-1)

    @staticmethod
    def _newton_schulz(G: torch.Tensor, steps: int) -> torch.Tensor:
        """Muon: approximately orthogonalise a (B, r, c) matrix (r <= c) with quintic Newton-Schulz."""
        a, b, c = 3.4445, -4.7750, 2.0315
        X = G / (G.flatten(1).norm(dim=-1)[:, None, None] + 1e-7)
        for _ in range(steps):
            A = X @ X.transpose(-1, -2)
            X = a * X + (b * A + c * (A @ A)) @ X
        return X

    # ------------------------------------------------------------------ state helpers
    def _current_state(self, B: int) -> tuple[torch.Tensor, ...]:
        if torch.is_grad_enabled() and self._grad_state is not None:
            return self._grad_state
        M = self.M.unsqueeze(0).expand(B, -1, -1).clone()
        S = self.S.unsqueeze(0).expand(B, -1, -1).clone()
        return M, S, self.slot_values.clone(), self.ep_x.clone(), self.ep_s.clone()

    def _commit_state(self, M, S, V, bx, bs) -> None:
        if torch.is_grad_enabled() and self.keep_grad_state:
            self._grad_state = (M, S, V, bx, bs)
        elif not torch.is_grad_enabled():
            self.M.copy_(M[0].detach())
            self.S.copy_(S[0].detach())
            self.slot_values.copy_(V.detach())
            self.ep_x.copy_(bx.detach())
            self.ep_s.copy_(bs.detach())

    # ---- v5: extra memory layers at other depths ("peers") follow the primary layer's controls
    def __setattr__(self, name, value):
        super().__setattr__(name, value)
        if name in ("online_update", "keep_grad_state") or (name == "_grad_state" and value is None):
            for p in self.__dict__.get("peers", ()):
                setattr(p, name, value)

    @torch.no_grad()
    def reset_memory(self) -> None:
        for p in self.__dict__.get("peers", ()):
            p.reset_memory()
        self._reset_own()

    @torch.no_grad()
    def _reset_own(self) -> None:
        """Wipe all personal memories (medium, long, episodic buffer) while keeping learned skills."""
        self.M.zero_()
        self.S.zero_()
        self.slot_values.zero_()
        self.expert_strength.fill_(1.0)
        self.ep_x.zero_()
        self.ep_s.fill_(-1.0)
        self._grad_state = None

    @torch.no_grad()
    def forget(self, days: float, fast_rate: float = 0.05, slow_rate: float = 0.02) -> None:
        """Multi-timescale Ebbinghaus decay: medium M fades faster than long-term slots."""
        for p in self.__dict__.get("peers", ()):
            p.forget(days, fast_rate, slow_rate)
        d = max(0.0, float(days))
        self.M.mul_(math.exp(-fast_rate * d))
        self.S.zero_()
        self.expert_strength.mul_(math.exp(-slow_rate * d))

    # ------------------------------------------------------------------ consolidation
    def consolidate(self) -> dict:
        for p in self.__dict__.get("peers", ()):
            p._consolidate_own()
        return self._consolidate_own()

    def _consolidate_own(self) -> dict:
        """
        End-of-session consolidation (medium -> long), forward-only:
          1. replay buffered salient tokens as cues into M  -> what M recalls for them
          2. gate_consol (neural) x salience decides how strongly each one is kept
          3. write into the slot whose key best matches the cue (the slot that later reads will hit)
          4. clear the episodic buffer
        Differentiable when called inside outer-loop training (keep_grad_state=True).
        """
        M, S, V, bx, bs = self._current_state(1)
        valid = (bs >= 0).float()
        if valid.sum() == 0:
            return {"consolidated": 0}

        x = bx  # (N, d_model), already in_norm'ed
        q = self._feat(x, query=True)
        recall = self.fast_out(torch.einsum("ij,nj->ni", M[0], q))  # (N, d_model)
        value = self.slot_val_proj(x) + recall

        c = torch.sigmoid(self.gate_consol(x)).squeeze(-1) * bs.clamp(min=0.0) * valid  # (N,)
        self.last_consol_gate = c

        E, Sn, D = V.shape
        exp_idx = self.router(x).argmax(dim=-1)  # (N,)
        keys_norm = F.normalize(self.slot_keys, dim=-1)
        sims = torch.einsum("nd,esd->nes", F.normalize(x, dim=-1), keys_norm)  # (N, E, Sn)
        slot_idx = sims[torch.arange(x.shape[0], device=x.device), exp_idx].argmax(dim=-1)
        flat = exp_idx * Sn + slot_idx  # (N,)

        w_sum = torch.zeros(E * Sn, device=x.device, dtype=x.dtype).index_add(0, flat, c)
        v_sum = torch.zeros(E * Sn, D, device=x.device, dtype=x.dtype).index_add(0, flat, c[:, None] * value)
        rate = w_sum.clamp(max=1.0)[:, None]
        target = v_sum / w_sum.clamp(min=1e-6)[:, None]
        V_new = ((1.0 - rate) * V.reshape(E * Sn, D) + rate * target).reshape(E, Sn, D)

        empty_x = torch.zeros_like(bx)
        empty_s = torch.full_like(bs, -1.0)
        self._commit_state(M, S, V_new, empty_x, empty_s)
        return {"consolidated": int(valid.sum().item()), "consol_gate_mean": float((c.sum() / valid.sum()).item())}

    # ------------------------------------------------------------------ forward
    def forward(self, h: torch.Tensor) -> torch.Tensor:
        orig_dtype = h.dtype
        B, T, _ = h.shape
        x = self.in_norm(h.float())

        g_read = torch.sigmoid(self.gate_read(x))    # (B, T, 1)
        g_write = torch.sigmoid(self.gate_write(x))  # (B, T, 1) - pure neural architecture gate
        if T > 1 or self.last_gate is None:
            self.last_gate = g_read
            self.last_write_gate = g_write

        # Only write during input prefill (T > 1)
        do_write = self.online_update and (T > 1)

        M, S, V, bx, bs = self._current_state(B)

        # ---------- Medium-term: associative memory (M, S) ----------
        k = self._feat(x, query=False)
        q = self._feat(x, query=True)
        v = self.Wv(x)

        # 1) Read from incoming memory first (prevents intra-turn teacher-forcing leakage)
        y_fast = self.fast_out(torch.einsum("bij,btj->bti", M, q))  # (B, T, d_model)

        if torch.is_grad_enabled() and T > 1:
            self.last_y_fast = y_fast
            self.last_x_in = x  # (v4 recall loss) normalised inputs of this forward

        # 2) Multi-step online delta write, controlled 100% by neural g_write
        if do_write:
            if self.shift_key:
                # pair t: key from token t-1, value / gates from token t (the token being remembered)
                k, v, xg, gw_pair, bx_src = k[:, :-1], v[:, 1:], x[:, 1:], g_write[:, 1:], x[:, :-1]
            else:
                xg, gw_pair, bx_src = x, g_write, x
            Tw = k.shape[1]
            theta = torch.sigmoid(self.gate_lr(xg)) * gw_pair * self.max_lr
            eta = torch.sigmoid(self.gate_mom(xg))
            alpha = torch.sigmoid(self.gate_forget(xg)) * gw_pair * self.max_forget
            c = self.omega_window
            for _ in range(self.inner_steps):
                for t in range(Tw):
                    if c <= 1:
                        err = torch.einsum("bij,bj->bi", M, k[:, t]) - v[:, t]
                        grad = 2.0 * torch.einsum("bi,bj->bij", err, k[:, t])
                    else:
                        # Atlas Omega rule: fit the whole recent window, each token weighted by its own g_write
                        lo = max(0, t - c + 1)
                        kw, vw = k[:, lo:t + 1], v[:, lo:t + 1]
                        gw = gw_pair[:, lo:t + 1, 0]
                        err = torch.einsum("bij,bwj->bwi", M, kw) - vw
                        grad = 2.0 * torch.einsum("bw,bwi,bwj->bij", gw, err, kw) / kw.shape[1]
                    if self.muon:
                        # Atlas/Muon: momentum of raw gradients, orthogonalised step scaled by theta
                        S = eta[:, t, :, None] * S - grad
                        M = (1.0 - alpha[:, t, :, None]) * M + theta[:, t, :, None] * self._newton_schulz(S, self.muon_steps)
                    else:
                        S = eta[:, t, :, None] * S - theta[:, t, :, None] * grad
                        M = (1.0 - alpha[:, t, :, None]) * M + S

            # 3) Episodic buffer: keep the n_buffer most salient tokens (ranked by neural g_write)
            # (shift_key: the cue stored is the context token t-1, scored by the salience of token t)
            all_x = torch.cat([bx, bx_src.reshape(-1, self.d_model)], dim=0)
            all_s = torch.cat([bs, gw_pair.reshape(-1)], dim=0)
            top = all_s.topk(min(self.n_buffer, all_s.numel())).indices
            bx, bs = all_x[top], all_s[top]

        # ---------- Long-term: routed slot read (softmax attention over slots) ----------
        r_logits = self.router(x)
        top_exp = r_logits.topk(min(self.k_experts, self.n_experts), dim=-1)
        w_exp = F.softmax(top_exp.values, dim=-1)

        keys_norm = F.normalize(self.slot_keys, dim=-1)
        x_norm = F.normalize(x, dim=-1)
        y_med = torch.zeros_like(x)
        for e in range(self.n_experts):
            we = (w_exp * (top_exp.indices == e)).sum(dim=-1, keepdim=True)  # (B, T, 1)
            if not we.any():
                continue
            scores = torch.einsum("btd,sd->bts", x_norm, keys_norm[e])
            top_s = scores.topk(min(self.topk, self.n_slots), dim=-1)
            w_s = F.softmax(top_s.values * 5.0, dim=-1)
            read_e = (w_s.unsqueeze(-1) * V[e][top_s.indices]).sum(dim=-2)
            y_med = y_med + we * self.expert_strength[e] * read_e

        if do_write or (torch.is_grad_enabled() and self.keep_grad_state):
            if B == 1 or torch.is_grad_enabled():
                self._commit_state(M, S, V, bx, bs)

        # ---------- Normalized residual + per-token read gate (100% neural) ----------
        mem_raw = y_fast + y_med
        if mem_raw.abs().max() < 1e-7:
            mem_normed = torch.zeros_like(x)
        else:
            mem_normed = self.out_norm(mem_raw) * self.res_scale.clamp(-1.0, 1.0)
            if self.res_rel:
                mem_normed = mem_normed * h.float().pow(2).mean(-1, keepdim=True).sqrt().detach()

        out_h = h.float() + g_read * mem_normed
        return out_h.to(orig_dtype)


if __name__ == "__main__":
    layer = NestedMemoryLayer(d_model=64, d_mem=32, n_experts=4, n_slots=16, topk=4, n_buffer=8)
    with torch.no_grad():
        layer(torch.randn(1, 10, 64))
        print("buffer filled:", int((layer.ep_s >= 0).sum()), "M_norm:", round(layer.M.norm().item(), 4))
        print("consolidate:", layer.consolidate())
        print("V_norm after consolidate:", round(layer.slot_values.norm().item(), 4),
              "buffer after:", int((layer.ep_s >= 0).sum()))
    # gradient path: write -> consolidate -> fade M -> read
    layer.reset_memory()
    layer.keep_grad_state = True
    layer(torch.randn(1, 10, 64))
    layer.consolidate()
    M, S, V, bx, bs = layer._grad_state
    layer._grad_state = (M * 0.0, S * 0.0, V, bx, bs)  # M fully faded -> answer must come from slots
    y = layer(torch.randn(1, 6, 64))
    y.sum().backward()
    print("grad gate_consol:", round(layer.gate_consol.weight.grad.abs().sum().item(), 4),
          "grad gate_write:", round(layer.gate_write.weight.grad.abs().sum().item(), 4))