Skip to main content

PyForgeAI

Ask DeepWiki Python 3.10+ PyTorch 2.0+ License: MIT

PyForgeAI is a modular, multi-backend game AI training and inference library built for Pygame and real-time Python simulations. Designed around the AIFactory, ITrainer, and IAIModel patterns, it unifies Neuroevolution (Genetic Algorithms) and Deep Q-Learning (Double-DQN) into a clean, zero-boilerplate package with automatic HUD activation tracking and backward-compatible checkpoint serialization.


Features

  • Unified Training Algorithms (Trainers):
    • GeneticTrainer (Neuroevolution): Elitism, multi-trial fitness averaging, uniform tensor crossover, adaptive mutation scaling on fitness stagnation, and periodic random diversity injection.
    • QLearningTrainer & DQNAgent (Deep Reinforcement Learning): Experience ReplayMemory, Double-DQN action evaluation, Huber/MSE loss, gradient clipping, and epsilon-greedy exploration decay.
  • Multi-Backend Neural Networks & Adapters (Models & Adapters):
    • Dynamic multi-layer perceptrons (SimpleNN_Pytorch & SimpleNN_Tensorflow) with configurable hidden_sizes and activation functions (relu, tanh, leaky_relu, elu).
    • Built-in normalized layer-1 activation capture (model.activations in [0, 1]) for real-time HUD neural network rendering, with a headless fast-mode toggle (record_activations=False).
    • PyTorchAdapter, TensorFlowAdapter, and MockAdapter implementing the unified IAIModel contract (predict, predict_action, predict_probabilities, get_weights, set_weights).
  • Flexible Environment Integration (Environments):
    • Works seamlessly with step-by-step Gym-like environments (IEnvironment), pure fitness callables (fn(model) -> float), or legacy Pygame loops (game.run_with_model() via GameFitnessBridge).
  • Smart Checkpoint Serialization (Serialization):
    • Automatic architecture metadata persistence and legacy layer remapping (fc1/fc2 $\rightarrow$ hidden_layers.*) via save_model, load_model, and configuration-driven AILoader.
  • Training Lifecycle Callbacks:
    • Built-in EarlyStoppingCallback, CheckpointCallback, and HistoryCallback.

Architecture

flowchart TD
    Factory["AIFactory"] --> Models["Models (SimpleNN_Pytorch / SimpleNN_Tensorflow)"]
    Factory --> Adapters["Adapters (PyTorchAdapter / TensorFlowAdapter / MockAdapter)"]
    Factory --> Trainers["Trainers (GeneticTrainer / QLearningTrainer)"]
    Factory --> Controller["AIController (Runtime Inference & Episodic DQN State)"]

    Trainers --> Env["Environments (IEnvironment / IFitnessEnvironment / GameFitnessBridge)"]
    Trainers --> Callbacks["Callbacks (EarlyStopping / Checkpoint / History)"]
    Controller --> Adapters
    Adapters --> Serializer["Serialization (save_model / load_model / AILoader)"]

Installation

From PyPI (once published)

pip install pyforgeai-engine

Local Editable Install (for development or local game projects)

pip install -e .

Optional TensorFlow backend support:

pip install -e ".[tensorflow]"

Quickstart

1. Neuroevolution (GeneticTrainer)

from pyforgeai import AIFactory, EarlyStoppingCallback, TargetSeekEnvironment, save_model

env = TargetSeekEnvironment(max_steps=80, seed=42)

factory = AIFactory({
    "type_model": "Pytorch",
    "input_size": env.state_size,
    "output_size": env.action_size,
    "hidden_sizes": [16, 16],
})

trainer = factory.create_GeneticTrainer(
    generations=50,
    population_size=20,
    elitism=2,
    num_trials=3,
    adaptive_mutation=True,
    diversity_interval=10,
    callbacks=[EarlyStoppingCallback(patience=10)],
)

result = trainer.train_with_result(env)
save_model(result.best_model, "AI/best_genetic_model.pth")

2. Deep Q-Learning (QLearningTrainer / DQNAgent)

from pyforgeai import AIFactory, TargetSeekEnvironment

env = TargetSeekEnvironment(max_steps=80)
factory = AIFactory({
    "input_size": env.state_size,
    "output_size": env.action_size,
    "hidden_sizes": [32, 32],
})

dqn_trainer = factory.create_QLearningTrainer(
    episodes=200,
    lr=1e-3,
    gamma=0.99,
    epsilon_start=1.0,
    epsilon_end=0.02,
    epsilon_decay=0.995,
    double_dqn=True,
    save_path="AI/best_dqn_model.pth",
)

result = dqn_trainer.train_environment_with_result(env)

3. Runtime Inference in Pygame (AIController)

from pyforgeai import AIController, load_model

model = load_model("AI/best_genetic_model.pth", "Pytorch")

controller = AIController(
    state_provider=lambda: game.get_observation_array(),
    action_dispatcher=lambda action_idx: game.apply_ai_action(action_idx),
)
controller.set_runtime_model(model)

# Inside your Pygame loop:
chosen_action = controller.select_action(deterministic=True)

Running the Showcase Demo & Unit Tests

Run the standalone training and inference showcase:

python demo_ai_training.py

Run the automated test suite:

python -m unittest discover -s tests -v

Build .whl and .tar.gz distributions for PyPI:

pip install build twine
python -m build
twine upload dist/*

License

This project is licensed under the MIT License.

Author

Developed by Drakonosinc

Metadata

Release files for pyforgeai-engine 1.0.0

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

Source distribution (sdist)

Source distribution for pyforgeai-engine 1.0.0
File Size Uploaded Provenance Actions
pyforgeai_engine-1.0.0.tar.gz 33.2 kB Without provenance Details for pyforgeai_engine-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pyforgeai-engine 1.0.0
File Interpreter ABI Platform Actions
pyforgeai_engine-1.0.0-py3-none-any.whl Python 3 none any Details for pyforgeai_engine-1.0.0-py3-none-any.whl

Total release size: 68.9 kB

Release files / pyforgeai_engine-1.0.0.tar.gz

Download URL pyforgeai_engine-1.0.0.tar.gz
Size 33.2 kB
Tags Source
SHA-256 checksum
How to use checksums
d68a488497a09457adaa094c8430809e288fcd44562ffa0ad50b5bb63ba3c613
BLAKE2b-256 checksum
How to use checksums
08809006e8806804cb9b5e6f139011050d384e94984d9ca2cd1431f7cb206b20
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.0

Release files / pyforgeai_engine-1.0.0-py3-none-any.whl

Download URL pyforgeai_engine-1.0.0-py3-none-any.whl
Size 35.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5ce73aa7129771c697430897f4ae5793a2b2f8e08172d878484f3f4e68d9016e
BLAKE2b-256 checksum
How to use checksums
1e4653060383ad2ee5ca7a7c3696014bbd721c8621b2adda8ec05b6665cdee10
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.0

Security for pyforgeai-engine 1.0.0

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.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

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