Two synthetic tasks live in different regions of a 10-dimensional input space and follow different rules, so one small network can solve both jointly. Train on A, then on B with no protection, with EWC at two strengths, or with replay of 100 stored A examples.
import torch, torch.nn as nn, torch.nn.functional as F
torch.manual_seed(0)
def make_task(shift, rule_dim, n=2000):
x = torch.randn(n, 10); x[:, 0] += shift
return x, (x[:, rule_dim] > 0).long()
A, B = make_task(+2.0, 1), make_task(-2.0, 2)
net = lambda: nn.Sequential(nn.Linear(10, 64), nn.ReLU(), nn.Linear(64, 2))
acc = lambda m, d: (m(d[0]).argmax(1) == d[1]).float().mean().item()
def fit(m, data, penalty=None, replay=None, steps=1500):
opt = torch.optim.Adam(m.parameters(), lr=1e-3)
x, y = data
for _ in range(steps):
i = torch.randint(len(x), (64,))
loss = F.cross_entropy(m(x[i]), y[i])
if replay:
j = torch.randint(len(replay[0]), (16,))
loss = loss + F.cross_entropy(m(replay[0][j]), replay[1][j])
if penalty:
loss = loss + penalty(m)
opt.zero_grad(); loss.backward(); opt.step()
def fisher_diag(m, data, n=500):
fis = [torch.zeros_like(p) for p in m.parameters()]
for k in range(n):
m.zero_grad()
F.cross_entropy(m(data[0][k:k+1]), data[1][k:k+1]).backward()
for f, p in zip(fis, m.parameters()):
f += p.grad ** 2 / n
return fis
base = net(); fit(base, A)
star = [p.detach().clone() for p in base.parameters()]
fis = fisher_diag(base, A)
ewc = lambda lam: lambda m: lam / 2 * sum(
(f * (p - s) ** 2).sum() for p, s, f in zip(m.parameters(), star, fis))
print(f"after A only : acc A {acc(base, A):.2f}")
for label, kw in [("no protection", {}),
("EWC lambda=100", {"penalty": ewc(100.0)}),
("EWC lambda=3000", {"penalty": ewc(3000.0)}),
("replay 100 of A", {"replay": (A[0][:100], A[1][:100])})]:
m = net(); m.load_state_dict(base.state_dict()); fit(m, B, **kw)
print(f"then B, {label:<15}: acc A {acc(m, A):.2f} acc B {acc(m, B):.2f}")
Output:
after A only : acc A 1.00
then B, no protection : acc A 0.60 acc B 0.99
then B, EWC lambda=100 : acc A 0.79 acc B 0.97
then B, EWC lambda=3000: acc A 0.87 acc B 0.93
then B, replay 100 of A: acc A 0.90 acc B 0.97
Read it as the stability-plasticity dial. Unprotected, A falls from 1.00 to 0.60. EWC at lambda 100 keeps 0.79; at 3000 it keeps 0.87 but B drops to 0.93, because the springs now resist the new task too. Replay of just 100 examples, 5% of A's data, keeps the most A while still learning B.
Gotcha: With plain SGD at learning rate 0.1, lambda values of 300 and above made this same setup diverge to chance on both tasks. The penalty's curvature is lambda times the Fisher, and a step size that is fine for the task loss can be far too large for that stiffness.