Evolutionary Algorithms & Genetic Neural Nets
🧬 Evolutionary Algorithms, Neuroevolution & Genetic Sandboxes
In simulation research (such as Karl Sims' virtual creatures or OpenAI's Evolution Strategies), neural networks can be trained without backpropagation or gradient descent.
Instead, a population of candidate agents is spawned in a Godot physics sandbox. The highest-performing individuals are selected to reproduce, passing their neural weights and topologies to the next generation via Crossover and Mutation.
🏛️ The Evolutionary Sandbox Loop
+-------------------------------------------------------------+
| 1. Population Generation (e.g. 50 Creature Agents) |
| - Each agent contains unique Neural Weights (Genome) |
+-------------------------------------------------------------+
│
(Spawn into Godot Arena)
▼
+-------------------------------------------------------------+
| 2. Physics Simulation & Fitness Evaluation (600 Ticks) |
| - Walkers: Fitness = Forward Distance Traveled |
| - Combat Arena: Fitness = Damage Dealt + Survival Time |
+-------------------------------------------------------------+
│
(Rank by Fitness Score)
▼
+-------------------------------------------------------------+
| 3. Selection, Crossover & Mutation |
| - Top 10% Elites survive unchanged (Elitism) |
| - Breed remainder: Child = ParentA * 0.5 + ParentB * 0.5 |
| - Add Gaussian noise to weights: w += Normal(0, sigma) |
+-------------------------------------------------------------+
│
(Next Generation)
▼
+-------------------------------------------------------------+
| 4. Loop to Generation N+1 (Emergent locomotion & combat) |
+-------------------------------------------------------------+
⚖️ Neuroevolution vs. Traditional Reinforcement Learning
| Feature | Neuroevolution (Genetic Algorithms) | Reinforcement Learning (PPO / DQN) |
|---|---|---|
| Gradient Requirement | Zero gradients needed: Works with non-differentiable physics, sharp jumps, and discrete events. | Requires smooth differentiable loss functions and autograd. |
| Reward Sparsity | Handles extremely sparse rewards (only needs a single scalar fitness at the end of a round). | Struggles with sparse rewards; requires dense reward shaping. |
| Exploration Style | Population-wide genetic diversity across distinct niches. | Local stochastic action noise around the current policy. |
| Parallelization | Embarrassingly parallel (simulate 100 agents on independent CPU cores or GPU instances). | Complex parallel trajectory collection and gradient synchronization. |
💻 Pure GDScript Neural Network for In-Engine Evolution
Below is a complete, self-contained Feed-Forward Neural Network written purely in Godot 4 GDScript, requiring zero external Python or C++ libraries. It runs directly inside Godot agents and supports crossover and Gaussian mutation:
# NeuralBrain.gd - Standalone Godot 4 Evolvable Neural Network
class_name NeuralBrain
extends RefCounted
var layer_sizes: Array[int] = [8, 16, 4] # [Inputs, Hidden, Outputs]
var weights: Array = [] # Array of 2D Arrays (Matrices)
var biases: Array = [] # Array of Arrays
func _init(layers: Array[int] = [8, 16, 4]) -> void:
layer_sizes = layers
_initialize_random_weights()
func _initialize_random_weights() -> void:
weights.clear()
biases.clear()
for i in range(layer_sizes.size() - 1):
var rows: int = layer_sizes[i + 1]
var cols: int = layer_sizes[i]
# Xavier/He uniform random weight initialization
var weight_matrix: Array = []
for r in range(rows):
var row: Array[float] = []
for c in range(cols):
row.append(randf_range(-1.0, 1.0))
weight_matrix.append(row)
weights.append(weight_matrix)
var bias_vector: Array[float] = []
for r in range(rows):
bias_vector.append(randf_range(-0.1, 0.1))
biases.append(bias_vector)
# Fast Forward Pass (Matrix Multiplication + Tanh Activation)
func predict(inputs: Array[float]) -> Array[float]:
var current_activations: Array[float] = inputs.duplicate()
for layer_idx in range(weights.size()):
var weight_matrix: Array = weights[layer_idx]
var bias_vector: Array[float] = biases[layer_idx]
var next_activations: Array[float] = []
for r in range(weight_matrix.size()):
var dot_sum: float = bias_vector[r]
var row: Array = weight_matrix[r]
for c in range(row.size()):
dot_sum += row[c] * current_activations[c]
# Tanh activation function (-1.0 to +1.0)
next_activations.append(tanh(dot_sum))
current_activations = next_activations
return current_activations
# Mutation: Adds Gaussian noise to random weights
func mutate(mutation_rate: float = 0.05, mutation_strength: float = 0.2) -> void:
for layer in weights:
for row in layer:
for c in range(row.size()):
if randf() < mutation_rate:
row[c] += randfn(0.0, mutation_strength)
# Crossover: Combines two parent brains into a child brain
static func crossover(parent_a: NeuralBrain, parent_b: NeuralBrain) -> NeuralBrain:
var child: NeuralBrain = NeuralBrain.new(parent_a.layer_sizes)
for l in range(parent_a.weights.size()):
for r in range(parent_a.weights[l].size()):
for c in range(parent_a.weights[l][r].size()):
child.weights[l][r][c] = parent_a.weights[l][r][c] if randf() > 0.5 else parent_b.weights[l][r][c]
return child
🏆 3. Genetic Sandbox Design Patterns
When building an evolutionary simulation in Godot:
- Fitness Stagnation (Premature Convergence):
- If one slightly effective agent dominates early, genetic diversity collapses.
- Solution (Speciation / Niches): Group creatures into species based on weight distance. Creatures only compete for survival within their own species cluster, allowing wild new experimental designs time to mature.
- Elitism: Always copy the top
highest-fitness creatures directly into the next generation with zero mutation. This guarantees that your maximum fitness curve is monotonically non-decreasing. - Behavioral Diversity (Novelty Search): Instead of rewarding raw performance, reward creatures for doing something different (e.g. discovering a new area of the map or using a novel joint oscillation frequency).
🔗 Related Notes
- Multi-Agent Reinforcement Learning & Self-Play Sandboxes — Competitive neural network combat and MAPPO.
- Sensory Perception & Spatial Grids for AI — Raycasts, sound fields, and sensory grids for sandbox agents.
- Reinforcement Learning & Game AI — Traditional policy gradient algorithms and Gym training.
- Machine Learning Hub — Master machine learning index.
- Game Development Hub — Central game development index.