Tensorized NEAT and HyperNEAT neuroevolution on EvoX Compiler. Evolves neural network structures and weights with batched computation.
TensorNEAT 0.2.0 — NEAT / HyperNEAT neuroevolution on the
EvoX Compiler (evoxc). No JAX, no PyTorch.
TensorNEAT @ GECCO 2024
TensorNEAT received the GECCO 2024 Best Paper Award (NE track). Many thanks to everyone who has been supporting TensorNEAT.
What changed in 0.2.0
The computation layer is the EvoX Compiler (evoxc), not JAX.
| 0.1.x | 0.2.0 (this tree) | |
|---|---|---|
| Compute layer | jax.jit + jax.vmap |
evoxc graphs |
| Execution | XLA, traced per call | @evoxc.defn graph built once, then exe(...) per generation on a switchable backend |
| Default backend | JAX (CPU/GPU) | "numpy" reference interpreter (always available); "iree", "xla", "tvm" opt-in |
| Runtime deps | jax, brax, gymnax, jaxopt, optax, flax, mujoco, mujoco-mjx |
evoxc, numpy, networkx, matplotlib, sympy |
import tensorneat |
pulls in JAX | pulls in no jax / torch / brax / gymnax / mujoco (release-gate test) |
The NEAT idea is unchanged. Irregular network topologies are tensorized into fixed-shape arrays so a whole population of differently-shaped networks is evaluated at once, with the population on axis 0 of every tensor. What changed is the engine: a graph is traced with @evoxc.defn, handed to evoxc.build(backend=..., **options), and the resulting executable is reused for every generation of a given shape, instead of being jax.jit/vmap-traced.
Everything else is preserved from the pre-rewrite library and pinned by test/parity/ against the frozen JAX implementation in benchmarks/legacy_jax: the gene encoding, the NaN padding semantics (an unconnected node value is NaN, a NaN fitness becomes -inf), speciation and distance kernels, and deterministic per-seed runs ((seed, config, shape) reproduces a trajectory, because all randomness is evoxc.random stateless keys).
Quickstart (60 seconds)
git clone --branch evoxc https://gitlab.com/emi-lab/tensorneat.git
cd tensorneat
python -m pip install "evoxc @ git+https://gitlab.com/emi-lab/evox-compiler.git@fe85a534192f749a97b2f6e3b13b0800f69b8d90" numpy networkx matplotlib sympy
python -m pip install --no-deps -e .
python examples/func_fit/xor.py
Run these commands in a Python 3.11+ virtual environment. The GitLab default branch is evoxc (TensorNEAT 0.2.0). This recipe preserves the compiler revision used by the recorded examples; the compiler pin and the reason for --no-deps are explained under Install.
Real output from one run of this checkout (first generation, one middle generation, and the report tail — the run prints one such block per generation; the compile time and the per-generation Cost time move by a few tens of ms between runs, the fitness and topology numbers do not):
compile finished, cost time: 0.285115s
Generation: 1, Cost time: 41.80ms
fitness: valid cnt: 200, max: -0.2503, min: -0.4789, mean: -0.3197, std: 0.0536
node counts: max: 4, min: 3, mean: 3.06
conn counts: max: 4, min: 1, mean: 2.02
species: 1, [200]
...
Generation: 40, Cost time: 52.34ms
fitness: valid cnt: 200, max: -0.0434, min: -0.5115, mean: -0.2336, std: 0.1138
node counts: max: 7, min: 3, mean: 5.18
conn counts: max: 10, min: 1, mean: 6.95
species: 8, [53, 38, 29, 26, 22, 17, 11, 4]
...
Generation: 67, Cost time: 47.06ms
fitness: valid cnt: 200, max: -0.0009, min: -0.5536, mean: -0.2148, std: 0.1719
node counts: max: 7, min: 3, mean: 5.12
conn counts: max: 12, min: 2, mean: 7.80
species: 7, [56, 41, 35, 28, 20, 14, 6]
Fitness limit reached!
input: [0. 0.], target: [0.], predict: [0.02215577]
input: [0. 1.], target: [1.], predict: [0.9849813]
input: [1. 0.], target: [1.], predict: [0.9658409]
input: [1. 1.], target: [0.], predict: [0.03987563]
loss: 0.0008683378109708428
final loss: 8.68e-04 after 67 generations
That is the whole quickstart: seed 42 converges at generation 67 in 4.2-4.6 s on this box (two fresh runs), so the demo budget is pop 200 with at most 150 generations and fitness_target=-1e-3 (fitness_target is in fitness space and fitness is maximised, so "error below 1e-3" is -1e-3).
The script itself is examples/func_fit/xor.py, 41 lines including comments; a real run raises pop_size into the thousands and the generation limit into the hundreds.compile finished is the one-off evoxc build of the generation graph: Pipeline.setup() only prepares host state, the build happens inside the first step (that is, inside auto_run), and the resulting executable is then reused for every generation of that shape.
After evolution the best individual is available host-side, with no graph involved (pipeline is the one built by examples/func_fit/xor.py):
state = pipeline.setup() # host-only; no graph is built yet
state, best = pipeline.auto_run(state) # builds the graph on the first step, then evolves
pipeline.show(state, best) # prints the best network's I/O behaviour
# `best` is a ONE-INDIVIDUAL BATCH; network_dict takes it as a single argument.
network = pipeline.algorithm.genome.network_dict(state, best)
print(sorted(network))
print(len(network["nodes"]), "nodes,", len(network["conns"]), "connections")
['conns', 'nodes', 'topo_layers', 'topo_order', 'useful_nodes']
4 nodes, 5 connections
network_dict(state, payload), repr(state, payload), sympy_func(state, network, ...) and visualize(network, ...) are host-only methods on the genome instance (pipeline.algorithm.genome, a DefaultGenome here — tensorneat.genome has no module-level visualize/sympy_func): they read one individual's payload and never feed back into a graph. tensorneat.__version__ is "0.2.0" in an installed checkout ("0.0.0" outside one).
Architecture
One generation is one evoxc graph: split randkey -> ask -> transform -> problem.evaluate -> tell.
genome / algorithm / problem kernels src/tensorneat/genome, algorithm, problem
│ all tensor ops are written as batch-first graph code
▼
@evoxc.defn (or a plain closure) traced once, with host config baked in as constants
│
▼
evoxc.build(fn, *TensorSpec, backend=..., **options) ← the compile site
│ backend="numpy" reference interpreter, always available
│ backend="iree" StableHLO export + iree-compile (llvm-cpu)
│ backend="xla" StableHLO export + PJRT plugin .so (auto-discovered)
│ backend="tvm" opt-in extra
▼
evoxc.Executable cached in Pipeline._executables[(pop_size, max_nodes, max_conns,
max_in_degree, max_depth, key_span)]
│
▼
exe(randkey, node_keys, node_attrs, conn_keys, conn_attrs, generation, *species_leaves)
│ once per generation:
│ Pipeline.step -> evoxc.run(executable, state.randkey, *state.pop,
│ state.generation, *evoxc.tree_leaves(state.species))
│ returns [randkey, generation, *pop, *species, fitness, max_overflow]
▼
host code: logging, checkpointing, early stop (no eager mode: all numerics are inside the graph)
- Batch-first. Axis 0 is the population
Pfor every kernel; datasets/episodes are tiled over that axis by the problem (P * samples,P * repeats) and the schedule is repeated to match. - Static shapes.
pop_size,max_nodesandmax_connsare fixed when the graph is built, so an executable is valid for exactly one shape signature; changing any of them builds a second executable (Pipelinecaches by signature, seetest/integration/test_shape_rebuild.py). Shapes are never silently resized. - Split gene payload. One individual is four arrays:
node_keys (P, N) int32,node_attrs (P, N, A) float32,conn_keys (P, E, K) int32,conn_attrs (P, E, W) float32. Structural identity lives in the int32 keys (so it is exact), parameters live in the float32 attributes (so they are differentiable). - Host only orchestrates. Configuration, RNG keys and the tensors live in the immutable
Statecontainer; construction validates and prints nothing. No numerical work happens on the host — not even in logging (it goes throughtensorneat.common.tools.to_numpy). - No fallback. An unsupported backend, dtype, shape or op raises the backend's own error (
evoxc.core.errors.BackendError,TensorNEATErrorfor configuration); nothing silently switches to another backend.
Portability rules every kernel respects
These come from the StableHLO v1 exporter and from what the compiled backends accept; they are enforced by construction in src/:
scatteris rank-1axis=0or a rank-2 full row/column write — never a rank >= 3 operand.- One prepared index block feeds exactly one
scatter; merge payloads into a wider buffer instead. - No unsigned dtype in an exported generation graph: same-width signed carriers (two's complement keeps arithmetic bit-identical) plus one explicit sign flip (
bitwise_xor(v, INT64_MIN)) wherever unsigned order matters. The onlyuint32a graph produces is the digestGenome.hashreturns, from a standalone helper no generation graph calls, so it never reaches a compiled artifact. - No op the StableHLO v1 exporter defers. The gate is
evoxc.backends.stablehlo.ops.status(op.name) != "deferred", which covers two disjoint sets: every name inevoxc'sDEFERRED_OPS(runtime_call,external_call,block_call,rank,world_size,erf,gelu,diagonal,cholesky,qr,matrix_rank,svd,matrix_exp,random_multinomial, plus the 16sparse_*/dense_dot_sparsenames, numpy-backend-only in v1) and every op the exporter has no mapping for at all (call,tril,triu,cumsum,cumprod,flip,roll,nan_to_num,solve, ...). Use a static constant, a static-indexgather, or a log2-doubling fold. Spellings matter, because the deferral is keyed on the graph op name: evoxc spellswhereasselectand convolution asconv(both v1), andscan/while_loopare frontend loop constructs that trace to awhileregion (v1), so the shipped kernels use them freely —where,convolutionandscanare simply not evoxc op names. - Static dims only, non-negative axes only (a negative
concatenateaxis is legal at the frontend and rejected byiree-compile).
The evidence for each rule, including the exact failures that forced it, is in benchmarks/BACKENDS.md; the per-module rules live in the CONTEXT.md chain under src/tensorneat/common/, src/tensorneat/algorithm/neat/, src/tensorneat/algorithm/hyperneat/, src/tensorneat/genome/ and src/tensorneat/genome/operations/.
Features that actually exist
Every item below is backed by a file in this tree and, where a test exists, by that test.
- Batched topology inference — a whole population of different topologies in one forward pass (
genome/step.py,genome/grad.py;test/unit/genome/test_forward.py). - Gradient descent through evolved topologies —
genome.BaseGenome.grad(...)is a graph factory returning anevoxc.Graphthat maps(node_keys, node_attrs, conn_keys, conn_attrs, inputs)to gradients w.r.t. the float attribute tensors;loss_fnis scalarised assum(loss_fn(outputs))becauseevoxc.gradneeds one scalar output (src/tensorneat/genome/grad.py). The differentiated pass is a dense-weight twin of the window forward, because evoxc transposesgatherwith put semantics and would keep only one cotangent where a node fans out. The host-side convenience wrapper isgenome.DefaultGenome.grad_from_payload(state, payload, inputs, loss_fn)(theBaseGenomeHostmixin insrc/tensorneat/genome/host.py): it derives the schedule on the host, builds and compiles the gradient graph and returns(node_attr_grads, conn_attr_grads)for one batch-first payload. Verified against central finite differences intest/unit/genome/test_grad.pyand against the legacy JAX gradients intest/parity/test_grad.py; the runnable reference isexamples/interpret_visualize/grad_descent.py, which differentiates one evolved topology and checks the result against finite differences. - HyperNEAT with substrates —
algorithm.HyperNEAT(recurrent,activate_timetick-unroll) andHyperNEATFeedForwardoverMLPSubstrate, plusFullSubstrate(algorithm/hyperneat/, examplesxor_hyperneat*.py). - Recurrent genomes —
genome.RecurrentGenomewith a staticactivate_timeunroll (genome/recurrent.py). - Speciation and distance kernels — compatibility distance with node/connection gene digests, species assignment, stagnation, spawn allocation (
algorithm/neat/species.py,genome/operations/distance/). - Visualization —
pipeline.algorithm.genome.visualize(network, save_path=...)(a genome instance method) draws the decoded topology to SVG via matplotlib (examples/interpret_visualize/visualize_genome.py). - Sympy formula + Python code generation —
pipeline.algorithm.genome.sympy_func(state, network, ...)(again an instance method, and it needs theState) returns an 8-tuple consumed byto_python_code/to_latex_codefromtensorneat.common.sympy_tools(examples/interpret_visualize/genome_sympy.py).RecurrentGenomerefuses it by design: a cyclic network has no closed form. - Three RL problems, all simulator-free —
problem.CartPole(discrete, fixedmax_stephorizon, return as fitness),problem.Pendulum(continuous torque, the logit squashed inside the problem asmax_torque * tanh(logit), a hidden layer needed to learn quickly) andproblem.MountainCarContinuous(continuous force at the Gym-faithful 999-step default, one-time goal bonus). Fitness is the return (mean overrepeat_times) in all three. Two documented caveats:MountainCarContinuoushas a bang-bang idle optimum — a stationary policy scores ≈−0.00and never reaches the goal, so its demo budget cannot "solve" it — andPendulum.show"runs its own graph of one individual ... and reads both the return and the final observation out of the rollout carry" fromstate.randkey, a different reset key from any training episode, so on seed 42 its printed return (-595.12) is a different measurement from the training fitness (-271.30), not a contradiction.examples/rl/cartpole.pyreaches 200/200 steps at pop 200 on CPU. - Checkpointing —
Pipeline(..., is_save=True, save_dir=...)writesconfig.txt,log.txt,genomes/<generation>.npzper generation andgenomes/best_genome.npz(verified: 2 generations →genomes/1.npz,genomes/2.npz,genomes/best_genome.npz).test/integration/test_checkpoint.pyround-trips it. - Deterministic per-seed runs — all randomness is
evoxc.randomkeys created fromseed; the same(seed, config, shape)reproduces a run (test/integration/test_determinism.py). - Per-genome activation/aggregation menus —
node_gene=genome.BiasNode(activation_options=[...], aggregation_options=[...])takes plain callables; the built-in registries areACT(12 options:scaled_sigmoid,sigmoid,scaled_tanh,tanh,sin,relu,lelu,identity,inv,log,exp,abs) andAGG(sum,product,max,min,maxabs,mean). There is no globalACT.add_funcregistry any more. - Shape-signature rebuild and population chunking — a new
(P, max_nodes, max_conns, ...)builds a new executable;NEAT(pop_batch_size=...)runs crossover/mutation asevoxc.scanchunks to cut peak memory.
Not in the library any more (they required JAX): the Brax/Gymnax/mujoco RL environments, and the EvoX 1.x algorithm/monitor adaptor.
Backends
backend= is forwarded verbatim to evoxc.build; compile_options is expanded into its **options; nothing falls back — a backend that cannot run a kernel raises.
| backend | install | measured here |
|---|---|---|
numpy |
none — the default | the evoxc reference interpreter: the only leg with no optional dependency and the fastest CPU leg (benchmarks/RESULTS.md) |
iree |
uv sync --extra iree — iree-base-compiler / iree-base-runtime 3.13.x (3.10/3.11 abort in the ROCm/HIP HAL on any while/scan loop and SIGSEGV iree-compile on a while-nested cond; 3.13 fixes both) |
llvm-cpu is 1.54× / 5.47× / 6.63× slower per generation than numpy at pop 100/500/1000, with one 8.0–9.6 s iree-compile per static shape (benchmarks/BACKENDS.md); on the AMD Instinct MI300X (ROCm 7.1, gfx942) with compile_options={"target_backends": ["rocm"]} and device="rocm" it runs every shipped case at xor_p100 9.9, xor_p500 11.9, xor_p1000 14.2, xor3d_p500 12.0, custom_pagie_p500 14.8 and cartpole_p100 59.0 ms/generation (benchmarks/GPU.md) |
xla |
uv sync --extra xla-rocm — jax-rocm7-pjrt (ROCm; NVIDIA would use jax-cuda12-pjrt, and no CPU PJRT plugin is pip-installable). The plugin lands at <site-packages>/jax_plugins/xla_rocm7/xla_rocm_plugin.so and evoxc discovers an installed jax_plugins/*/*_plugin.so itself (plugin_path or EVOXC_PJRT_PLUGIN pins a different one). A long while (the RL rollout) can SIGSEGV the ROCm plugin inside PJRT_LoadedExecutable_Execute, whose FUSION command buffer replays the loop as a HIP graph; XLA_FLAGS=--xla_gpu_enable_command_buffer=WHILE removes it at no measurable cost |
the fastest accelerator leg: xor_p100 3.6, xor_p500 3.9, xor_p1000 4.1, xor3d_p500 3.9, custom_pagie_p500 5.3 and cartpole_p100 23.6 ms/generation — 2.50–3.51× faster than iree on the same device and 4.14–154.20× faster than the numpy leg, with a 2.24–2.79 s compile per shape (benchmarks/GPU.md) |
tvm |
uv sync --extra tvm |
opt-in extra, untested on this box |
Getting iree to run took five exporter/compiler gates (rank-3 scatter, unsigned dtypes, v1-deferred ops, one shared index block iree-compile could not legalize, and a negative concatenate axis); each failure and the fix that removed it is recorded in benchmarks/BACKENDS.md.
Running on an accelerator
import os
from tensorneat import Pipeline, algorithm, genome, problem
g = genome.DefaultGenome(num_inputs=2, num_outputs=1, max_nodes=50, max_conns=100)
algo = algorithm.NEAT(genome=g, pop_size=100, species_size=20, survival_threshold=0.01)
prob = problem.XOR()
# xla on ROCm: the PJRT C API plugin is a .so loaded over ctypes (no `jax` import).
# evoxc finds an installed jax_plugins/*/*_plugin.so on its own; this pins one explicitly.
plugin = "<site-packages>/jax_plugins/xla_rocm7/xla_rocm_plugin.so"
# A long `while` (the RL rollout) needs the ROCm plugin to skip HIP-graph capture.
os.environ["XLA_FLAGS"] = "--xla_gpu_enable_command_buffer=WHILE"
pipe = Pipeline(algo, prob, backend="xla", device="rocm",
compile_options={"plugin_path": plugin})
# or iree compiled for the same device
pipe = Pipeline(algo, prob, backend="iree", device="rocm",
compile_options={"target_backends": ["rocm"]})
Pipeline.setup() still runs its host-side graphs on CPU (the device-selecting keys are stripped for that phase); the runtime tensors are placed on the device once afterwards, and only the reported values come back to host.
The full numpy / iree / xla matrix over six cases, with its protocol and 14-generation lockstep traces, is benchmarks/GPU.md.
Leave compile_options at the default (or opt_level="O0"/"O1") and expect a recompile on every shape change: O2/O3 now SIGSEGV inside iree-compile (surfaced as a BackendError, never a fallback), and test/backends skips cleanly without the extra.
Performance
Honest state: on CPU, with the numpy reference interpreter, the rewrite is not uniformly faster per generation than the frozen pre-rewrite JAX implementation. The table is the generated harness record in benchmarks/RESULTS.md, rendered from benchmarks/results/authoritative.json, measured on the merged tree 63f0fc67 (3 repeats, seeds 42/43/44, JAX 0.10.2, 150 timed generations after 3 warmup, one process per run, on a shared 20-core INTEL Xeon Platinum 8568Y+ — other jobs ran concurrently, so the per-repeat spread is the honest uncertainty and a median alone would hide it).
Its verdict is FAIL, and nothing below is a uniform CPU win.
| case | pop | legacy JAX ms/gen | this library (numpy) ms/gen |
speed-up (old / new) |
|---|---|---|---|---|
xor_p100 |
100 | 38.87 | 41.42 | 0.94× (new slower) |
xor_p500 |
500 | 308.49 | 119.02 | 2.59× (new faster) |
xor_p1000 |
1000 | 809.34 | 199.16 | 4.06× (new faster) |
xor3d_p100 |
100 | 24.63 | 36.02 | 0.68× (new slower) |
xor3d_p500 |
500 | 105.63 | 127.98 | 0.83× (new slower) |
xor3d_p1000 |
1000 | 226.66 | 212.41 | 1.07× (new faster) |
custom_pagie_p500 |
500 | 480.21 | 1258.04 | 0.38× (new slower) |
cartpole_p100 |
100 | n/a (no old-side equivalent) | 307.16 | n/a |
The numpy interpreter is 2.59× (xor_p500) and 4.06× (xor_p1000) faster than the frozen JAX side, 1.07× on xor3d_p1000, and slower on xor_p100 (0.94×), xor3d_p100 (0.68×), xor3d_p500 (0.83×) and custom_pagie_p500 (0.38×: 1258.04 vs 480.21 ms/gen); cartpole_p100 is new-only at 307.16 ms/gen.
On the accelerator the same cases take 3.6–23.6 ms/generation through xla, i.e. 4.14–154.20× faster than the numpy reference, 2.50–3.51× faster than iree on the same device and 1.48–2.60× faster than the frozen JAX implementation measured on that same device.
The batch forward pass
The forward pass is where the rewrite's advantage is largest, because the pre-rewrite implementation evaluated it as lax.fori_loop(0, max_nodes, ...) with a per-node lax.cond and a vmap over every connection, while this library runs one tensorized level sweep over the whole population. Measured on one process, median of 20 passes after 3 warmups, on the merged tree (benchmarks/results/forward.json, rendered in benchmarks/FORWARD.md):
| forward workload | rows | legacy JAX ms | numpy ms |
iree ms |
xla ms |
JAX ÷ xla |
JAX ÷ iree |
|---|---|---|---|---|---|---|---|
xor_p100 × 4 samples |
400 | 1.382 | 2.950 | 1.498 | 0.419 | 3.30× | 0.92× |
xor_p500 × 4 |
2 000 | 1.566 | 11.316 | 1.701 | 0.481 | 3.25× | 0.92× |
xor_p1000 × 4 |
4 000 | 1.661 | 19.975 | 1.663 | 0.497 | 3.34× | 1.00× |
xor_p100 × 500 |
50 000 | 3.430 | 94.724 | 1.885 | 0.745 | 4.60× | 1.82× |
xor_p500 × 500 |
250 000 | 7.681 | 561.243 | 2.892 | 1.326 | 5.79× | 2.66× |
xor_p1000 × 500 |
500 000 | 14.238 | 1 094.888 | 3.867 | 2.229 | 6.39× | 3.68× |
| CartPole policy forward | 100 | 1.383 | 1.801 | 1.177 | 0.450 | 3.07× | 1.18× |
The gap widens with the number of rows: the legacy side re-runs its max_nodes-step loop per individual call, while the tensorized sweep amortises each level's dispatch over the whole batch. The CPU reference interpreter wins only on the 400-row row, where its numpy kernel bodies are cheap and the accelerator's launch floor dominates.
The CartPole row is the one that matters in practice: a rollout re-invokes the policy forward at every timestep, so its 3.07× is paid max_step times per generation.
Run on the device instead of the CPU, the frozen forward is unchanged (it is dispatch-bound: 1.382→1.435 ms at 400 rows, 7.681→7.366 at 250 000), so the same-device forward gap is 3.20×–6.17× (benchmarks/results/forward_jax_rocm_2026-11-07.json).
Against the frozen JAX implementation, on the same device
The pre-rewrite implementation is in-tree and JAX runs on the MI300X through the same PJRT plugin the xla leg uses (JAX_PLATFORMS=rocm, jax/jaxlib 0.10.2, device asserted per row as rocm:0 / AMD Instinct MI300X), so old and new are timed on one device in one protocol (seed 42, 3 warmup + 20 timed generations, one process per row, compile excluded; benchmarks/results/jax_rocm_2026-11-07.json, rendered in benchmarks/GPU.md):
| case | frozen JAX ms/gen | xla ms/gen |
iree ms/gen |
old ÷ xla |
old ÷ iree |
old JAX compile s | xla build s |
|---|---|---|---|---|---|---|---|
xor_p100 |
5.338 | 3.599 | 9.867 | 1.48× | 0.54× | 6.904 | 2.243 |
xor_p500 |
10.089 | 3.883 | 11.863 | 2.60× | 0.85× | 6.742 | 2.431 |
xor_p1000 |
10.511 | 4.054 | 14.215 | 2.59× | 0.74× | 6.554 | 2.617 |
xor3d_p500 |
9.196 | 3.876 | 12.004 | 2.37× | 0.77× | 6.803 | 2.510 |
custom_pagie_p500 |
12.710 | 5.276 | 14.751 | 2.41× | 0.86× | 6.860 | 2.785 |
xla beats the frozen implementation on all five shared cases (1.48–2.60×) and compiles 2.46–3.08× faster, so there is no per-generation-versus-compile trade to weigh; iree is slower than the frozen implementation here (0.54–0.86×), a per-dispatch overhead result rather than a numerical one.
cartpole_p100 has no old side — the pre-rewrite RL problems required brax/gymnax/mujoco — and the two sides come from two sessions on one shared device rather than an interleaved A/B, so the per-row min–max is the uncertainty measure.
Build/compile is the one latency number that went the other way: the evoxc build is 0.30 / 0.45 / 0.61 s for xor_p100/xor_p500/xor_p1000 against 2.99 / 2.97 / 2.96 s for jax.jit(...).lower().compile(), and peak RSS is 6.2× / 3.6× / 2.4× lower than the frozen JAX side on the same rows (109.2/191.5/291.6 vs 680.1/693.6/703.5 MiB) but 1.5× higher on Pagie (1299.0 vs 849.9 MiB), where the interpreter's per-generation working set grows with pop_size × max_nodes × max_conns while the XLA side stays close to its runtime floor.
Both are record-only facts: they describe 63f0fc67, not a universal property of the interpreter.
So the stated CPU contract ("at least as fast as the frozen JAX baseline") is not met on this record's tree, whose verdict benchmarks/RESULTS.md writes as FAIL: four timing rows fail (xor_p100, xor3d_p100, xor3d_p500 and custom_pagie_p500) and its quality verdict fails only on xor3d_p100 (−0.2500 against the old side's −0.0894). The numpy interpreter beats the frozen JAX side on xor_p500, xor_p1000 and xor3d_p1000 and loses on the other four CPU rows.
Where the rewrite does win:
- No JAX, no torch, no CUDA toolchain.
import tensorneatpulls in neither, enforced bytest/release_gate_no_jax.py; the runtime dependency set isevoxc,numpy,networkx,matplotlib,sympy. - The graph is data. It is inspectable, cacheable and transformable (
evoxc.Graph,evoxc.lower(...)), instead of being an opaquejax.jitdispatch; one executable per static shape is built once and reused. - Latency to first generation. Build 0.30 s at pop 100 vs 2.99 s of XLA compilation, and the same order for the XOR quickstart graph above, whose one quoted run printed
compile finished, cost time: 0.285115s(the build is 0.30-0.61 s on the three XOR rows and 1.55 s on Pagie; it is a one-off per static shape). - Switchable backends. The same kernels run on IREE llvm-cpu and on an accelerator:
xlais 4.14–154.20× faster per generation than the numpy leg on the MI300X, 2.50–3.51× faster thanireethere and 1.48–2.60× faster than the frozen JAX implementation on the same device, while on this CPUireellvm-cpu is 1.54–6.63× slower (see Backends andbenchmarks/GPU.md). - Memory at small scale. Peak RSS is 2.4–6.2× lower than the frozen JAX side on the three XOR rows (109.2/191.5/291.6 vs 680.1/693.6/703.5 MiB) and 1.5× higher on Pagie (1299.0 vs 849.9 MiB).
The measured bottleneck on the numpy backend is tell (speciation), not the forward pass, and the figures come from the hand-measured passes recorded in benchmarks/PERF_NUMPY.md. Profiling 20 generations at pop 500 before the first pass put evoxc's interpreter per-op overhead (operand resolution, dtype/shape validation, Tensor construction, ~13 µs/op) at ~63 % of a generation against ~37 % of numpy kernel bodies and 0.1 % of host-side Python, and the two speciate scans at 9 160 of the 10 767 executed ops per generation (85 %). The op-count pass (a697531 → tree f619f46) brought a pop-500 generation to 8 336 executed ops (−23 %; 8 340 at pop 1000), and on the current tree a generation executes 7 920 ops for xor_p500, 11 187 for custom_pagie_p500 and 27 860 for cartpole_p100 (op count is a leading indicator of wall time, never a proxy: pass 1's agg fold added 16 ops and made forward 26 % faster). No committed artifact re-measures the overhead or speciation share after either pass. Pass 3 of the same record is measured on the merged tree (3437e556, whose src/ is byte-identical to 63f0fc67): keeping the graph and the executed op count fixed, the post-pass evoxc interpreter is 1.07–2.25× faster per generation at 12–37 % lower peak RSS, and that pass is on the pinned evoxc revision, so a plain uv sync gets it.
Record map: benchmarks/GPU.md is the accelerator matrix (including the frozen JAX implementation on the same device), benchmarks/FORWARD.md the batch-forward matrix, benchmarks/BACKENDS.md the CPU compiled-backend evidence, and benchmarks/PERF_NUMPY.md the hand-measured numpy passes.
Install
Requires Python >= 3.11 (.python-version is 3.12).
uv (the repository-pinned environment)
git clone --branch evoxc https://gitlab.com/emi-lab/tensorneat.git
cd tensorneat
uv sync # runtime deps + the default `dev` group (pytest); --no-dev skips it
uv run pytest # or: uv run python examples/func_fit/xor.py
Extras:
| extra | installs | for |
|---|---|---|
bench |
jax >= 0.4.28, pytest |
the frozen legacy JAX implementation: benchmarks/ baseline and the test/parity/ oracle |
iree |
iree-base-compiler + iree-base-runtime 3.13.x |
backend="iree" on llvm-cpu and ROCm, test/backends |
xla-rocm |
jax-rocm7-pjrt==0.10.2 (a PJRT C API plugin .so, no jax import) |
backend="xla" on an AMD ROCm device; NVIDIA uses jax-cuda12-pjrt instead, and no CPU PJRT plugin is pip-installable |
tvm |
evoxc[tvm] |
backend="tvm" (untested here) |
compilers |
iree-base-compiler + iree-base-runtime 3.13.x and evoxc[tvm] |
every compiled backend this package ships |
docs |
sphinx >= 7.0, sphinx-rtd-theme |
building docs/ |
test |
pytest >= 8.0 |
the test suite without the JAX oracle |
e.g. uv sync --extra bench --extra iree or uv sync --all-extras.
evoxc discovers an installed jax_plugins/*/*_plugin.so by itself, so backend="xla" needs no environment variable; compile_options={"plugin_path": ...} (or EVOXC_PJRT_PLUGIN) pins a different plugin.
evoxc is resolved from a pinned upstream commit, not from PyPI, by [tool.uv.sources] in pyproject.toml:
[tool.uv.sources]
evoxc = { git = "https://github.com/EMI-Group/evoxc", rev = "fe85a534192f749a97b2f6e3b13b0800f69b8d90" }
The pin preserves the environment used for the recorded benchmarks. At the time of those measurements, the PyPI 0.1.0 wheel predated both the frontend work (linear ir.verify, two redundant verify passes removed from lower(), batched constant-payload emission, frame-walk source-location capture, an xla deadlock fix) and the numpy-interpreter performance pass (per-block dispatch plans, a flat value store, dead-value release at last use), which together are 1.07–2.25× on the numpy leg (benchmarks/PERF_NUMPY.md). Note that the pinned revision's package metadata still says version = "0.1.0", so evoxc.__version__ prints 0.1.0 even on the correct checkout.
pip (preserve the recorded compiler revision)
# 1. Runtime dependencies with the same compiler revision as the recorded benchmarks
pip install "evoxc @ git+https://gitlab.com/emi-lab/evox-compiler.git@fe85a534192f749a97b2f6e3b13b0800f69b8d90" \
numpy networkx matplotlib sympy
# 2. this package, from a checkout (or a git URL)
git clone --branch evoxc https://gitlab.com/emi-lab/tensorneat.git
pip install --no-deps ./tensorneat
Installation notes (checked 2026-12-05):
- Install TensorNEAT from the
evoxccheckout. Thetensorneatpackage is not currently available on PyPI. - Use
--no-depsonly after installing the dependencies above. This deliberately preserves the pinned compiler: its metadata says0.1.0, while TensorNEAT declaresevoxc >= 0.1.1. An ordinary resolver may reject that combination or replace the pin with a newer release. Current PyPI releases of EvoX Compiler are newer; they are not the environment used for the benchmark numbers in this README. - The
uvworkflow honors the repository's existing[tool.uv.sources]and lockfile. The pip recipe above fetches the same compiler commit from GitLab. Backend and performance measurements below retain their original hardware, versions, and dates.
Examples
The ten pipeline scripts use the public API only and print a per-generation log; the three interpret_visualize scripts are host-only introspection and import evoxc directly for that. Wall times below are from this box, one fresh process per script, uv run startup included (0.6–20.6 s end to end).
| script | what it demonstrates | command | verified |
|---|---|---|---|
examples/func_fit/xor.py |
2-input XOR, DefaultGenome(2 -> 1, max_nodes=12), pop 200, 150 gens, target -1e-3 |
uv run python examples/func_fit/xor.py |
ran, 4.3-4.4 s; converges at generation 67, loss 8.68e-04 |
examples/func_fit/xor3d.py |
3-bit parity (problem.XOR3d), max_nodes=16, pop 400, 150 gens, target -1e-3 |
uv run python examples/func_fit/xor3d.py |
ran, 20.0-20.6 s; converges at generation 144, loss 9.34e-04 |
examples/func_fit/xor_origin.py |
genome.OriginNode/OriginConn (historical markers, whole-gene crossover), pop 300, 250 gens, target -1e-6 |
uv run python examples/func_fit/xor_origin.py |
ran, 5.8-6.2 s; converges at generation 89, loss 8.86e-07 |
examples/func_fit/xor_recurrent.py |
RecurrentGenome(activate_time=10) on XOR3d, pop 300, 200 gens, target -1e-4 |
uv run python examples/func_fit/xor_recurrent.py |
ran, 10.6-11.2 s; converges at generation 72, loss 1.66e-10 |
examples/func_fit/custom_func_fit.py |
Pagie polynomial via problem.CustomFuncFit, pop 200, 30 gens |
uv run python examples/func_fit/custom_func_fit.py |
ran, 5.1-5.4 s; demo budget, stops at the generation limit, loss 0.0435 -> 0.0300 |
examples/func_fit/xor_hyperneat.py |
recurrent HyperNEAT over FullSubstrate (CPPN 4 coords -> 1 weight), pop 300, 40 gens |
uv run python examples/func_fit/xor_hyperneat.py |
ran, 5.7-6.1 s; demo budget, loss 0.25 -> 0.0165 |
examples/func_fit/xor_hyperneat_feedforward.py |
HyperNEATFeedForward + MLPSubstrate([4, 6, 6, 1]), pop 300, 40 gens |
uv run python examples/func_fit/xor_hyperneat_feedforward.py |
ran, 9.4-9.9 s; demo budget, loss 0.2232 -> 0.1876 |
examples/rl/cartpole.py |
problem.CartPole(max_step=200), two action logits, no output_transform, pop 200, 20 gens |
uv run python examples/rl/cartpole.py |
ran, 1.4-1.6 s; converges at generation 2, mean return 200/200 |
examples/rl/pendulum.py |
problem.Pendulum(max_step=200), init_hidden_layers=(6,), pop 100, 20 gens, target -300 |
uv run python examples/rl/pendulum.py |
ran, 2.7-3.0 s; converges at generation 5 (training max -271.30; show reports one episode at -595.12) |
examples/rl/mountaincar.py |
problem.MountainCarContinuous(), 999-step default, pop 100, 10 gens, fitness_target=float("inf") |
uv run python examples/rl/mountaincar.py |
ran, 11.9-12.5 s; no fitness target (never stops early), demo return -0.00, goal not reached |
examples/interpret_visualize/genome_sympy.py |
sympy formula + Python code + LaTeX of one genome (host only) | uv run python examples/interpret_visualize/genome_sympy.py |
ran, 0.8-1.1 s |
examples/interpret_visualize/grad_descent.py |
exact gradients through one evolved topology, checked against finite differences | uv run python examples/interpret_visualize/grad_descent.py |
ran, 0.62-0.65 s, prints PASS (worst discrepancy 8.33e-06 against the 1e-3 tolerance) |
examples/interpret_visualize/visualize_genome.py |
draw one genome as SVG (host only) | uv run python examples/interpret_visualize/visualize_genome.py |
ran, 0.95-1.9 s (the first run in a session pays a matplotlib font-cache build); writes an untracked, git-ignored network.svg next to the script |
The ten pipeline scripts use demo budgets on backend="numpy" (pop 100–400, 10–250 generations): the seven func_fit scripts mark theirs with a # Demo budget: comment, rl/cartpole.py marks its reduced max_step with # Small budget:, and rl/pendulum.py / rl/mountaincar.py size theirs through pop_size and generation_limit alone. Six of them reach their fitness target on seed 42 — xor.py, xor3d.py, xor_origin.py, xor_recurrent.py, cartpole.py, pendulum.py; three (custom_func_fit.py, the two HyperNEAT scripts) stop at the generation limit with a visibly falling loss and claim no convergence, and mountaincar.py sets fitness_target=float("inf"), so it has no target to cross. A real run raises pop_size into the thousands and the generation limit into the hundreds. The three interpret_visualize scripts are host-only (no Pipeline, under 2 s). Fitness is maximised everywhere, so a function-fitting fitness_target is a negative error bound. The Brax/Gymnax/mujoco examples of 0.1.x no longer exist.
Tutorials
tutorials/quickstart.ipynb— the current-API notebook, executed top to bottom: build a genome/algorithm/problem,Pipeline.setup/step/auto_run, the batch-firstbestpayload, backend selection (documented with anireeinstall probe; the notebook itself only ever builds and runsbackend="numpy"), and inspecting the builtevoxcexecutable.tutorials/legacy_jax/— the three pre-rewrite notebooks (tutorial-00-functional programming and state.ipynb,tutorial-01-genome.ipynb,tutorial-02-Usage.ipynb), kept for concepts only: their code is the oldjax/vmapAPI and does not run against this tree.
Project layout
| Path | Purpose |
|---|---|
src/tensorneat/pipeline.py |
the host compile site, generation loop, logging and checkpoint writer |
src/tensorneat/genome/ |
gene payload, genetic operators, forward/grad algebra, host-only introspection |
src/tensorneat/algorithm/ |
NEAT (speciation, spawn, breeding) and HyperNEAT/HyperNEATFeedForward + substrates |
src/tensorneat/problem/ |
XOR, XOR3d, FuncFit/CustomFuncFit, CartPole, Pendulum, MountainCarContinuous |
src/tensorneat/common/ |
State, error types, tensorization/schedule, ACT/AGG registries, sympy codegen |
benchmarks/ |
old-vs-new harness, the frozen legacy JAX implementation, RESULTS.md, BACKENDS.md |
test/ |
unit/, parity/ (vs legacy JAX), integration/, backends/ (iree), support/ (shared fixtures), the two release gates |
examples/ |
the runnable scripts above |
docs/ |
Sphinx configuration and autodoc stubs |
tutorials/ |
the quickstart notebook and the JAX-era notebooks |
Testing
uv run pytest # whole tree
uv run pytest -m "not parity and not slow" # numpy backend only, no optional dependency
uv run pytest -m parity # needs: uv sync --extra bench (frozen JAX oracle)
uv run pytest -m slow # integration: evolution, determinism, rebuild, checkpoints
uv run pytest -m requires_iree # needs: uv sync --extra iree
uv run pytest -m requires_rocm # the ROCm leg: needs: uv sync --extra iree + a HIP device
uv run pytest test/release_gate_no_jax.py test/test_release_gate_surface.py
Measured on this box with every extra installed (uv sync --all-extras):
$ uv run pytest
1539 passed, 0 failed, 0 skipped in ~105s
All 1539 collected tests pass: test/unit 1354, test/parity 60, test/integration 61, test/backends 46 (3 llvm-cpu + 2 ROCm compiled-backend cases plus the 41 marker-guard cases in test/backends/test_conftest.py), test/support 9, and 9 release gates (4 in test/release_gate_no_jax.py + 5 in test/test_release_gate_surface.py). The parity tests need the bench extra (jax) and the backend tests need --extra iree plus a HIP device for the ROCm cases; without those extras the parity modules and the compiled-backend cases skip at import instead of failing (an explicit -m requires_iree/-m requires_rocm run fails loudly instead), and everything else runs on a bare uv sync.
| suite | tests | extra needed | proves |
|---|---|---|---|
test/unit/ |
1354 | none | kernels against numpy oracles: schedule derivation, forward/NaN rules, mutation/crossover invariants, speciation (both GATED_ROWS paths), distance, parent selection and spawn, grad vs finite differences, ACT/AGG tables, the three RL problems against host oracles, HyperNEAT substrates/weights/genes plus a two-generation end-to-end run, version metadata, and the benchmark harness's own protocol/report/fingerprint |
test/parity/ |
60 | --extra bench |
the same kernels on identical payloads against benchmarks/legacy_jax (rtol 1e-5 forward, 1e-4 gradients), marker parity; test_oracle_integrity.py additionally pins that the oracle stays a separate implementation, that its four modules are actually collected, and that the directory still collects 60 tests |
test/integration/ |
61 | none | whole-pipeline XOR evolution, per-seed determinism, rebuild on shape change, checkpoint round-trip, show(state, best), the ask/tell diagnostics hook, chunked evaluate and its guard, the host_payload=False opt-out and materialize_payload, auto_run stopping, HyperNEAT end to end, RL golden returns, marker slow |
test/backends/ |
46 | --extra iree, plus a HIP device for the 2 ROCm cases |
backend="iree" end to end on llvm-cpu (3 cases) and on a real ROCm device with device="rocm" + target_backends=["rocm"] (2 cases, skipping with a named reason without /dev/kfd or a HIP device), both agreeing with numpy on the same seed and rejecting an unknown compile option instead of falling back; the marker-guard suite test_conftest.py (41 cases, no extra) pins the implies_requires_iree/requires_rocm -m truth table and the announced IREE 3.13 install command |
test/support/ |
9 | none | test_lazy.py pins the lazy-import helper (support/lazy.py): it imports a suite's package when the fixture runs, propagates every error by default (NotImplementedError included — a pending implementation is a defect), and skips only an explicit allow_pending=True NotImplementedError raised inside src/tensorneat; the rest of the directory (runner.py, payloads.py, oracle.py, functions_ref.py) is imported by the other suites rather than collected |
test/release_gate_no_jax.py + test/test_release_gate_surface.py |
4 + 5 | none | import hygiene — import tensorneat leaves jax, jaxlib, torch, brax, gymnax, mujoco out of sys.modules, even under an import hook that raises for them, and a tiny XOR run still evolves — plus the package surface: every module imports in a fresh subprocess, every __all__ name resolves, and no src/ file imports a forbidden framework |
Citation
If you use TensorNEAT in your research, please cite:
@article{10.1145/3730406,
author = {Wang, Lishuang and Zhao, Mengfei and Liu, Enyu and Sun, Kebin and Cheng, Ran},
title = {TensorNEAT: A GPU-accelerated Library for NeuroEvolution of Augmenting Topologies},
year = {2025},
publisher = {Association for Computing Machinery},
address = {New York, NY, USA},
url = {https://doi.org/10.1145/3730406},
doi = {10.1145/3730406},
journal = {ACM Trans. Evol. Learn. Optim.},
month = apr,
keywords = {Neuroevolution, GPU Acceleration, Algorithm Library}
}
License
TensorNEAT is released under the GNU General Public License v3.0; the full text is LICENSE.
pyproject.toml declares exactly that: license = { file = "LICENSE" } plus the classifier License :: OSI Approved :: GNU General Public License v3 (GPLv3), so a built wheel carries the GPL-3.0 text in its License: field, License-File: LICENSE, and the same classifier.
Acknowledgements
- Thanks to Kenneth O. Stanley and Risto Miikkulainen for the NEAT algorithm, which has greatly advanced neuroevolution.
- Thanks to neat-python and pureples for their clear Python implementations of NEAT and HyperNEAT.
- Thanks to the EvoX Compiler (
evoxc), the graph compiler and switchable-backend runtime this library's computation layer is built on. - Thanks to EvoX for the framework and the multi-device/distributed direction this library follows.
- The pre-rewrite JAX implementation is preserved under
benchmarks/legacy_jaxas the frozen timing baseline and numerical oracle; thanks to the JAX team for the engine that powered 0.1.x and still powers that oracle. - TensorNEAT received the GECCO 2024 Best Paper Award.
Community & Support
- Questions, bugs and feature requests: GitHub Issues.
- QQ group: 297969717.
Roadmap
- Close the CPU gap on the numpy interpreter. The measured bottleneck is
tell, dominated by speciation, plusevoxc's interpreter per-op overhead: before the op-count pass the twospeciatescans were 9 160 of the 10 767 executed ops per generation at pop 500 (85 %) and per-op overhead was ~63 % of a generation; that pass took the same generation to 8 336 executed ops and the post-tiling tree to 8 263 forxor_p500, but no committed record re-measures the overhead or speciation share after either pass (seebenchmarks/PERF_NUMPY.md). The forward pass is not the problem. - Make a compiled backend actually competitive. The IREE leg works but loses on llvm-cpu because the dense key-table
gather/argsort/scattertraffic lowers to generic loops; that is a kernel-formulation project (sparse/segment reductions), not a compiler-flag one. No compiled win is claimed until it is measured. - Lift the remaining
evoxcv1 exporter deferrals upstream, then re-evaluate the compiled backends and re-run the contract. - More NEAT-family algorithms and substrates (e.g. ES-HyperNEAT), and more RL problems that do not need JAX.
- Docs and tutorials: keep
docs/andtutorials/quickstart.ipynbin step with the API.
Pull requests are welcome.
Introduction
Tensorized NEAT and HyperNEAT neuroevolution on EvoX Compiler. Evolves neural network structures and weights with batched computation.
Customize your domain