NEATdocs

Keras

Use NEAT in model.compile on TensorFlow, JAX or PyTorch, just like any other Keras optimizer.

The main workflow is intentionally familiar to Keras users: create a model, pass NEAT as the optimizer, then inspect diagnostics after training.

Official Keras ecosystem integration

NEAT appears in the Keras ecosystem directory on keras.io. It is built on public Keras 3 APIs and fits the standard Keras workflow without wrappers or patches:

Keras featureHow NEAT plugs in
keras.optimizers.OptimizerNEAT subclasses the Keras 3 base optimizer, so it works anywhere a built-in optimizer does
model.compile / model.fitPass optimizer=NEAT(...); no custom training loop needed
keras.savingNEAT and NEATDiagnosticsCallback are registered serializables (package="neat_optim"), so model.save() and keras.models.load_model() round-trip
keras.callbacksNEATDiagnosticsCallback logs neat_* metrics to History and TensorBoard
Multi-backend KerasSame code on TensorFlow, JAX and PyTorch via KERAS_BACKEND
Custom training stepsoptimizer.apply_gradients(...) works inside tf.function steps

NEAT is maintained independently of the Keras team. The keras.io listing marks it as a Keras ecosystem project, not as part of Keras itself.

Backends

Pick a backend with KERAS_BACKEND. The same model.compile(optimizer=NEAT(...)) code runs on all three.

BackendCI coverage
TensorFlowFull Keras integration test suite plus a custom-loop example
JAXfit() smoke test
PyTorchfit() smoke test plus direct TorchNEAT adapter tests
KERAS_BACKEND=jax python train.py

Player-aware training is TensorFlow-only

player_train_step uses tf.GradientTape, so it requires the TensorFlow backend. Everything else on this page works on all three backends.

Training example

train.py
import keras
from neat_optim import NEAT

model = keras.Sequential([
    keras.layers.Input((32,)),
    keras.layers.Dense(64, activation="relu"),
    keras.layers.Dense(10),
])

optimizer = NEAT(
    learning_rate=1e-3,
    alpha=0.25,
    beta=0.9,
    nce_mode="projection",
    opponent_source="gradient_ema",
    correction_warmup_steps=5,
    adaptive_alpha=True,
    adaptive_preconditioning=True,
)

model.compile(
    optimizer=optimizer,
    loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=["accuracy"],
)

model.fit(x_train, y_train, epochs=20, validation_data=(x_val, y_val))
print(model.optimizer.diagnostic_snapshot())

Diagnostics

diagnostic_snapshot() returns running means since the last reset:

snap = model.optimizer.diagnostic_snapshot()
# {
#   "mean_conflict_ratio":        0.021,  # average conflict detected per step
#   "mean_correction_ratio":      0.008,  # correction size / gradient size
#   "mean_update_alignment":      0.997,  # cosine similarity of corrected vs raw gradient
#   "mean_opponent_norm":         0.043,  # magnitude of the opponent signal
#   "correction_active_fraction": 0.74,   # fraction of steps where correction fired
#   ...
# }

It also reports mean_effective_alpha, mean_gradient_noise, mean_gradient_norm, mean_correction_norm, mean_step_norm and mean_effective_step_size.

Is the correction doing anything?

If mean_conflict_ratio < 0.01 and correction_active_fraction < 0.1, the correction is essentially inactive on this task. NEAT then behaves like momentum SGD, and tuning alpha won't help. Tasks with noisy or multi-objective gradients tend to show much higher conflict ratios.

Per-epoch metrics, TensorBoard and reports

from neat_optim import NEATDiagnosticsCallback

history = model.fit(
    x_train, y_train,
    callbacks=[
        NEATDiagnosticsCallback(
            log_dir="runs/neat",                           # TensorBoard scalars (pip install tensorboard)
            report_path="runs/neat/training-report.html",  # optional JSON or HTML report
            reset_each_epoch=True,
        ),
    ],
)
print(history.history["neat_mean_conflict_ratio"])

Read per-epoch values from History

With reset_each_epoch=True, the callback writes each epoch's diagnostics to History and then resets the optimizer's counters. Calling diagnostic_snapshot() after fit() will therefore return zeros. Use history.history["neat_..."] instead.

Saving and loading

Compiled models save and load normally, optimizer included:

model.save("model.keras")
restored = keras.models.load_model("model.keras")  # restored.optimizer is a NEAT instance

get_config() / NEAT.from_config(...) round-trip every optimizer argument.

Custom TensorFlow training loop

import tensorflow as tf
import keras
from neat_optim import NEAT

optimizer = NEAT(learning_rate=1e-3, alpha=0.25)
loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True)

@tf.function
def train_step(x, y):
    with tf.GradientTape() as tape:
        logits = model(x, training=True)
        loss = loss_fn(y, logits)
    grads = tape.gradient(loss, model.trainable_variables)
    optimizer.apply_gradients(zip(grads, model.trainable_variables))
    return loss

See Configuration for every optimizer argument.

On this page