File size: 9,505 Bytes
18a8899
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
857044b
 
18a8899
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
857044b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18a8899
 
 
 
 
 
 
 
 
 
857044b
 
 
 
 
 
 
 
 
18a8899
 
 
 
 
 
857044b
 
 
 
 
 
 
18a8899
857044b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18a8899
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
"""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])