File size: 2,964 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
from __future__ import annotations

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


class GatedSlotMemory(nn.Module):
    """
    Slot-based memory module with:
    - Read gate (per-token residual gating)
    - Write mask (restricting which slots are trainable)
    - Decay / forget mechanism
    """

    def __init__(self, d_model: int, n_slots: int = 16384, topk: int = 32):
        super().__init__()
        self.topk = topk
        self.norm = nn.RMSNorm(d_model)
        self.keys = nn.Parameter(torch.randn(n_slots, d_model) * (d_model ** -0.5))
        self.values = nn.Parameter(torch.zeros(n_slots, d_model))
        self.gate = nn.Linear(d_model, 1)
        nn.init.constant_(self.gate.bias, -4.0)

        self.register_buffer("strength", torch.ones(n_slots))
        self.register_buffer("write_mask", torch.ones(n_slots, dtype=torch.bool))
        self.track = False
        self.last_gate: torch.Tensor | None = None

    def forward(self, h: torch.Tensor) -> torch.Tensor:
        x = self.norm(h)
        g = torch.sigmoid(self.gate(x))  # (B, T, 1)
        if self.track:
            self.last_gate = g

        scores = x @ self.keys.T  # (B, T, n_slots)
        top = scores.topk(min(self.topk, self.keys.size(0)), dim=-1)
        w = F.softmax(top.values, dim=-1)
        v = self.values[top.indices] * self.strength[top.indices].unsqueeze(-1)
        mem = (w.unsqueeze(-1) * v).sum(dim=-2)
        return h + g * mem

    @torch.no_grad()
    def set_write_mask(self, mask: torch.Tensor) -> None:
        self.write_mask.copy_(mask.bool())

    @torch.no_grad()
    def forget(self, days: float, decay_per_day: float = 0.03) -> None:
        self.strength.mul_((1.0 - decay_per_day) ** days)


def sleep_loss(
    model: nn.Module,
    base_model: nn.Module,
    mem: GatedSlotMemory,
    batch_memory: dict[str, torch.Tensor],
    batch_general: dict[str, torch.Tensor],
    lam_kl: float = 1.0,
    lam_gate: float = 0.5,
) -> torch.Tensor:
    """
    Sleep consolidation loss:
    1) Task loss on new/rehearsed memory batch + gate should open (target=1)
    2) KL divergence on general batch against frozen base_model + gate should stay closed (target=0)
    """
    mem.track = True
    out_m = model(**batch_memory)
    g_m = mem.last_gate

    out_g = model(input_ids=batch_general["input_ids"]).logits
    g_g = mem.last_gate
    mem.track = False

    with torch.no_grad():
        ref = base_model(input_ids=batch_general["input_ids"]).logits

    kl = F.kl_div(
        F.log_softmax(out_g, dim=-1),
        F.log_softmax(ref, dim=-1),
        log_target=True,
        reduction="batchmean",
    )

    gate_loss = torch.tensor(0.0, device=out_m.loss.device)
    if g_m is not None and g_g is not None:
        gate_loss = F.binary_cross_entropy(g_m, torch.ones_like(g_m)) + F.binary_cross_entropy(
            g_g, torch.zeros_like(g_g)
        )

    return out_m.loss + lam_kl * kl + lam_gate * gate_loss