AI/ML Neural Cellular Automata WebGL2 Morphogenesis PyTorch

Neural Cellular Automata (NCA) in WebGL2: Self-Healing Morphogenesis on the GPU


WebGL2 Ping-Pong FBO · Drag to slice/damage tissue and watch local regeneration
Live GPU Neural Cellular Automaton: every pixel runs an identical Sobel + Laplacian perception stencil followed by a learned $1\times 1$ MLP residual update with asynchronous stochastic masking.

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:

Differentiable Neural Cellular Automaton Update (Mordvintsev et al., 2020)
$$\mathbf{z}_{x,y} = \big[\mathbf{s},\; K_{\nabla x} * \mathbf{s},\; K_{\nabla y} * \mathbf{s},\; K_{\nabla^2} * \mathbf{s}\big] \in \mathbb{R}^{4C}$$ $$\mathbf{s}_{x,y}^{(t+1)} = \mathbf{s}_{x,y}^{(t)} + m_{x,y}^{(t)} \cdot W_2\,\mathrm{ReLU}\big(W_1 \mathbf{z}_{x,y} + \mathbf{b}_1\big), \qquad m_{x,y}^{(t)} \sim \mathrm{Bernoulli}(p)$$

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()
Two NCA Training Footguns: (1) Always zero-initialize 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.
PropertyGray–Scott PDENeural Cellular Automaton (NCA)
Local OperatorHand-crafted 2-species Laplacian + $uv^2$Learned $1\times 1$ MLP over Sobel + Laplacian features
State Channels2 scalars ($u, v$)4–16 channels (visible RGB$\alpha$ + hidden morphogens)
Self-HealingRegrows generic texture onlyRegenerates global asymmetric anatomy via attractor basin
GPU Cost (WebGL2)1 FBO pass1–2 RGBA16F ping-pong passes at 60 FPS