Skip to main content

NEATify

A modern, production-ready implementation of NEAT (NeuroEvolution of Augmenting Topologies) with PyTorch integration.

Features

Core Evolution

  • ✅ NEAT Algorithm: Complete implementation with speciation and innovation tracking
  • ✅ Dynamic Speciation: Automatic compatibility threshold adjustment
  • ✅ Advanced Mutations: Weight perturbation, topology mutations, activation mutations
  • ✅ Elitism: Preserve best genomes across generations
  • ✅ Configurable: Extensive hyperparameter control

PyTorch Integration

  • ✅ Efficient Inference: Convert genomes to PyTorch modules
  • ✅ Recurrent Networks: Full support for cyclic topologies
  • ✅ Sparse Mode: Optimized batch processing for large networks
  • ✅ Gradient Fine-Tuning: Register weights as nn.Parameter for hybrid evolution + learning
  • ✅ Bidirectional Sync: Update genomes with trained weights

Production Features

  • ✅ Checkpointing: Save/load population state
  • ✅ Serialization: JSON and Pickle export/import
  • ✅ Visualization: Species plots, genome graphs, complexity tracking
  • ✅ Benchmarks: XOR, LunarLander, function approximation
  • ✅ Hyperparameter Tuning: Grid and random search utilities

Installation

pip install neatify-ai

Quick Start

from neatify import Population, EvolutionConfig, NeatModule
import torch

# Configure evolution
config = EvolutionConfig()
config.population_size = 150
config.prob_add_connection = 0.3
config.prob_add_node = 0.1

# Create population
pop = Population(pop_size=150, num_inputs=2, num_outputs=1, config=config)

# Define fitness function
def fitness_fn(genomes):
    for genome in genomes:
        model = NeatModule(genome)
        # ... evaluate model ...
        genome.fitness = score

# Evolve
for generation in range(100):
    pop.run_generation(fitness_fn)
    best = max(pop.genomes, key=lambda g: g.fitness)
    print(f"Gen {generation}: Best fitness = {best.fitness:.4f}")

Examples

XOR Problem

python examples/xor_solve.py

LunarLander-v2

python examples/lunarlander_solve.py

Function Approximation

python examples/function_approx.py

Visualization Demo

python examples/visualization_demo.py

Hyperparameter Tuning

python examples/hyperparam_search.py --method random --trials 50

Hybrid Evolution + Learning

from neatify import NeatModule, Checkpoint
import torch.optim as optim

# 1. Evolve topology
pop.run_generation(fitness_fn)
best_genome = max(pop.genomes, key=lambda g: g.fitness)

# 2. Fine-tune weights with gradient descent
model = NeatModule(best_genome, trainable=True)
optimizer = optim.Adam(model.parameters(), lr=0.01)

for epoch in range(100):
    optimizer.zero_grad()
    output = model(input_data)
    loss = criterion(output, target)
    loss.backward()
    optimizer.step()

# 3. Sync weights back to genome
model.update_genome_weights()

# 4. Continue evolution with improved weights
pop.genomes[0] = best_genome
pop.run_generation(fitness_fn)

Checkpointing

from neatify import Checkpoint

# Save population state
Checkpoint.save(pop, "checkpoint_gen100.pkl")

# Load and resume
pop = Checkpoint.load("checkpoint_gen100.pkl")
pop.run_generation(fitness_fn)

# Save best genome
best = max(pop.genomes, key=lambda g: g.fitness)
Checkpoint.save_best(best, "best_genome.pkl")

# Export to JSON (human-readable)
Checkpoint.export_genome_json(best, "best_genome.json")

Visualization

from neatify.visualization import (
    plot_species_distribution,
    visualize_genome,
    plot_complexity_evolution
)

# Track evolution history
history = []
for gen in range(100):
    pop.run_generation(fitness_fn)
    history.append(copy.deepcopy(pop))

# Generate plots
plot_species_distribution(history, "species.png")
visualize_genome(best_genome, "network.png")
plot_complexity_evolution(history, "complexity.png")

