"""NEO (Neural Theorizer) and the three monolithic baselines. Architecture follows Table 19/22 of arXiv:2605.03413v2: shared pretrained CNN VAE encoder/decoder, FiLM-MLP policy and transition networks, VQ codebook for the discrete "language of thought", MDL length selection (Eq. 4). """ from __future__ import annotations import torch import torch.nn as nn import torch.nn.functional as F # Scale of the state-grounding term relative to the categorical reconstruction # loss; see src/_abcheck.py. True = mean over state dims, False = sum (paper's # literal Eq. 5). GROUNDING_MEAN = True # -------------------------------------------------------------------------- # Shared observation autoencoder (pretrained once, reused by every method) # -------------------------------------------------------------------------- class ConvVAE(nn.Module): """Small CNN VAE over (1, H, W) one-hot grids. The observation always has exactly one active cell per row-group, so the decoder emits per-cell logits and exact-match decoding is an argmax. """ def __init__(self, h, w, state_dim=32, d_model=32, mode="flat"): super().__init__() self.h, self.w, self.state_dim = h, w, state_dim self.mode = mode # "flat" (grid) or "row" (digits) self.enc = nn.Sequential( nn.Conv2d(1, d_model, 3, 1, 1), nn.ReLU(), nn.Conv2d(d_model, d_model, 3, 2, 1), nn.ReLU(), nn.Conv2d(d_model, d_model, 3, 2, 1), nn.ReLU(), ) self.eh, self.ew = (h + 3) // 4, (w + 3) // 4 feat = d_model * self.eh * self.ew self.to_mu = nn.Linear(feat, state_dim) self.to_lv = nn.Linear(feat, state_dim) self.from_z = nn.Linear(state_dim, feat) self.dec = nn.Sequential( nn.ConvTranspose2d(d_model, d_model, 3, 2, 1), nn.ReLU(), nn.ConvTranspose2d(d_model, d_model, 4, 2, 1), nn.ReLU(), ) self.head = nn.Conv2d(d_model, 1, 3, 1, 1) self.d_model = d_model def encode(self, x): f = self.enc(x).flatten(1) return self.to_mu(f), self.to_lv(f) def decode(self, s): f = self.from_z(s).view(-1, self.d_model, self.eh, self.ew) f = self.dec(f) # The transposed-conv stack only lands exactly on (h, w) when both are # multiples of 4 (true for the 10x10 grid, false for the 8x10 digit # grid, where it produced 6 rows). Resize to the exact observation # shape before the output head; this is a no-op when the stack already # matches, so GridWorld results are unchanged. if f.shape[-2] != self.h or f.shape[-1] != self.w: f = F.interpolate(f, size=(self.h, self.w), mode="nearest") return self.head(f) def forward(self, x): mu, lv = self.encode(x) s = mu + torch.randn_like(mu) * (0.5 * lv).exp() return self.decode(x if False else s), mu, lv def recon_loss(logits, target, mode="flat", reduce=True): """Per-example categorical NLL. The observation is one-hot by construction (one object cell for GridWorld, one digit per position for Arithmetic), so the natural likelihood is a softmax over the candidate cells -- and it is exactly the quantity whose arg-max defines the paper's exact-match metric. Pixel-wise BCE is the wrong likelihood here: with 99 background cells to 1 foreground it is minimised by predicting all-background, which never learns the object. """ if mode == "flat": l = F.cross_entropy(logits.flatten(1), target.flatten(1).argmax(1), reduction="none") else: lp = logits[:, 0] # (N, H, W) tgt = target[:, 0].argmax(-1) # (N, H) l = F.cross_entropy(lp.reshape(-1, lp.shape[-1]), tgt.reshape(-1), reduction="none").view(tgt.shape).mean(1) return l.mean() if reduce else l def to_obs(logits, mode="flat"): """Logits -> a normalised observation-shaped tensor (for state grounding).""" if mode == "flat": n, c, h, w = logits.shape return F.softmax(logits.flatten(1), dim=1).view(n, c, h, w) return F.softmax(logits, dim=-1) def decode_index(logits, mode="flat"): """Argmax decoding to a discrete object identity for exact-match scoring.""" if mode == "flat": return logits.flatten(1).argmax(1) # "row": one active cell per row (digit string) return logits[:, 0].argmax(-1) # (N, H) # -------------------------------------------------------------------------- # FiLM-MLP building block # -------------------------------------------------------------------------- class FiLMMLP(nn.Module): """FiLM-conditioned MLP. The pretrained VAE latent has a large scale (||s|| ~ 19), which makes an un-normalised FiLM layer produce gammas of order 10 and diverge. We LayerNorm both the input and the conditioning stream; this is conditioning hygiene, not a change to the method. """ def __init__(self, in_dim, cond_dim, out_dim, d_ff=128): super().__init__() self.ln_x = nn.LayerNorm(in_dim) self.ln_c = nn.LayerNorm(cond_dim) self.fc1 = nn.Linear(in_dim, d_ff) self.film = nn.Linear(cond_dim, 2 * d_ff) self.fc2 = nn.Linear(d_ff, d_ff) self.out = nn.Linear(d_ff, out_dim) def forward(self, x, cond): h = self.fc1(self.ln_x(x)) gamma, beta = self.film(self.ln_c(cond)).chunk(2, dim=-1) h = F.relu(h * (1 + gamma) + beta) h = F.relu(self.fc2(h)) return self.out(h) class VQ(nn.Module): """Vector quantiser with straight-through estimator and commitment loss.""" def __init__(self, n_codes, dim, commitment=0.25): super().__init__() self.emb = nn.Embedding(n_codes, dim) nn.init.normal_(self.emb.weight, 0.0, 1.0) # matches LayerNormed inputs self.commitment = commitment self.n_codes = n_codes def dists(self, z): return (z.pow(2).sum(1, keepdim=True) - 2 * z @ self.emb.weight.t() + self.emb.weight.pow(2).sum(1)[None, :]) def forward(self, z, idx=None): d = self.dists(z) if idx is None: idx = d.argmin(1) zq = self.emb(idx) loss = F.mse_loss(zq, z.detach()) + self.commitment * F.mse_loss(z, zq.detach()) zq_st = z + (zq - z).detach() return zq_st, idx, loss def lookup(self, idx): return self.emb(idx) # -------------------------------------------------------------------------- # NEO # -------------------------------------------------------------------------- class NEO(nn.Module): def __init__(self, vae: ConvVAE, n_codes=6, action_dim=16, d_ff=128, commitment=0.25, grounding=True): super().__init__() self.vae = vae sd = vae.state_dim self.policy = FiLMMLP(sd, sd, action_dim, d_ff) # q_phi(z | s_k, s_y) self.pol_norm = nn.LayerNorm(action_dim) # bounded VQ inputs self.transition = FiLMMLP(sd, action_dim, sd, d_ff) # f_theta(s, z) self.vq = VQ(n_codes, action_dim, commitment) self.grounding = grounding # identity-initialised execution: s_{k+1} = s_k at step 0, so the # rollout starts on the encoder manifold instead of drifting off it. nn.init.zeros_(self.transition.out.weight) nn.init.zeros_(self.transition.out.bias) def step(self, s, z_q): return s + self.transition(s, z_q) # residual execution def rollout(self, s1, s_y, K, temperature=None, generator=None): """Unroll K steps. Returns states s_1..s_{K+1}, code indices, vq loss.""" s, states, codes, vq_loss = s1, [s1], [], 0.0 for _ in range(K): a = self.pol_norm(self.policy(s, s_y)) if temperature is None: zq, idx, l = self.vq(a) else: logits = -self.vq.dists(a) / temperature probs = F.softmax(logits, dim=1) idx = torch.multinomial(probs, 1, generator=generator).squeeze(1) zq, idx, l = self.vq(a, idx=idx) vq_loss = vq_loss + l s = self.step(s, zq) states.append(s) codes.append(idx) return states, torch.stack(codes, 1), vq_loss / max(K, 1) def mdl_select(self, states, target, lam): """Eq. (4): k* = argmin_L lambda^L * loss(y, D(s_{L+1})), L in 0..K.""" mode = getattr(self.vae, "mode", "flat") losses = torch.stack( [recon_loss(self.vae.decode(s), target, mode, reduce=False) for s in states], 1) L = torch.arange(losses.shape[1], device=losses.device, dtype=losses.dtype) scores = (lam ** L)[None, :] * losses kstar = scores.argmin(1) return kstar, losses def grounding_loss(self, states): if not self.grounding: return torch.zeros((), device=states[0].device) mode = getattr(self.vae, "mode", "flat") tot = 0.0 for s in states[1:]: # intermediate + final states with torch.no_grad(): anchor = self.vae.encode(to_obs(self.vae.decode(s), mode))[0] d2 = (s - anchor).pow(2) tot = tot + (d2.mean(1) if GROUNDING_MEAN else d2.sum(1)).mean() return tot / max(len(states) - 1, 1) # -------------------------------------------------------------------------- # Monolithic baselines # -------------------------------------------------------------------------- class DiscMono(nn.Module): """Conditional VQ-VAE: the whole program is ONE quantised vector (LAPO/Genie).""" def __init__(self, vae: ConvVAE, n_codes=36, action_dim=16, d_ff=128, commitment=0.25): super().__init__() self.vae = vae sd = vae.state_dim self.infer = FiLMMLP(sd, sd, action_dim, d_ff) self.inf_norm = nn.LayerNorm(action_dim) self.transition = FiLMMLP(sd, action_dim, sd, d_ff) self.vq = VQ(n_codes, action_dim, commitment) nn.init.zeros_(self.transition.out.weight) nn.init.zeros_(self.transition.out.bias) def program(self, sx, sy): a = self.inf_norm(self.infer(sx, sy)) zq, idx, l = self.vq(a) return zq, idx, l def apply(self, sx, zq): return sx + self.transition(sx, zq) class ContMono(nn.Module): """Conditional beta-VAE: the program is ONE continuous vector (AdaWorld).""" def __init__(self, vae: ConvVAE, action_dim=16, d_ff=128, beta=0.01): super().__init__() self.vae = vae sd = vae.state_dim self.infer = FiLMMLP(sd, sd, 2 * action_dim, d_ff) self.transition = FiLMMLP(sd, action_dim, sd, d_ff) self.beta = beta self.action_dim = action_dim nn.init.zeros_(self.transition.out.weight) nn.init.zeros_(self.transition.out.bias) def program(self, sx, sy, sample=True): mu, lv = self.infer(sx, sy).chunk(2, dim=-1) lv = lv.clamp(-8, 8) z = mu + torch.randn_like(mu) * (0.5 * lv).exp() if sample else mu kl = (-0.5 * (1 + lv - mu.pow(2) - lv.exp())).sum(1).mean() return z, kl def apply(self, sx, z): return sx + self.transition(sx, z)