"""Core reimplementation of the continual-learning setup of "On the Theory of Continual Learning with Gradient Descent for Neural Networks" (ICML 2026, OpenReview l35QweVxgn / arXiv:2510.05573v2) Model (paper Sec. 2.1, matching the authors' notebook github.com/hosseinta2/continual-learning-with-neural-nets, `continual_learning_codes-XOR.ipynb`): Phi(w, x) = (1/sqrt(m)) * sum_i a_i * phi(x^T w_i), phi(t) = t^2/2, a_i in {+-1} fixed, w_i^{(0)} ~ N(0, I_d). Data (paper Eq. 3): task k is a d-dimensional XOR cluster with mu_+^k, mu_-^k orthogonal (across classes *and* across tasks), norms Theta(1/sqrt(d)), noise sigma = Theta(1/(polylog(d) sqrt(d))). Following the authors' notebook, task k uses coordinate pair (2k, 2k+1): mu_+^k = (e_{2k} + e_{2k+1})/sqrt(d), mu_-^k = (e_{2k} - e_{2k+1})/sqrt(d). Training: full-batch gradient descent, T steps per task, step size eta, sequential over K tasks with no replay and no regularization (Algorithm 1 of the paper). Everything is float64 numpy so that the numerical audits are exact to double precision. """ from __future__ import annotations import os import numpy as np # -------------------------------------------------------------------------- # losses. f(u) acts on the margin u = y * Phi(w, x). # -------------------------------------------------------------------------- def hinge(u): return np.maximum(1.0 - u, 0.0) def dhinge(u): return np.where(u < 1.0, -1.0, 0.0) def linear(u): """The 'linear loss' used in the authors' notebook: f(u) = -u. This is the hinge loss restricted to its linear region, which is where the paper's analysis operates (see the remark after Thm. 3).""" return -u def dlinear(u): return -np.ones_like(u) def logistic(u): # numerically stable log(1 + exp(-u)) return np.logaddexp(0.0, -u) def dlogistic(u): # d/du log(1+exp(-u)) = -sigmoid(-u) return -1.0 / (1.0 + np.exp(np.clip(u, -500, 500))) LOSSES = { "hinge": (hinge, dhinge), "linear": (linear, dlinear), "logistic": (logistic, dlogistic), } # -------------------------------------------------------------------------- # data # -------------------------------------------------------------------------- def task_means(d: int, k: int): """Orthogonal XOR mean pair for task k (0-indexed), norm 1/sqrt(d).""" if 2 * k + 1 >= d: raise ValueError(f"d={d} too small for {k + 1} orthogonal tasks") mp = np.zeros(d) mm = np.zeros(d) mp[2 * k] = 1.0 / np.sqrt(d) mp[2 * k + 1] = 1.0 / np.sqrt(d) mm[2 * k] = 1.0 / np.sqrt(d) mm[2 * k + 1] = -1.0 / np.sqrt(d) return mp, mm def sample_xor(d: int, k: int, n: int, sigma: float, rng: np.random.Generator): """n iid samples from the task-k XOR cluster distribution (Eq. 3). Balanced labels; within each class the two antipodal clusters are balanced. """ mp, mm = task_means(d, k) n1 = n // 2 n2 = n - n1 y = np.concatenate([np.ones(n1), -np.ones(n2)]) signs1 = np.where(np.arange(n1) < n1 // 2, 1.0, -1.0) signs2 = np.where(np.arange(n2) < n2 // 2, 1.0, -1.0) centres = np.concatenate( [signs1[:, None] * mp[None, :], signs2[:, None] * mm[None, :]], axis=0 ) x = centres + sigma * rng.standard_normal((n, d)) return x, y # -------------------------------------------------------------------------- # network # -------------------------------------------------------------------------- # Cap on the number of float64 entries in the (n, m) pre-activation matrix Z. # Z is the only object in this file whose size grows as n * m, and it is # consumed row-block by row-block, so bounding it costs nothing numerically # (the arithmetic is identical, just re-associated) while keeping the peak # resident set of a worker at ~ZBLOCK * 8 bytes. 4e6 entries = 32 MB. ZBLOCK = int(os.environ.get("CL_ZBLOCK", 4_000_000)) # Worker-pool size for the sweep drivers. This box has 12 cores but only # ~15 GB of RAM (much of it already spoken for), and an over-wide pool sent it # into swap-death twice, so the default is deliberately conservative. Raise # with CL_NPROC on a machine with headroom. NPROC = int(os.environ.get("CL_NPROC", 3)) def _row_block(m: int, n: int) -> int: """Number of samples per chunk so that the (block, m) matrix fits ZBLOCK.""" return max(1, min(n, ZBLOCK // max(1, m))) class QuadNet: """One-hidden-layer quadratic network with fixed +-1 output layer.""" def __init__(self, d: int, m: int, rng: np.random.Generator): self.d, self.m = d, m self.W = rng.standard_normal((m, d)) # w_i^{(0)} ~ N(0, I_d) self.a = rng.choice([-1.0, 1.0], size=m) self.W0 = self.W.copy() def out(self, X): """Phi(w, X), computed in row blocks so (n, m) is never materialized.""" n = X.shape[0] bs = _row_block(self.m, n) out = np.empty(n) scale = 0.5 / np.sqrt(self.m) for s in range(0, n, bs): Z = X[s:s + bs] @ self.W.T # (bs, m) out[s:s + bs] = scale * ((Z * Z) @ self.a) return out def dist_from_init(self): return float(np.linalg.norm(self.W - self.W0)) def gd_step(net: QuadNet, X, y, eta: float, dloss): """One full-batch GD step on (1/n) sum_i f(y_i Phi(w, x_i)). Returns the per-sample margins u = y * Phi(w, x). The gradient is accumulated over row blocks, so peak memory is O(ZBLOCK + m*d) rather than O(n*m); the result is bit-comparable to the unchunked version up to floating-point summation order. """ n = X.shape[0] m = net.m bs = _row_block(m, n) scale = 0.5 / np.sqrt(m) u = np.empty(n) G = np.zeros((m, net.d)) for s in range(0, n, bs): Xb = X[s:s + bs] yb = y[s:s + bs] Z = Xb @ net.W.T # (bs, m) ub = yb * (scale * ((Z * Z) @ net.a)) u[s:s + bs] = ub g = dloss(ub) * yb # dL/dPhi per sample, (bs,) # grad_{w_i} = (1/n) sum_j g_j (a_i / sqrt(m)) z_{ji} x_j Z *= g[:, None] G += Z.T @ Xb G *= net.a[:, None] / (n * np.sqrt(m)) net.W -= eta * G return u def eval_task(net: QuadNet, X, y, loss): out = net.out(X) u = y * out return float(np.mean(loss(u))), float(np.mean(u <= 0)) # -------------------------------------------------------------------------- # continual learning driver # -------------------------------------------------------------------------- def continual_run( d=50, m=1000, K=3, n=2500, T=200, eta=2.0, sigma_c=0.1, loss_name="linear", seed=0, n_test=2000, track_traj=False, n_first=None, ): """Run Algorithm 1 and record every quantity the theorems talk about. n_first: sample size for task 1 only (paper's Fig. 4 protocol, where the first task's n is held fixed while later tasks' n is varied). Returns a dict with, for every pair (k, j) with j >= k, the empirical loss and misclassification error of task k measured at w_j, plus the test-set counterparts, plus ||w_j - w_0|| and the cumulative training losses that appear in Theorem 4. """ loss, dloss = LOSSES[loss_name] rng = np.random.default_rng(seed) sigma = sigma_c / np.sqrt(d) ns = [n] * K if n_first is not None: ns[0] = n_first Xs, ys, Xte, yte = [], [], [], [] for k in range(K): xk, yk = sample_xor(d, k, ns[k], sigma, rng) Xs.append(xk) ys.append(yk) xt, yt = sample_xor(d, k, n_test, sigma, rng) Xte.append(xt) yte.append(yt) net = QuadNet(d, m, rng) # loss_at[j][k] = empirical loss of task k measured at w_j (after task j+1) loss_at = np.full((K, K), np.nan) err_at = np.full((K, K), np.nan) tloss_at = np.full((K, K), np.nan) terr_at = np.full((K, K), np.nan) dist = np.zeros(K) cum_train_loss = np.zeros(K) # sum_t Fhat_j(w_j^{(t)}), t = 0..T-1 traj = [] if track_traj else None for j in range(K): for t in range(T): u = gd_step(net, Xs[j], ys[j], eta, dloss) cum_train_loss[j] += float(np.mean(loss(u))) if track_traj: traj.append([eval_task(net, Xs[k], ys[k], loss)[0] for k in range(K)]) dist[j] = net.dist_from_init() for k in range(K): loss_at[j, k], err_at[j, k] = eval_task(net, Xs[k], ys[k], loss) tloss_at[j, k], terr_at[j, k] = eval_task(net, Xte[k], yte[k], loss) return dict( loss_at=loss_at, err_at=err_at, test_loss_at=tloss_at, test_err_at=terr_at, dist=dist, cum_train_loss=cum_train_loss, ns=ns, traj=(np.array(traj) if track_traj else None), Xs=Xs, ys=ys, net=net, cfg=dict(d=d, m=m, K=K, n=n, T=T, eta=eta, sigma_c=sigma_c, loss=loss_name, seed=seed, n_first=n_first), ) def train_forgetting(res, k): """F^tr_{k,K} = Fhat_k(w_K) - Fhat_k(w_k) (k 0-indexed here).""" K = res["cfg"]["K"] return float(res["loss_at"][K - 1, k] - res["loss_at"][k, k]) def test_forgetting(res, k): K = res["cfg"]["K"] return float(res["test_loss_at"][K - 1, k] - res["test_loss_at"][k, k]) def gen_gap(res, k): """Delayed generalization gap F_k(w_K) - Fhat_k(w_K).""" K = res["cfg"]["K"] return float(res["test_loss_at"][K - 1, k] - res["loss_at"][K - 1, k])