QDpy
Loading...
Searching...
No Matches
hebbian_qd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
6
7"""Evolve local learning rules and deploy them using independent rollout sessions."""
8
9from dataclasses import dataclass
10
11import numpy as np
12
13from ._population import _finite_vector
14from .modern import IsoLineMAPElites, _positive_int
15from .task_search import _validate_grid
16
17__all__ = ["HebbianPolicy", "HebbianSession", "HebbianEvaluator", "hebbian_map_elites"]
18
19
20def _layout(layer_sizes):
21 sizes = tuple(_positive_int(n, "Layer width") for n in layer_sizes)
22 if len(sizes) < 2:
23 raise ValueError("Include at least one input and one output layer.")
24 return sizes
25
26
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.")
30
31
32
33@dataclass(frozen=True, slots=True)
35 """Each layer has ordered rows of (A, B, C, D, eta).
36
37 A policy describes a dense bias-free tanh network and update rule.
38 Its weights are initialized separately for every rollout.
39
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.
45 """
46
47 layer_sizes: tuple[int, ...]
48 genome: tuple[float, ...]
49 initial_scale: float = .1
50 weight_limit: float = 4.
51 learning_scale: float = .1
52
53 def __post_init__(self):
54 sizes = _layout(self.layer_sizes)
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].")
58 _scales(self.initial_scale, self.weight_limit, self.learning_scale)
59 object.__setattr__(self, "layer_sizes", sizes)
60 object.__setattr__(self, "genome", genome)
61
62
66 def start(self, *, seed=0, plastic=True):
67 """Create a fresh rollout session. Use plastic=False for a frozen control."""
68 return HebbianSession(self, seed=seed, plastic=plastic)
69
70
71
73 """Return tanh actions and update the local synapses after each forward pass."""
74
75 def __init__(self, policy, *, seed=0, plastic=True):
76 if not isinstance(policy, HebbianPolicy):
77 raise TypeError("Supply a HebbianPolicy.")
78 self._policy = policy
79 self._plastic = plastic
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]))
86
87 @property
88 def weights(self):
89 """Return a copy of each layer's current synapse matrix."""
90 return tuple(weights.copy() for weights in self._weights)
91
92
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]))
98 proposed = []
99 for weights, pre, post in zip(self._weights, self._rules, self._rules[1:]):
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)
105 if self._plastic and self._policy.learning_scale:
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)
116 activity = output
117 if proposed:
118 self._weights = proposed
119 return activity
120
121
122
124 """Use this callable with a native optimizer such as CMA-ME or CMA-MAE.
125
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.
129 """
130
131 def __init__(self, layer_sizes, evaluate, *, initial_scale=.1, weight_limit=4., learning_scale=.1):
132 self.layer_sizes = _layout(layer_sizes)
133 if not callable(evaluate):
134 raise TypeError("Supply a callable policy evaluator.")
135 _scales(initial_scale, weight_limit, learning_scale)
136 self.evaluate = evaluate
137 self.initial_scale, self.weight_limit, self.learning_scale = initial_scale, weight_limit, learning_scale
138
139 @property
140 def dimension(self):
141 """Return five times the total number of neurons."""
142 return 5 * sum(self.layer_sizes)
143
144 def policy(self, genome):
145 """Decode a measured genome into an immutable deployable policy."""
146 return HebbianPolicy(self.layer_sizes, genome, self.initial_scale, self.weight_limit, self.learning_scale)
147
148 def __call__(self, genome):
149 return self.evaluate(self.policy(genome))
150
151
152
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."""
161 from qdpy.simple import run
162
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.
Definition hebbian_qd.py:34
start(self, *, seed=0, plastic=True)
Seed a new independent set of synapses.
Definition hebbian_qd.py:66
Stateful controller instance for a single rollout.
Definition hebbian_qd.py:72
act(self, observation)
Compute an action and apply the neuron-centric Hebbian update.
Definition hebbian_qd.py:95
Fill a one-elite grid using Iso+LineDD variation.
Definition modern.py:56