summaryrefslogtreecommitdiff
path: root/sdil/local_baselines.py
diff options
context:
space:
mode:
Diffstat (limited to 'sdil/local_baselines.py')
-rw-r--r--sdil/local_baselines.py241
1 files changed, 161 insertions, 80 deletions
diff --git a/sdil/local_baselines.py b/sdil/local_baselines.py
index a6a11a3..23b1b5c 100644
--- a/sdil/local_baselines.py
+++ b/sdil/local_baselines.py
@@ -1,6 +1,7 @@
"""
-Other biologically-motivated / non-backprop local learning baselines, sharing
-SDILNet's architecture and initialisation for a fair comparison:
+Other biologically-motivated / non-backprop local learning baselines. FA and
+PEPITA reuse SDILNet's tensor layout; FF and EP retain their native model
+classes because their state spaces and objectives are fundamentally different:
- FANet : Feedback Alignment (Lillicrap 2016) -- backprop through FIXED random
feedback matrices instead of W^T (sequential, layer-wise). DFA is the
@@ -12,7 +13,10 @@ SDILNet's architecture and initialisation for a fair comparison:
it on negative (wrong label) data; inference picks max total goodness.
All train with no global backward graph. Autograd, where used (FF's per-layer
-local loss), never crosses layer boundaries -> the update stays local.
+local loss), never crosses layer boundaries -> the update stays local. The
+implementations follow the authors' published algorithms and reference code;
+their deliberately different architectures are exposed rather than hidden
+behind an allegedly apples-to-apples SDILNet wrapper.
"""
import math
import torch
@@ -25,9 +29,11 @@ from .core import SDILNet, ACTS
# Feedback Alignment (sequential, layer-wise random feedback)
# --------------------------------------------------------------------------
class FANet(SDILNet):
- def __init__(self, *args, b_scale=1.0, **kw):
+ def __init__(self, *args, b_scale=1.0, feedback_seed=None, **kw):
+ model_seed = kw.get("seed", 0)
super().__init__(*args, **kw)
- g = torch.Generator(device="cpu").manual_seed(4242)
+ g = torch.Generator(device="cpu").manual_seed(
+ model_seed + 4242 if feedback_seed is None else feedback_seed)
# fixed random feedback B[l] with the same shape as W[l], for l=1..L-1
self.B = [None]
for l in range(1, self.L):
@@ -39,16 +45,22 @@ class FANet(SDILNet):
with torch.no_grad():
fwd = self.forward(x)
h, u = fwd["h"], fwd["u"]
- B = x.shape[0]
e = torch.softmax(h[-1], 1) - yoh # grad wrt logits
loss = F.cross_entropy(h[-1], y).item()
# output layer (exact local)
- delta = e # grad wrt u[L-1]
- self._upd(self.L - 1, delta, h[self.L - 1], eta, momentum)
- # hidden layers: propagate with fixed random B
+ self._upd(self.L - 1, e, h[self.L - 1], eta, momentum)
+
+ # dh is the error wrt the hidden *state*. On a residual block,
+ # h'=h+alpha*phi(Wh), the identity branch transports dh exactly and
+ # only the nonlinear branch uses a fixed random feedback matrix.
+ dh = e @ self.B[self.L - 1]
for l in range(self.L - 2, -1, -1):
- delta = (delta @ self.B[l + 1]) * self.act_prime(u[l]) # grad wrt u[l]
- self._upd(l, delta, h[l], eta, momentum)
+ branch_scale = self.res_alpha if self.residual and l >= 1 else 1.0
+ du = branch_scale * dh * self.act_prime(u[l])
+ self._upd(l, du, h[l], eta, momentum)
+ if l > 0:
+ feedback = du @ self.B[l]
+ dh = dh + feedback if self.residual and l >= 1 else feedback
return loss
def _upd(self, l, delta, pre, eta, momentum):
@@ -65,39 +77,85 @@ class FANet(SDILNet):
# PEPITA (forward-only, error-modulated second pass)
# --------------------------------------------------------------------------
class PEPITANet(SDILNet):
- def __init__(self, *args, f_scale=0.1, **kw):
+ """Original two-forward-pass PEPITA/ERIN rule.
+
+ Dellaferrera & Kreiman initialise both feedforward weights and the input
+ error projection with He-uniform samples, then multiply the latter by 0.05.
+ Their fully-connected implementation has ReLU hidden units, a softmax
+ output, no biases, and optionally shares one dropout mask across the two
+ presentations. We keep logits internally but form exactly the same
+ softmax errors.
+ """
+
+ def __init__(self, *args, f_scale=0.05, original_init=True,
+ use_bias=False, keep_prob=1.0, **kw):
+ model_seed = kw.get("seed", 0)
super().__init__(*args, **kw)
- g = torch.Generator(device="cpu").manual_seed(7777)
+ g = torch.Generator(device="cpu").manual_seed(model_seed + 7777)
n_in = self.sizes[0]
- # projection of output error back onto the input (fixed random)
- self.Fproj = (torch.randn(n_in, self.n_classes, generator=g)
- * (f_scale / math.sqrt(self.n_classes))).to(self.W[0].device, self.dtype)
+ if original_init:
+ for l, w in enumerate(self.W):
+ limit = math.sqrt(6.0 / self.sizes[l])
+ w.copy_((torch.rand(w.shape, generator=g) * 2.0 * limit - limit)
+ .to(w.device, w.dtype))
+ limit = math.sqrt(6.0 / n_in)
+ self.Fproj = ((torch.rand(n_in, self.n_classes, generator=g) * 2.0 * limit - limit)
+ * f_scale).to(self.W[0].device, self.dtype)
+ self.use_bias = use_bias
+ self.keep_prob = keep_prob
+
+ def _pepita_forward(self, x, masks):
+ h = [x]
+ for l in range(self.L):
+ cur = h[-1] @ self.W[l].t()
+ if self.use_bias:
+ cur = cur + self.b[l]
+ if l < self.L - 1:
+ cur = self.act(cur)
+ if masks is not None:
+ cur = cur * masks[l]
+ h.append(cur)
+ return h
def pepita_step(self, x, y, yoh, eta, momentum=0.0):
with torch.no_grad():
- std = self.forward(x)
- hs = std["h"]
+ masks = None
+ if self.keep_prob < 1.0:
+ masks = [(torch.rand(x.shape[0], self.sizes[l + 1], device=x.device)
+ < self.keep_prob).to(x.dtype) / self.keep_prob
+ for l in range(self.L - 1)]
+ hs = self._pepita_forward(x, masks)
e = torch.softmax(hs[-1], 1) - yoh
loss = F.cross_entropy(hs[-1], y).item()
x_mod = x + (e @ self.Fproj.t()) # modulate the input by the error
- mod = self.forward(x_mod)
- hm = mod["h"]
+ hm = self._pepita_forward(x_mod, masks)
+ mod_error = torch.softmax(hm[-1], 1) - yoh
B = x.shape[0]
for l in range(self.L):
- # change in this layer's output between clean and modulated passes
- dpost = hs[l + 1] - hm[l + 1]
- # PEPITA: first layer uses the CLEAN input as presynaptic; deeper
- # layers use the modulated presynaptic.
- pre = x if l == 0 else hm[l]
- dW = -(dpost.t() @ pre) / B
- db = -dpost.mean(0)
+ pre = hm[l] # modulated presynaptic state
+ if l == self.L - 1:
+ update = -(mod_error.t() @ pre) / B
+ update_b = -mod_error.mean(0)
+ else:
+ diff = hs[l + 1] - hm[l + 1]
+ update = -(diff.t() @ pre) / B
+ update_b = -diff.mean(0)
if momentum:
- self.mW[l].mul_(momentum).add_(dW); self.mb[l].mul_(momentum).add_(db)
- self.W[l] += eta * self.mW[l]; self.b[l] += eta * self.mb[l]
+ self.mW[l].mul_(momentum).add_(update)
+ self.W[l] += eta * self.mW[l]
+ if self.use_bias:
+ self.mb[l].mul_(momentum).add_(update_b)
+ self.b[l] += eta * self.mb[l]
else:
- self.W[l] += eta * dW; self.b[l] += eta * db
+ self.W[l] += eta * update
+ if self.use_bias:
+ self.b[l] += eta * update_b
return loss
+ def forward(self, x, **_):
+ h = self._pepita_forward(x, masks=None)
+ return {"h": h, "u": []}
+
# --------------------------------------------------------------------------
# Forward-Forward (Hinton 2022)
@@ -107,8 +165,9 @@ class FFNet:
each layer is trained by a local goodness objective; classification sums
goodness across layers over the candidate labels."""
- def __init__(self, sizes, act="tanh", device="cpu", seed=0, threshold=2.0,
- n_classes=10, dtype=torch.float32, overlay_val=10.0):
+ def __init__(self, sizes, act="relu", device="cpu", seed=0, threshold=2.0,
+ n_classes=10, dtype=torch.float32, overlay_val=None,
+ score_from_layer=1):
self.sizes = list(sizes)
self.L = len(sizes) - 1
self.n_classes = n_classes
@@ -117,18 +176,19 @@ class FFNet:
self.act, _ = ACTS[act]
self.thr = threshold
self.overlay_val = overlay_val
+ self.score_from_layer = min(score_from_layer, max(0, self.L - 1))
g = torch.Generator(device="cpu").manual_seed(seed)
- self.W, self.b, self.mW, self.mb = [], [], [], []
+ self.W, self.b, self.optimizers = [], [], []
for i in range(self.L):
- w = (torch.randn(sizes[i + 1], sizes[i], generator=g) / math.sqrt(sizes[i])
- ).to(device, dtype)
- w.requires_grad_(True)
+ # Match torch.nn.Linear initialization used by the public reference.
+ bound = 1.0 / math.sqrt(sizes[i])
+ w = (torch.rand(sizes[i + 1], sizes[i], generator=g) * 2.0 * bound - bound).to(
+ device, dtype).requires_grad_(True)
self.W.append(w)
- bb = torch.zeros(sizes[i + 1], device=device, dtype=dtype, requires_grad=True)
+ bb = (torch.rand(sizes[i + 1], generator=g) * 2.0 * bound - bound).to(
+ device, dtype).requires_grad_(True)
self.b.append(bb)
-
- def __init_overlay_scale__(self):
- pass
+ self.optimizers.append(torch.optim.Adam([w, bb], lr=0.03))
def _overlay(self, x, labels):
"""Overlay one-hot label onto the first n_classes input features.
@@ -136,7 +196,8 @@ class FFNet:
(10 of 784 pixels is otherwise swamped by the shared image)."""
xo = x.clone()
xo[:, :self.n_classes] = 0.0
- xo[torch.arange(x.shape[0]), labels] = self.overlay_val
+ value = x.max().detach() if self.overlay_val is None else self.overlay_val
+ xo[torch.arange(x.shape[0], device=x.device), labels] = value
return xo
@staticmethod
@@ -144,28 +205,40 @@ class FFNet:
return h / (h.norm(dim=1, keepdim=True) + 1e-8)
def _layer_forward(self, l, h_in):
- return self.act(h_in @ self.W[l].t() + self.b[l])
+ return self.act(self._norm(h_in) @ self.W[l].t() + self.b[l])
+
+ def _inputs_to_layer(self, l, x):
+ h = x
+ with torch.no_grad():
+ for k in range(l):
+ h = self._layer_forward(k, h)
+ return h.detach()
+
+ def train_layer(self, l, x, y, eta=0.03, negative_labels=None):
+ """One minibatch update of one greedy FF layer (local autograd only)."""
+ if negative_labels is None:
+ negative_labels = ((y + torch.randint(
+ 1, self.n_classes, y.shape, device=y.device)) % self.n_classes)
+ hpos = self._inputs_to_layer(l, self._overlay(x, y))
+ hneg = self._inputs_to_layer(l, self._overlay(x, negative_labels))
+ hp = self._layer_forward(l, hpos)
+ hn = self._layer_forward(l, hneg)
+ gp = hp.pow(2).mean(1)
+ gn = hn.pow(2).mean(1)
+ loss = (F.softplus(-gp + self.thr) + F.softplus(gn - self.thr)).mean()
+ opt = self.optimizers[l]
+ opt.param_groups[0]["lr"] = eta
+ opt.zero_grad()
+ loss.backward()
+ opt.step()
+ return loss.item()
def train_step(self, x, y, eta):
- # positive = correct label; negative = a random wrong label
+ """Compatibility path; canonical runner trains greedily layer-by-layer."""
neg = (y + torch.randint(1, self.n_classes, y.shape, device=y.device)) % self.n_classes
- xpos = self._overlay(x, y)
- xneg = self._overlay(x, neg)
- hpos, hneg = xpos, xneg
total = 0.0
for l in range(self.L):
- hp = self._layer_forward(l, hpos.detach())
- hn = self._layer_forward(l, hneg.detach())
- gp = hp.pow(2).mean(1) # goodness (positive)
- gn = hn.pow(2).mean(1) # goodness (negative)
- # push positive goodness above threshold, negative below
- loss = (F.softplus(-(gp - self.thr)) + F.softplus(gn - self.thr)).mean()
- gW, gb = torch.autograd.grad(loss, [self.W[l], self.b[l]])
- with torch.no_grad():
- self.W[l] -= eta * gW
- self.b[l] -= eta * gb
- total += loss.item()
- hpos, hneg = self._norm(hp).detach(), self._norm(hn).detach()
+ total += self.train_layer(l, x, y, eta, neg)
return total / self.L
@torch.no_grad()
@@ -176,9 +249,8 @@ class FFNet:
good = torch.zeros(x.shape[0], device=x.device)
for l in range(self.L):
h = self._layer_forward(l, h)
- if l > 0: # skip first layer for scoring (Hinton)
+ if l >= self.score_from_layer: # paper excludes first layer
good = good + h.pow(2).mean(1)
- h = self._norm(h)
scores[:, c] = good
return scores.argmax(1)
@@ -201,15 +273,20 @@ class EPNet:
Updates are local (products of adjacent-layer rho's) with no backprop."""
def __init__(self, sizes, device="cpu", seed=0, beta=0.5, dt=0.5,
- T_free=20, T_nudge=8, dtype=torch.float32):
+ T_free=20, T_nudge=4, dtype=torch.float32,
+ random_beta_sign=True):
self.sizes = list(sizes)
self.L = len(sizes) - 1 # number of weight layers
self.device = device
self.dtype = dtype
self.beta, self.dt, self.T_free, self.T_nudge = beta, dt, T_free, T_nudge
+ self.random_beta_sign = random_beta_sign
g = torch.Generator(device="cpu").manual_seed(seed)
- self.W = [(torch.randn(sizes[i + 1], sizes[i], generator=g) / math.sqrt(sizes[i])
- ).to(device, dtype) for i in range(self.L)]
+ self.W = []
+ for i in range(self.L):
+ limit = math.sqrt(6.0 / (sizes[i] + sizes[i + 1]))
+ self.W.append((torch.rand(sizes[i + 1], sizes[i], generator=g)
+ * 2.0 * limit - limit).to(device, dtype))
self.b = [torch.zeros(sizes[i + 1], device=device, dtype=dtype) for i in range(self.L)]
@staticmethod
@@ -218,28 +295,28 @@ class EPNet:
@staticmethod
def rhop(s):
- return ((s > 0) & (s < 1)).to(s.dtype)
+ # Theano's clip derivative used by the authors is active at the bounds.
+ return ((s >= 0) & (s <= 1)).to(s.dtype)
def _settle(self, x, y=None, beta=0.0, s=None, T=20):
rx = self.rho(x)
if s is None:
- # init in the active region (rhop=0 at the clamp boundaries would
- # otherwise freeze the dynamics); a feedforward warm start settles fast.
- s = []
- below = rx
- for i in range(self.L):
- below = (below @ self.W[i].t() + self.b[i]).clamp(0, 1)
- s.append(below)
+ # The reference implementation starts persistent particles at zero.
+ s = [torch.zeros(x.shape[0], n, device=x.device, dtype=x.dtype)
+ for n in self.sizes[1:]]
for _ in range(T):
new = []
for k in range(self.L):
below = rx if k == 0 else self.rho(s[k - 1])
- pre = below @ self.W[k].t() + self.b[k]
+ # -dE/ds for E = ||rho(s)||^2/2 - b*rho(s)
+ # - rho(s_below) W^T rho(s).
+ drive = -self.rho(s[k]) + below @ self.W[k].t() + self.b[k]
if k < self.L - 1: # top-down from layer above
- pre = pre + self.rho(s[k + 1]) @ self.W[k + 1]
+ drive = drive + self.rho(s[k + 1]) @ self.W[k + 1]
if k == self.L - 1 and beta: # nudge output toward target
- pre = pre + beta * (y - s[k])
- ds = self.rhop(s[k]) * pre - s[k]
+ # Original cost is ||s_out-y||^2, hence the factor two.
+ drive = drive + 2.0 * beta * (y - s[k])
+ ds = self.rhop(s[k]) * drive
new.append((s[k] + self.dt * ds).clamp(0, 1))
s = new
return s
@@ -247,15 +324,19 @@ class EPNet:
def train_step(self, x, y, yoh, eta):
with torch.no_grad():
s0 = self._settle(x, beta=0.0, T=self.T_free) # free phase
- sb = self._settle(x, yoh, beta=self.beta, s=[t.clone() for t in s0], T=self.T_nudge)
+ beta = self.beta
+ if self.random_beta_sign and torch.randint(0, 2, ()).item() == 0:
+ beta = -beta
+ sb = self._settle(x, yoh, beta=beta, s=[t.clone() for t in s0], T=self.T_nudge)
B = x.shape[0]
for k in range(self.L):
below0 = self.rho(x) if k == 0 else self.rho(s0[k - 1])
belowb = self.rho(x) if k == 0 else self.rho(sb[k - 1])
- dW = (self.rho(sb[k]).t() @ belowb - self.rho(s0[k]).t() @ below0) / (self.beta * B)
- db = (self.rho(sb[k]) - self.rho(s0[k])).mean(0) / self.beta
- self.W[k] += eta * dW
- self.b[k] += eta * db
+ dW = (self.rho(sb[k]).t() @ belowb - self.rho(s0[k]).t() @ below0) / (beta * B)
+ db = (self.rho(sb[k]) - self.rho(s0[k])).mean(0) / beta
+ layer_eta = eta[k] if isinstance(eta, (list, tuple)) else eta
+ self.W[k] += layer_eta * dW
+ self.b[k] += layer_eta * db
# free-phase output as prediction proxy for loss logging
return F.mse_loss(s0[-1], yoh).item()