Download code/Model/gated_memory.py from Jommarn/Qwen3.5-0.8B-NestedMemory-v5: direct link, hf CLI and curl.
- Browser
- Download file 2.96 kB
-
https://huggingface.co/Jommarn/Qwen3.5-0.8B-NestedMemory-v5/resolve/main/code/Model/gated_memory.py
- Command line
-
hf download hf://Jommarn/Qwen3.5-0.8B-NestedMemory-v5/code/Model/gated_memory.py
-
curl -L -o gated_memory.py https://huggingface.co/Jommarn/Qwen3.5-0.8B-NestedMemory-v5/resolve/main/code/Model/gated_memory.py
2.96 kB
| 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 | |
| def set_write_mask(self, mask: torch.Tensor) -> None: | |
| self.write_mask.copy_(mask.bool()) | |
| 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 | |