maxpagels's picture
Release 0.0.1
bcae6cd verified
Raw History Blame Contribute Delete
2.25 kB
"""Network building blocks, the same as Axiom's (axiom.model), copied so that axiom-effect
does not depend on axiom-discovery's internals. Keep the attribute names: they are the weights'
names in every checkpoint."""
from contextlib import contextmanager
import torch
import torch.nn as nn
def mlp(i, h, o):
return nn.Sequential(nn.Linear(i, h), nn.GELU(), nn.Linear(h, o))
class Attention(nn.Module):
"""Pre-norm residual self-attention over the middle axis of (N, L, E). With
`inducing` > 0 the tokens attend through that many learned inducing points (as in
Set Transformer's ISAB): cost O(L * inducing) instead of O(L^2), so L can be large.
`mask` (N, L), True = padding: those tokens are updated but not attended to (a
sequence with every token masked attends to all of them, to stay finite)."""
def __init__(self, E, H, inducing=0):
super().__init__()
self.norm = nn.LayerNorm(E)
self.attn = nn.MultiheadAttention(E, H, batch_first=True)
self.points = nn.Parameter(torch.randn(inducing, E) / E ** 0.5) if inducing else None
self.gather = nn.MultiheadAttention(E, H, batch_first=True) if inducing else None
def forward(self, x, mask=None):
h = self.norm(x)
if mask is not None:
mask = mask & ~mask.all(1, keepdim=True)
if self.points is None:
return x + self.attn(h, h, h, key_padding_mask=mask, need_weights=False)[0]
p = self.points.expand(x.shape[0], -1, -1)
s = self.gather(p, h, h, key_padding_mask=mask, need_weights=False)[0] # summarize the tokens
return x + self.attn(h, s, s, need_weights=False)[0] # every token reads the summary
class FeedForward(nn.Module):
"""Pre-norm residual MLP over the last axis."""
def __init__(self, E, mult=4):
super().__init__()
self.norm = nn.LayerNorm(E)
self.net = mlp(E, mult * E, E)
def forward(self, x):
return x + self.net(self.norm(x))
@contextmanager
def eval_mode(model):
"""The model in eval mode inside the block, then back in whichever mode it was in."""
was_training = model.training
model.eval()
try:
yield model
finally:
model.train(was_training)