Neural Cellular Automata (NCA) in WebGL2: Self-Healing Morphogenesis on the GPU
In How the Leopard Got Its Spots at 60 FPS, two hand-crafted PDEs (Gray–Scott) generated spots and stripes from local diffusion. Neural Cellular Automata (NCA) (Mordvintsev et al., Distill 2020; Self-Organising Textures, 2021) replace the hand-crafted reaction term with a tiny neural network (~8,000 parameters) shared identically by every cell on a 2D grid. Even more remarkably, the entire inference loop maps natively to a WebGL2 fragment shader.
1. Local Perception + Learned Residual Update
Each cell at coordinate $(x, y)$ holds a $C$-channel state vector $\mathbf{s}_{x,y}^{(t)} \in \mathbb{R}^C$ (typically $C = 16$: RGB, an alive mask $\alpha$, and 12 hidden morphogen channels). One NCA tick applies fixed spatial perception kernels ($K_{\text{id}}, K_{\nabla x}, K_{\nabla y}, K_{\nabla^2}$) per channel, concatenates them into a $4C$-dimensional perception vector $\mathbf{z}$, and feeds $\mathbf{z}$ through a $1\times 1$ two-layer MLP:
The stochastic mask $m_{x,y}^{(t)} \in \{0, 1\}$ is crucial: biological cells have no global clock. By updating only $p = 50\%$ of cells at random each tick, the learned rule cannot cheat by relying on synchronous parity oscillations and instead converges to a genuine continuous-time PDE attractor.
2. Pool-Based Sample Replay & Damage Training in PyTorch
If you only train an NCA for $T \in [64, 96]$ steps from a single seed pixel, the pattern will grow and then explode at $t = 200$. The trick from Distill is a sample pool of 1,024 evolved states: at every training step, replace the highest-loss sample with a fresh seed, punch circular holes in 2–3 samples from the pool, roll them forward $64$–$96$ steps, and backpropagate through time (BPTT):
PyTorch Implementation: NeuralCA Module with Sobel/Laplacian PerceptionPyTorch
import torch
import torch.nn as nn
import torch.nn.functional as F
class NeuralCA(nn.Module):
def __init__(self, channels: int = 16, hidden: int = 128):
super().__init__()
self.channels = channels
self.w1 = nn.Conv2d(channels * 4, hidden, kernel_size=1)
self.w2 = nn.Conv2d(hidden, channels, kernel_size=1, bias=False)
nn.init.zeros_(self.w2.weight) # do-nothing identity initialization
# Fixed depthwise perception filters: identity, Sobel-X, Sobel-Y, 9-pt Laplacian
k_id = torch.tensor([[0, 0, 0], [0, 1, 0], [0, 0, 0]], dtype=torch.float32)
k_gx = torch.tensor([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=torch.float32) / 8.0
k_gy = k_gx.T
k_lap = torch.tensor([[1, 2, 1], [2, -12, 2], [1, 2, 1]], dtype=torch.float32) / 16.0
filters = torch.stack([k_id, k_gx, k_gy, k_lap])[:, None, :, :]
self.register_buffer("filters", filters.repeat(channels, 1, 1, 1))
def perceive(self, x: torch.Tensor) -> torch.Tensor:
return F.conv2d(x, self.filters, padding=1, groups=self.channels)
def forward(self, x: torch.Tensor, fire_rate: float = 0.5) -> torch.Tensor:
pre_alive = F.max_pool2d(x[:, 3:4], 3, stride=1, padding=1) > 0.1
dx = self.w2(F.relu(self.w1(self.perceive(x))))
mask = (torch.rand_like(x[:, :1]) <= fire_rate).float()
x = x + dx * mask
post_alive = F.max_pool2d(x[:, 3:4], 3, stride=1, padding=1) > 0.1
return x * (pre_alive & post_alive).float()
w2.weight so the initial automaton is an exact identity map; random weights blow up exponentially over 96 unrolled BPTT steps. (2) Normalize parameter gradients per tensor (g /= g.norm() + 1e-8) rather than global clipping – recurrent spatial Jacobians have wildly different spectral norms across w1 and w2.
| Property | Gray–Scott PDE | Neural Cellular Automaton (NCA) |
|---|---|---|
| Local Operator | Hand-crafted 2-species Laplacian + $uv^2$ | Learned $1\times 1$ MLP over Sobel + Laplacian features |
| State Channels | 2 scalars ($u, v$) | 4–16 channels (visible RGB$\alpha$ + hidden morphogens) |
| Self-Healing | Regrows generic texture only | Regenerates global asymmetric anatomy via attractor basin |
| GPU Cost (WebGL2) | 1 FBO pass | 1–2 RGBA16F ping-pong passes at 60 FPS |