pns-bind-25m / e8_full /source /pns /model /relwrite.py
nur-dev's picture
Add E8-FULL reproducibility assets and update author metadata
b9461a3 verified
Raw History Blame Contribute Delete
2.85 kB
"""PNS-RelWrite (E5): apply the identity objective where its gradient can reach
the write.
E4 supervised the intermediate identity at the QUESTION. Training detaches the
recurrent state every 32 events, and 70.2% of two-hop questions ask about a
relation written more than 32 events earlier (median 64), so for most questions
that loss had no gradient path to the write it was complaining about.
E5 keeps E4's read path unchanged and moves only where the identity loss is
evaluated. The model therefore exposes the payload at the moment it is written,
so a loss can be attached there:
write step, relation observation writing slot w:
lg_e = <V . s_w , key_ent(e)> e over entities of this lifetime
read step, question over attribute a:
lg_j = <W . s_1 , key_j> j over slots carrying attribute a
`addr_w` exists in every arm, so `ADDR_WRITE`, `ADDR_READ` and `ADDR_SHUF` are
parameter-identical and differ only in where the loss is applied and against
what target.
A separate module from `compose.py` so the E4 arms keep their recorded hash.
"""
from __future__ import annotations
from dataclasses import dataclass
import torch
import torch.nn as nn
from .compose import ComposeConfig, PNSCompose
@dataclass
class RelWriteConfig(ComposeConfig):
mode: str = "hard" # read path is hard dereference in every E5 arm
class PNSRelWrite(PNSCompose):
def __init__(self, cfg: RelWriteConfig):
super().__init__(cfg)
self.addr_w = nn.Linear(cfg.d, cfg.d, bias=False)
def entity_logits(self, payload, cand_ent):
"""Score candidate entity identities against a written payload.
payload [B, d] the record just written
cand_ent [B, E] int candidate entity ids, -1 padding
"""
q = self.addr_w(payload) # [B, d]
k = self.key_ent((cand_ent.long() + 1).clamp(0, 4096)) # [B, E, d]
lg = torch.einsum("bd,bed->be", q, k.to(q.dtype))
return lg.masked_fill(cand_ent < 0, -1e9)
def step(self, state, tok, etype, dt, bind_write, bind_read, slot_ent, slot_attr,
target_attr=None, freeze_writes=False, payload_scale=1.0,
rec_bank=None, live_mask=None, hop_override=None):
state, out = super().step(
state, tok, etype, dt, bind_write, bind_read, slot_ent, slot_attr,
target_attr=target_attr, freeze_writes=freeze_writes,
payload_scale=payload_scale, rec_bank=rec_bank, live_mask=live_mask,
hop_override=hop_override)
# expose the payload this event just wrote, so a write-time loss can see it
B, S, d = state.shape
w = bind_write.long().clamp(min=0).view(B, 1, 1).expand(-1, 1, d)
out["write_payload"] = torch.gather(state, 1, w).squeeze(1)
return state, out