Configuration

from neatify import EvolutionConfig

config = EvolutionConfig()

# Population
config.population_size = 150
config.elitism_count = 3
config.target_species = 5

# Mutations
config.prob_mutate_weight = 0.8
config.prob_add_connection = 0.3
config.prob_add_node = 0.1
config.prob_mutate_activation = 0.1

# Weight mutations
config.prob_replace_weight = 0.1
config.weight_mutation_power = 0.5
config.weight_perturbation_type = 'gaussian'  # or 'uniform'
config.weight_min_value = -30.0
config.weight_max_value = 30.0

# Speciation
config.compatibility_threshold = 3.0
config.c1 = 1.0  # Excess genes coefficient
config.c2 = 1.0  # Disjoint genes coefficient
config.c3 = 0.4  # Weight difference coefficient

Testing

Run all tests:

python tests/test_dynamic_threshold.py
python tests/test_elitism.py
python tests/test_weight_mutation.py
python tests/test_recurrent.py
python tests/test_activations_adapter.py
python tests/test_fine_tuning.py
python tests/test_weight_sync.py
python tests/test_checkpoint.py

Architecture

src/neatify/
├── core.py              # Genome, NodeGene, ConnectionGene
├── evolution.py         # Mutation operators, crossover, config
├── population.py        # Population management, speciation
├── pytorch_adapter.py   # PyTorch integration
├── checkpoint.py        # Save/load utilities
├── visualization.py     # Plotting functions
└── distributed/         # Distributed NEAT components

examples/
├── xor_solve.py         # Basic XOR solver
├── distributed_xor_*.py # Distributed XOR examples
├── lunarlander_solve.py # Continuous control
└── ...

tests/
├── test_*.py            # Unit tests
└── benchmark_batch.py   # Performance benchmarks

Performance

  • Sparse Mode: 3-5x faster for large, sparse networks
  • Batch Processing: Efficient GPU utilization
  • Checkpointing: Minimal overhead (~1% of evolution time)

Documentation

  • User Guide: Step-by-step tutorials, advanced usage, and best practices.
  • Walkthrough: Technical details and implementation history.
  • Examples: Practical demonstration scripts.

Citation

If you use NEATify in your research, please cite:

@software{neatify_ai_2025,
  title = {neatify-ai: Modern NEAT Implementation with PyTorch},
  year = {2025},
  url = {https://github.com/Supreme-Shrestha/neatify-ai}
}

License

MIT License - see LICENSE file for details.

Contributing

Contributions welcome! Please see CONTRIBUTING.md for guidelines.

Metadata

Release files for neatify-ai 0.1.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for neatify-ai 0.1.4
File Size Uploaded Provenance Actions
neatify_ai-0.1.4.tar.gz 34.5 kB Without provenance Details for neatify_ai-0.1.4.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for neatify-ai 0.1.4
File Interpreter ABI Platform Actions
neatify_ai-0.1.4-py3-none-any.whl Python 3 none any Details for neatify_ai-0.1.4-py3-none-any.whl

Total release size: 63.2 kB

Release files / neatify_ai-0.1.4.tar.gz

Download URL neatify_ai-0.1.4.tar.gz
Size 34.5 kB
Tags Source
SHA-256 checksum
How to use checksums
186f21c1d2133a09453c6d891c6711cda07d76e18a79f3f5bd1087b5a3c37e67
BLAKE2b-256 checksum
How to use checksums
dcebd03e767f11698fbc31bf7d597e9e400a0870243c4099448c21cff85428b8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.11

Release files / neatify_ai-0.1.4-py3-none-any.whl

Download URL neatify_ai-0.1.4-py3-none-any.whl
Size 28.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b04dfa1de7e5a87e8abdad877917351f355ac100ad40011227a06f5b660f4ed6
BLAKE2b-256 checksum
How to use checksums
10f277a4d2637e0317ac3a33701a5d5041b0c44b8586df8fc239f50b00530efc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.11

Security for neatify-ai 0.1.4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page