# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Rollout-local neuron-centric plasticity for quality-diversity search.
# @see https://doi.org/10.1007/978-3-032-23604-3_22
# @see https://doi.org/10.1145/3638529.3654011
"""Evolve local learning rules and deploy them using independent rollout sessions."""
from dataclasses import dataclass
import numpy as np
from ._population import _finite_vector
from .modern import IsoLineMAPElites, _positive_int
from .task_search import _validate_grid
__all__ = ["HebbianPolicy", "HebbianSession", "HebbianEvaluator", "hebbian_map_elites"]
def _layout(layer_sizes):
sizes = tuple(_positive_int(n, "Layer width") for n in layer_sizes)
if len(sizes) < 2:
raise ValueError("Include at least one input and one output layer.")
return sizes
def _scales(initial_scale, weight_limit, learning_scale):
if not (0 <= initial_scale <= weight_limit < np.inf and weight_limit > 0 and 0 <= learning_scale < np.inf):
raise ValueError("Use finite nonnegative scales and a positive weight limit.")
## @brief An immutable genome with five Hebbian coefficients per neuron.
[docs]
@dataclass(frozen=True, slots=True)
class HebbianPolicy:
"""Each layer has ordered rows of (A, B, C, D, eta).
A policy describes a dense bias-free tanh network and update rule.
Its weights are initialized separately for every rollout.
:param layer_sizes: Input, hidden and output widths.
:param genome: Flat layer-major coefficient vector in [-1, 1].
:param initial_scale: Uniform half-width for synapse initialization.
:param weight_limit: Symmetric per-synapse clip after the update.
:param learning_scale: Global multiplier for the local update.
"""
layer_sizes: tuple[int, ...]
genome: tuple[float, ...]
initial_scale: float = .1
weight_limit: float = 4.
learning_scale: float = .1
def __post_init__(self):
sizes = _layout(self.layer_sizes)
genome = _finite_vector(self.genome, "Hebbian coefficients", 5 * sum(sizes))
if any(abs(value) > 1. for value in genome):
raise ValueError("Hebbian coefficients must be in [-1, 1].")
_scales(self.initial_scale, self.weight_limit, self.learning_scale)
object.__setattr__(self, "layer_sizes", sizes)
object.__setattr__(self, "genome", genome)
## @brief Seed a new independent set of synapses.
# @param seed Seed for initial weights.
# @param plastic Whether forward passes update synapses.
# @return A mutable HebbianSession.
[docs]
def start(self, *, seed=0, plastic=True):
"""Create a fresh rollout session. Use plastic=False for a frozen control."""
return HebbianSession(self, seed=seed, plastic=plastic)
## @brief Stateful controller instance for a single rollout.
[docs]
class HebbianSession:
"""Return tanh actions and update the local synapses after each forward pass."""
def __init__(self, policy, *, seed=0, plastic=True):
if not isinstance(policy, HebbianPolicy):
raise TypeError("Supply a HebbianPolicy.")
self._policy = policy
self._plastic = plastic
sizes = policy.layer_sizes
rng = np.random.default_rng(seed)
self._weights = [rng.uniform(-policy.initial_scale, policy.initial_scale, size=(left, right))
for left, right in zip(sizes, sizes[1:])]
coefficients = np.asarray(policy.genome).reshape(-1, 5)
self._rules = np.split(coefficients, np.cumsum(sizes[:-1]))
@property
def weights(self):
"""Return a copy of each layer's current synapse matrix."""
return tuple(weights.copy() for weights in self._weights)
## @brief Compute an action and apply the neuron-centric Hebbian update.
# @param observation Flat input of the configured length.
# @return Bounded action vector in [-1, 1].
[docs]
def act(self, observation):
"""Use the current weights for inference and the activations for the next update."""
activity = np.asarray(_finite_vector(observation, "Observation", self._policy.layer_sizes[0]))
proposed = []
for weights, pre, post in zip(self._weights, self._rules, self._rules[1:]):
with np.errstate(over="ignore", invalid="ignore"):
current = activity @ weights
if not np.isfinite(current).all():
raise ValueError("Pre-activations overflowed. Rescale the observations.")
output = np.tanh(current)
if self._plastic and self._policy.learning_scale:
a, _, c, d, eta = pre.T
_, b, c_next, d_next, eta_next = post.T
rate = .5 * (eta[:, None] + eta_next[None, :]) * self._policy.learning_scale
with np.errstate(over="ignore", invalid="ignore"):
local = ((a * activity)[:, None] + (b * output)[None, :]
+ np.outer(c * activity, c_next * output) + np.outer(d, d_next))
updated = np.clip(weights + rate * local, -self._policy.weight_limit, self._policy.weight_limit)
if not np.isfinite(updated).all():
raise ValueError("A synapse update became nonfinite. Rescale inputs or learning.")
proposed.append(updated)
activity = output
if proposed:
self._weights = proposed
return activity
## @brief Adapt a policy-evaluating callback to QDpy's numeric candidate contract.
[docs]
class HebbianEvaluator:
"""Use this callable with a native optimizer such as CMA-ME or CMA-MAE.
The supplied rollout function receives a HebbianPolicy. It returns
objective values and descriptors in the optimizer's normal format.
Start a fresh session for each episode in your evaluator.
"""
def __init__(self, layer_sizes, evaluate, *, initial_scale=.1, weight_limit=4., learning_scale=.1):
self.layer_sizes = _layout(layer_sizes)
if not callable(evaluate):
raise TypeError("Supply a callable policy evaluator.")
_scales(initial_scale, weight_limit, learning_scale)
self.evaluate = evaluate
self.initial_scale, self.weight_limit, self.learning_scale = initial_scale, weight_limit, learning_scale
@property
def dimension(self):
"""Return five times the total number of neurons."""
return 5 * sum(self.layer_sizes)
[docs]
def policy(self, genome):
"""Decode a measured genome into an immutable deployable policy."""
return HebbianPolicy(self.layer_sizes, genome, self.initial_scale, self.weight_limit, self.learning_scale)
def __call__(self, genome):
return self.evaluate(self.policy(genome))
## @brief Illuminate behaviors by evolving local plasticity coefficients.
# @param archive Empty Grid or CVTGrid with one objective.
# @param evaluator HebbianEvaluator adapting a rollout function.
# @param budget Number of genomes evaluated.
# @param batch_size Number of proposals per MAP-Elites batch.
# @param seed Private search seed.
# @return QDpy RunResult with numeric genomes in the archive.
[docs]
def hebbian_map_elites(archive, evaluator, *, budget, batch_size=1, seed=0):
"""Run Iso+LineDD MAP-Elites in the space of neuron-specific rules."""
from qdpy.simple import run
_validate_grid(archive)
if not isinstance(evaluator, HebbianEvaluator):
raise TypeError("Supply a HebbianEvaluator.")
weights = archive.fitness_weights
direction = "maximisation" if weights is None or weights[0] > 0 else "minimisation"
search = IsoLineMAPElites(archive, budget, evaluator.dimension, ind_domain=(-1., 1.),
batch_size=batch_size, iso_sigma=.14, optimisation_task=direction)
return run(search, evaluator, seed=seed)