A platform that trains game-playing agents and NPC behaviour by neuroevolution, from a user's own environment, for people with no background in machine learning.
Evolvarium is a student-initiated undergraduate capstone project at the University of Windsor, carried out over two semesters. The first turns a single-game engine into one that trains any environment written to a common contract. The second builds the platform around it. It is in development.
The code starts as an exact copy of
Snake-AI v0.2.0, where that
project stopped. Only the name differs: the package snake_ai is now
evolvarium, and the command, dashboard title, default export name and model
format string follow it. The first commit is the baseline the project is
measured against, and everything after it is new work.
At the baseline the engine trained Snake and nothing else. Its best model, in
models/, averages 81.5 over 60 held-out games.
Python 3.10 or newer. On Windows on ARM, use the ARM64 build of Python. The x86-64 build runs under emulation and trains about a third slower.
pip install -e ".[dev]"
python -m evolvarium train --open
python -m pytestpython -m pytest -m slow replays all 60 held-out games of the model in
models/ and checks each game's score, length and how it ended against the
record in tests/data, then probes every game, broken or not, on the default
budget. It takes under six minutes. CI runs both on Linux, Windows, Windows on
ARM and macOS.
Every setting has a name. A game's are named by their path in its settings,
such as board.width for Snake, and the engine's by section, such as
evolution.population_size. python -m evolvarium settings lists them with
their values and the choices each one allows, and train sets any of them:
python -m evolvarium train --set board.width=12 network.hidden_layers=32,16 network.hidden_activations=relu,tanhA run checks its settings before it starts and reports every problem at once: a name that does not exist, with the closest one that does, a value of the wrong type, out of range or at odds with another setting, and a setting given by name that the others leave without effect.
Ctrl+C stops training after the generation in progress and saves it. A second
Ctrl+C drops that generation and quits. The dashboard follows the run through
GET /api/events, a server-sent event stream of each generation, record, hold
and checkpoint, which any other client can read as well:
curl -N http://127.0.0.1:8765/api/eventspython -m evolvarium serve --open opens the dashboard on every run in the runs
directory without training one. Runs are started there from a form of the
game's settings, checked as train checks them, and can be stopped, set side by
side and exported, choosing the exported genome by its average as export does.
--game picks the game the form starts on, and --set the values it starts
from:
python -m evolvarium serve --game package.module:Class --set evolution.population_size=120 --openpython -m evolvarium --help lists the other commands. The full reference for
the baseline is Snake-AI's
COMMANDS.md,
reading snake_ai there as evolvarium. Snake's own flags there, such as
--board and --spec, are settings now, set with --set.
The engine trains any game written to the contract in evolvarium/contract.py.
A game declares the inputs each agent sees, as numbers or categories, and the
actions it can take, as named options or numbers within a range. It resets from
a seed, takes an action for every agent each step, and says how each episode
ended and whether a higher or a lower score is better. The engine sizes the
network from that and turns its outputs back into the game's own actions.
Five games are built in and go by their short names, as in train --game arena.
Snake is in evolvarium/games/snake. The arena, in evolvarium/games/arena,
puts a team of agents with health on one floor to eat, heal and chase a scripted
rival that turns on them when they are hurt, and every agent plays the same
network. python -m evolvarium.games.arena.scripted plays hand-written teams on
the held-out seeds, the figures a trained team is measured against. Cart-pole,
in evolvarium/games/cartpole, keeps a pole upright on a cart by pushing the
cart along a track, and the network gives the push as a force rather than
picking a move. Its score is the number of steps the pole stayed up, out of 500
by default, and python -m evolvarium.games.cartpole.scripted does the same for
hand-written controllers.
Cyber defence, in evolvarium/games/cyber, is autonomous cyber defence of a
simulated enterprise network. Each seed draws a network of 12 to 18 hosts:
workstations, a web server, a few servers, a domain controller and a customer
database, each with its own firewall rules, cached credentials and flaws. An
intruder gets in by phishing or through the web server and works toward
stealing the database, or the copy on the backup server, or setting off
ransomware, by scanning, escalating its privileges, dumping credentials and
moving with them. Thrown out, it comes back by VPN with a password it stole
from a user whose VPN logons ask for no second factor, until the credentials
are reset, or with a new phishing campaign. A security
team of two analysts works a ranked queue of alerts, most of them false. For the
host it is handed, each analyst watches, dismisses, investigates, isolates,
releases or rebuilds it, resets the credentials or blocks the intruder's command
channel.
Investigating, isolating, rebuilding, resetting and blocking each cost something,
isolation and rebuilds take hosts out of service, and the score is what the
incident cost, so lower is better. Both analysts play the same network. python -m evolvarium.games.cyber.scripted plays hand-written defences on the held-out
seeds, the figures a trained team is measured against, beside two bounds that
read the truth of the incident.
The simulation is a small abstraction of a security team's decisions, not evidence about any real network. It leaves out:
- real protocols, packets, logs, vulnerabilities and tools: techniques are actions with chances of working and of being seen, and every chance, rate, duration and cost is chosen, not measured, with costs in units where the whole database is 100;
- alert types, correlation and threat intelligence: an alert has a severity, and a mark when it is a lead from a finding, and an investigation never reports an intruder that is not there;
- more than one intruder, worms, insiders and supply-chain attacks: there are three scripted intruders, which do not adapt;
- prevention, such as patching cycles, email filtering and a second factor anywhere but the VPN, and recovery beyond rebuilding a host, which understates what ransomware costs;
- networks of more than 18 hosts, and realistic false alert rates: each host raises far more than a real one, so a small network keeps two analysts busy and still leaves them time to investigate most hosts each day;
- incidents without an intruder: every one has one;
- a command channel per implant, and other hosts cut off from the internet: every implant shares one channel, and only the database cannot reach it;
- fatigue, shifts and handovers, legal reporting and the cost to reputation.
Water, in evolvarium/games/water, keeps contamination from a town's customers.
Each seed draws a pipe network of about 135 nodes with about one pipe for each.
Water flows one way, from a treatment works along a trunk of mains and out into
ten districts of 8 to 16 streets. Valves sit on the pipe into the first street of
every district, four mains and four other streets, sensors on eight mains and
streets, three streets serve a hospital or a school, and three pipes join a
street of one district to one of another. In three episodes in four a trunk main
breaks, and contaminated water gets in there for 12 to 36 steps and moves on one
pipe a step. Sensors alarm as it passes, contaminated streets complain, and some
alarms and complaints are false. Every valve is an agent, and each step it opens
or shuts. A shut valve keeps contamination from everything only it feeds and
leaves all of that without water. Each step a street is served contaminated
water costs its demand, each step it has none costs a tenth of that, and each
move of a valve costs half, so lower is better. Water has no inputs of its own:
the valves read the network through the network encoder, below. python -m evolvarium.games.water.scripted plays hand-written valves on dev seeds. It leaves
out hydraulics, so water moves a pipe a step whatever the pipe and nothing mixes
or decays; valves move at once; there is one break at most, always on a trunk
main, and no repair, flushing or notice to boil water; and every chance and cost
is chosen, not measured.
Any other game is named module:Class and imported from wherever Python finds
it, so train --game package.module:Class trains it and
settings --game package.module:Class lists its settings. A game can declare
the values a setting allows, check its settings against each other, and name
the ones that others leave without effect, and the run uses all three before it
starts. tests/test_contract.py trains one with two agents and a score that is
better lower.
A game's code plays under two time limits, limits.step_seconds for a step and
limits.episode_seconds for a whole episode, 10 s and 120 s by default. An
episode that runs over is played once more, since a busy machine can hold up a
step that is fine, and running over again ends the run with the step and seed
it happened on. An exception from the game ends it the same way, naming the
call it came from. With more than one worker, a worker that dies or stops
reporting while it scores is replaced and the genome played again on the new
one. A second worker lost on the same genome ends that run, and the dashboard
and any other runs carry on. train with evolution.workers=1 plays the game
in its own process and can only check the time after a step, so a step that
never returns hangs it there.
evolvarium/games/broken.py has each built-in game five more times, each with
one fault of the kind a game written in a hurry has: inputs far from zero in
units of their own, inputs that never change, inputs that copy others, no limit
on an episode's length, and episodes that ignore their seed. None is built in,
so a run names one in full, as in
train --game evolvarium.games.broken:DeadInputSnake.
The probe looks for those faults in any game before anything trains on it. Players that have learned nothing play the game, one at random, one repeating a single action, one holding each action for a while and untrained networks, on seeds from 600000 up. It takes about a second on cart-pole, under 10 s on the arena and under 35 s on Snake, and says what it measured and what it would do about it:
python -m evolvarium probe --game evolvarium.games.broken:DeadInputCartPole--set probe.enabled=true, on train or the dashboard's form, probes the game
before a run and trains on the game as fixed. It is off by default.
- An input reading beyond 8 either way, or barely moving for where it sits, is moved and scaled to read about -1 to 1. Inputs in range are left alone.
- An input that never changes is dropped, and so is one that only repeats another, even flipped or scaled. The network is sized from what is left.
- An input that only ever reads 3 to 8 whole numbers is taken for a code, such as a kind of tile, and gets one input per value, set to 1 for the value read, as a declared category does. A value play never showed reads as the nearest one it did.
- A game with an episode still going at
probe.ceilingsteps, 5,000 by default, gets a limit on steps with the score standing still, if its score moves often enough to tell, and a limit on all the steps of an episode. A game whose episodes all end by themselves gets no limit at all. - A game whose episodes a seed does not decide has its random generators seeded at the start of each one, wherever it keeps them. If that does not settle it, the report says so and the run goes ahead.
- Rewards in under 2% of episodes, and steps too slow for the time limits, are reported and left for the game's author.
A game with nothing wrong is played as it was written and trains the same as with
the probe off. The report is kept in the run's directory as probe.json, and the
dashboard shows it under Before training, beside how a sized run was sized. The
fixes go with its checkpoints and exported models, so a resumed run or a replay
reads the game as the run did. A game can define stop(stalled) to settle an
episode the probe's limits cut short, as the built-in games do. The players being
weak is also the probe's limit: an input that only moves or grows once a player
is good looks dead or well scaled to them.
--minutes, or sizing.minutes on the dashboard's form, fits a run to that much
time and ends it there:
python -m evolvarium train --game arena --minutes 5Untrained networks play a sample of games on the run's workers first, a few
seconds at most, and the run gets the largest of four sizes, from 50 genomes
playing 2 games each up to the defaults, that leaves time for
sizing.generations generations, 60 by default. A setting given by name stays as
given, and the size fits around it. The run ends before a generation that would
not fit, counting a probe and the sample but not time held for someone watching,
and a run carried on after a restart counts the time it had already spent. A
sized run is the same run as one given that size by hand.
A game on a grid can say what is on it instead of designing inputs. It declares
a grid, with its size, what each of its moves does and the kinds of thing on
it, such as food, and its view gives each agent's cell, the way it faces, the
cells it cannot enter, the ones that open after a few moves, as a body moving
out of the way does, and where the things are. The grid encoder in
evolvarium/grid.py builds the inputs from that, all relative to the way the
agent faces: which cells around it are blocked, how much of the grid each move
leaves within reach, which moves start a shortest way to the nearest thing of
each kind and where that thing lies, how much of the grid is blocked, and any
numbers no cell shows, such as health, as the view gives them. A game that moves
in fixed directions is steered by turns instead, from the way the agent last
moved.
A game with a grid and no inputs of its own always trains this way. Snake and
the arena have inputs of their own as well, and train on the grid when a run
asks for it. grid.radius is how many cells each way the agent sees, 1 by
default, and grid.horizon how many moves ahead the search looks, 32:
python -m evolvarium train --set grid.enabled=trueA game played on a network of nodes, such as hosts on an estate or streets on a
water main, can do the same. It declares a graph, naming the kinds of node,
the marks nodes hold, such as an alert or contamination, the numbers about an
agent's own node and those about the whole game, whether links go one way and
whether nodes fall into groups. Its graph_view gives each agent's node, which
nodes link to which, each node's kind and group, the nodes out of action and
where the marks are. The network encoder in evolvarium/graph.py builds the
inputs from that, all read from the agent's node: its kind; for each mark, its
value there, how much of it lies within graph.radius links into the node and
out of it, how many links it is to the nearest other node holding it upstream
and downstream, within graph.horizon links, how much of it the node's group
holds, and how many nodes hold it across the network; the nodes out of action
around it, in its group and across the network; and its links against the
network's mean. Nothing passes through a node out of action. No input belongs to
a numbered node, so a network can change size from one episode to the next. The
code says graph, since network is the policy network's section.
Water has only a network and always trains this way. Cyber defence has its own
inputs as well, and trains on its network when a run asks: each host's role and
zone, what reaches what, which hosts are out of service, and alert risk and
confirmed findings as marks, with 13 of its own inputs about the host in hand
and 8 about the incident passed through, 52 inputs against its own 31.
graph.radius is 1 by default and graph.horizon 8:
python -m evolvarium train --game cyber --set graph.enabled=trueA game that declares a scene can be watched on the dashboard. The scene lists
layers of cells, dots, boxes or lines and labels such as the score, and draw
returns each layer's items and each label's value after every step of a recorded
episode. The dashboard draws any game from that without running its code.
python -m evolvarium export, or the export panel on the dashboard, writes a
trained model as one JSON file: its weights, the names of its inputs in the
order the network reads them, each part of its actions and the game rules it
learned under.
evolvarium/player.py runs that file with the standard library alone, so it can
be copied next to a game that never installs Evolvarium:
from player import Player
player = Player.load("v3-seed99-gen155-81.json")
move = player.action(inputs) # "left", "straight" or "right"A game whose actions have several parts, such as a direction and a stride, gets a dict from part name to value, as the game received them in training.
A model of a game the probe changed still takes every input the game has. The
file says which of them the network reads, with the offset and scale of each and
any it reads as a code, and the player does the sums itself. A model trained on
the grid names the encoder's inputs and records its settings, so evaluate and
the dashboard play it as it trained, but the player needs those inputs given to
it.
The player's docstring describes the format. python -m evolvarium evaluate
scores a model file on the held-out games under the rules it records. With
torch installed, an export also writes a .pt copy.
- HISTORY.md: what changed after the baseline, and what it measured
- TODO.md: open work