Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85
46 lines
2.1 KiB
Python
46 lines
2.1 KiB
Python
"""Affective CPPN, Relational Perceptron, Gated Relational Perceptron, Organism.
|
|
|
|
Spec §3–§4. Shapes: N entities, k coords, d attrs, E edge types, C context dims, D hidden.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import torch
|
|
from torch import Tensor, nn
|
|
|
|
|
|
class AffectiveCPPN(nn.Module):
|
|
"""m_ij = W2 sin(omega * (W1 [r_ij ‖ onehot(e_ij) ‖ context] + b1)). One weight per channel."""
|
|
|
|
def __init__(self, coord_dim: int, n_edge_types: int, context_dim: int,
|
|
hidden: int, out_dim: int, omega: float = 10.0):
|
|
super().__init__()
|
|
self.l1 = nn.Linear(coord_dim + n_edge_types + context_dim, hidden)
|
|
self.l2 = nn.Linear(hidden, out_dim)
|
|
# omega is the calibration knob for kernel bandwidth; default
|
|
# Linear init cannot reach the ~1/sigma frequencies a local kernel needs.
|
|
self.omega = omega
|
|
|
|
def forward(self, r: Tensor, edge_onehot: Tensor, context: Tensor) -> Tensor:
|
|
n = r.shape[0]
|
|
ctx = context.view(1, 1, -1).expand(n, n, -1)
|
|
z = torch.cat([r, edge_onehot, ctx], dim=-1)
|
|
return self.l2(torch.sin(self.omega * self.l1(z)))
|
|
|
|
|
|
class RelationalPerceptron(nn.Module):
|
|
"""h_i = tanh( mean_{j in N_i} m_ij ⊙ (W_feat p_j) + b )."""
|
|
|
|
def __init__(self, attr_dim: int, coord_dim: int, n_edge_types: int, context_dim: int,
|
|
hidden_dim: int, cppn_hidden: int = 32, omega: float = 10.0):
|
|
super().__init__()
|
|
self.cppn = AffectiveCPPN(coord_dim, n_edge_types, context_dim, cppn_hidden, hidden_dim, omega)
|
|
self.feat = nn.Linear(attr_dim, hidden_dim, bias=False)
|
|
self.bias = nn.Parameter(torch.zeros(hidden_dim))
|
|
|
|
def forward(self, attrs: Tensor, r: Tensor, edge_onehot: Tensor, mask: Tensor, context: Tensor) -> Tensor:
|
|
m = self.cppn(r, edge_onehot, context) # (N,N,D)
|
|
f = self.feat(attrs) # (N,D)
|
|
msg = m * f[None, :, :] * mask[:, :, None] # (N,N,D)
|
|
deg = mask.sum(dim=1, keepdim=True).clamp(min=1.0) # (N,1)
|
|
return torch.tanh(msg.sum(dim=1) / deg + self.bias)
|