7"""Evolve local learning rules and deploy them using independent rollout sessions."""
9from dataclasses
import dataclass
13from ._population
import _finite_vector
14from .modern
import IsoLineMAPElites, _positive_int
15from .task_search
import _validate_grid
17__all__ = [
"HebbianPolicy",
"HebbianSession",
"HebbianEvaluator",
"hebbian_map_elites"]
20def _layout(layer_sizes):
21 sizes = tuple(_positive_int(n,
"Layer width")
for n
in layer_sizes)
23 raise ValueError(
"Include at least one input and one output layer.")
27def _scales(initial_scale, weight_limit, learning_scale):
28 if not (0 <= initial_scale <= weight_limit < np.inf
and weight_limit > 0
and 0 <= learning_scale < np.inf):
29 raise ValueError(
"Use finite nonnegative scales and a positive weight limit.")
33@dataclass(frozen=True, slots=True)
35 """Each layer has ordered rows of (A, B, C, D, eta).
37 A policy describes a dense bias-free tanh network and update rule.
38 Its weights are initialized separately for every rollout.
40 :param layer_sizes: Input, hidden and output widths.
41 :param genome: Flat layer-major coefficient vector in [-1, 1].
42 :param initial_scale: Uniform half-width for synapse initialization.
43 :param weight_limit: Symmetric per-synapse clip after the update.
44 :param learning_scale: Global multiplier for the local update.
47 layer_sizes: tuple[int, ...]
48 genome: tuple[float, ...]
49 initial_scale: float = .1
50 weight_limit: float = 4.
51 learning_scale: float = .1
53 def __post_init__(self):
55 genome = _finite_vector(self.
genome,
"Hebbian coefficients", 5 * sum(sizes))
56 if any(abs(value) > 1.
for value
in genome):
57 raise ValueError(
"Hebbian coefficients must be in [-1, 1].")
59 object.__setattr__(self,
"layer_sizes", sizes)
60 object.__setattr__(self,
"genome", genome)
66 def start(self, *, seed=0, plastic=True):
67 """Create a fresh rollout session. Use plastic=False for a frozen control."""
73 """Return tanh actions and update the local synapses after each forward pass."""
75 def __init__(self, policy, *, seed=0, plastic=True):
76 if not isinstance(policy, HebbianPolicy):
77 raise TypeError(
"Supply a HebbianPolicy.")
80 sizes = policy.layer_sizes
81 rng = np.random.default_rng(seed)
82 self.
_weights = [rng.uniform(-policy.initial_scale, policy.initial_scale, size=(left, right))
83 for left, right
in zip(sizes, sizes[1:])]
84 coefficients = np.asarray(policy.genome).reshape(-1, 5)
85 self.
_rules = np.split(coefficients, np.cumsum(sizes[:-1]))
89 """Return a copy of each layer's current synapse matrix."""
90 return tuple(weights.copy()
for weights
in self.
_weights)
95 def act(self, observation):
96 """Use the current weights for inference and the activations for the next update."""
97 activity = np.asarray(_finite_vector(observation,
"Observation", self.
_policy.layer_sizes[0]))
100 with np.errstate(over=
"ignore", invalid=
"ignore"):
101 current = activity @ weights
102 if not np.isfinite(current).all():
103 raise ValueError(
"Pre-activations overflowed. Rescale the observations.")
104 output = np.tanh(current)
106 a, _, c, d, eta = pre.T
107 _, b, c_next, d_next, eta_next = post.T
108 rate = .5 * (eta[:,
None] + eta_next[
None, :]) * self.
_policy.learning_scale
109 with np.errstate(over=
"ignore", invalid=
"ignore"):
110 local = ((a * activity)[:,
None] + (b * output)[
None, :]
111 + np.outer(c * activity, c_next * output) + np.outer(d, d_next))
112 updated = np.clip(weights + rate * local, -self.
_policy.weight_limit, self.
_policy.weight_limit)
113 if not np.isfinite(updated).all():
114 raise ValueError(
"A synapse update became nonfinite. Rescale inputs or learning.")
115 proposed.append(updated)
124 """Use this callable with a native optimizer such as CMA-ME or CMA-MAE.
126 The supplied rollout function receives a HebbianPolicy. It returns
127 objective values and descriptors in the optimizer's normal format.
128 Start a fresh session for each episode in your evaluator.
131 def __init__(self, layer_sizes, evaluate, *, initial_scale=.1, weight_limit=4., learning_scale=.1):
133 if not callable(evaluate):
134 raise TypeError(
"Supply a callable policy evaluator.")
135 _scales(initial_scale, weight_limit, learning_scale)
141 """Return five times the total number of neurons."""
145 """Decode a measured genome into an immutable deployable policy."""
148 def __call__(self, genome):
159def hebbian_map_elites(archive, evaluator, *, budget, batch_size=1, seed=0):
160 """Run Iso+LineDD MAP-Elites in the space of neuron-specific rules."""
163 _validate_grid(archive)
164 if not isinstance(evaluator, HebbianEvaluator):
165 raise TypeError(
"Supply a HebbianEvaluator.")
166 weights = archive.fitness_weights
167 direction =
"maximisation" if weights
is None or weights[0] > 0
else "minimisation"
168 search =
IsoLineMAPElites(archive, budget, evaluator.dimension, ind_domain=(-1., 1.),
169 batch_size=batch_size, iso_sigma=.14, optimisation_task=direction)
170 return run(search, evaluator, seed=seed)
Adapt a policy-evaluating callback to QDpy's numeric candidate contract.
An immutable genome with five Hebbian coefficients per neuron.
start(self, *, seed=0, plastic=True)
Seed a new independent set of synapses.
Stateful controller instance for a single rollout.
act(self, observation)
Compute an action and apply the neuron-centric Hebbian update.
Fill a one-elite grid using Iso+LineDD variation.